/
LastValueQueue.java
443 lines (366 loc) · 13.4 KB
/
LastValueQueue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.core.server.impl;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.Message;
import org.apache.activemq.artemis.api.core.RoutingType;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.filter.Filter;
import org.apache.activemq.artemis.core.paging.cursor.PageSubscription;
import org.apache.activemq.artemis.core.persistence.StorageManager;
import org.apache.activemq.artemis.core.postoffice.PostOffice;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.server.QueueFactory;
import org.apache.activemq.artemis.core.server.ServerConsumer;
import org.apache.activemq.artemis.core.settings.HierarchicalRepository;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.core.transaction.Transaction;
import org.apache.activemq.artemis.utils.actors.ArtemisExecutor;
/**
* A queue that will discard messages if a newer message with the same
* {@link org.apache.activemq.artemis.core.message.impl.CoreMessage#HDR_LAST_VALUE_NAME} property value. In other words it only retains the last
* value
* <p>
* This is useful for example, for stock prices, where you're only interested in the latest value
* for a particular stock
*/
@SuppressWarnings("ALL")
public class LastValueQueue extends QueueImpl {
private final Map<SimpleString, HolderReference> map = new ConcurrentHashMap<>();
private final SimpleString lastValueKey;
public LastValueQueue(final long persistenceID,
final SimpleString address,
final SimpleString name,
final Filter filter,
final PageSubscription pageSubscription,
final SimpleString user,
final boolean durable,
final boolean temporary,
final boolean autoCreated,
final RoutingType routingType,
final Integer maxConsumers,
final Boolean exclusive,
final Integer consumersBeforeDispatch,
final Long delayBeforeDispatch,
final Boolean purgeOnNoConsumers,
final SimpleString lastValueKey,
final Boolean nonDestructive,
final boolean configurationManaged,
final ScheduledExecutorService scheduledExecutor,
final PostOffice postOffice,
final StorageManager storageManager,
final HierarchicalRepository<AddressSettings> addressSettingsRepository,
final ArtemisExecutor executor,
final ActiveMQServer server,
final QueueFactory factory) {
super(persistenceID, address, name, filter, pageSubscription, user, durable, temporary, autoCreated, routingType, maxConsumers, exclusive, nonDestructive, consumersBeforeDispatch, delayBeforeDispatch, purgeOnNoConsumers, configurationManaged, scheduledExecutor, postOffice, storageManager, addressSettingsRepository, executor, server, factory);
this.lastValueKey = lastValueKey;
}
@Override
public synchronized void addTail(final MessageReference ref, final boolean direct) {
if (scheduleIfPossible(ref)) {
return;
}
final SimpleString prop = ref.getLastValueProperty();
if (prop != null) {
HolderReference hr = map.get(prop);
if (hr != null) {
// We need to overwrite the old ref with the new one and ack the old one
replaceLVQMessage(ref, hr);
} else {
hr = new HolderReference(prop, ref);
map.put(prop, hr);
super.addTail(hr, direct);
}
} else {
super.addTail(ref, direct);
}
}
@Override
public synchronized void addHead(final MessageReference ref, boolean scheduling) {
SimpleString lastValueProp = ref.getLastValueProperty();
if (lastValueProp != null) {
HolderReference hr = map.get(lastValueProp);
if (hr != null) {
if (scheduling) {
// We need to overwrite the old ref with the new one and ack the old one
replaceLVQMessage(ref, hr);
} else {
// We keep the current ref and ack the one we are returning
super.referenceHandled(ref);
try {
super.acknowledge(ref);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorAckingOldReference(e);
}
}
} else {
hr = new HolderReference(lastValueProp, ref);
map.put(lastValueProp, hr);
super.addHead(hr, scheduling);
}
} else {
super.addHead(ref, scheduling);
}
}
@Override
public boolean allowsReferenceCallback() {
return false;
}
private void replaceLVQMessage(MessageReference ref, HolderReference hr) {
MessageReference oldRef = hr.getReference();
referenceHandled(ref);
try {
oldRef.acknowledge(null, AckReason.REPLACED, null);
} catch (Exception e) {
ActiveMQServerLogger.LOGGER.errorAckingOldReference(e);
}
hr.setReference(ref);
}
@Override
protected void refRemoved(MessageReference ref) {
if (isNonDestructive()) {
removeIfCurrent(ref);
}
super.refRemoved(ref);
}
@Override
public void acknowledge(final MessageReference ref, final AckReason reason, final ServerConsumer consumer) throws Exception {
if (isNonDestructive() && reason == AckReason.EXPIRED || reason == AckReason.KILLED ) {
removeIfCurrent(ref);
}
super.acknowledge(ref, reason, consumer);
}
private synchronized void removeIfCurrent(MessageReference ref) {
SimpleString lastValueProp = ref.getLastValueProperty();
if (lastValueProp != null) {
MessageReference current = map.get(lastValueProp);
if (current == ref) {
map.remove(lastValueProp);
}
}
}
@Override
QueueIterateAction createDeleteMatchingAction(AckReason ackReason) {
QueueIterateAction queueIterateAction = super.createDeleteMatchingAction(ackReason);
return new QueueIterateAction() {
@Override
public void actMessage(Transaction tx, MessageReference ref) throws Exception {
removeIfCurrent(ref);
queueIterateAction.actMessage(tx, ref);
}
};
}
@Override
public boolean isLastValue() {
return true;
}
@Override
public SimpleString getLastValueKey() {
return lastValueKey;
}
public synchronized Set<SimpleString> getLastValueKeys() {
return Collections.unmodifiableSet(map.keySet());
}
private static class HolderReference implements MessageReference {
private final SimpleString prop;
private volatile MessageReference ref;
private long consumerID;
private boolean hasConsumerID = false;
HolderReference(final SimpleString prop, final MessageReference ref) {
this.prop = prop;
this.ref = ref;
}
@Override
public void onDelivery(Consumer<? super MessageReference> callback) {
// HolderReference may be reused among different consumers, so we don't set a callback and won't support Runnables
}
MessageReference getReference() {
return ref;
}
@Override
public void handled() {
// We need to remove the entry from the map just before it gets delivered
ref.handled();
if (!ref.getQueue().isNonDestructive()) {
((LastValueQueue) ref.getQueue()).removeIfCurrent(this);
}
}
@Override
public Object getProtocolData() {
return ref.getProtocolData();
}
@Override
public void setProtocolData(Object data) {
ref.setProtocolData(data);
}
@Override
public void setAlreadyAcked() {
ref.setAlreadyAcked();
}
@Override
public boolean isAlreadyAcked() {
return ref.isAlreadyAcked();
}
void setReference(final MessageReference ref) {
this.ref = ref;
}
@Override
public MessageReference copy(final Queue queue) {
return ref.copy(queue);
}
@Override
public void decrementDeliveryCount() {
ref.decrementDeliveryCount();
}
@Override
public int getDeliveryCount() {
return ref.getDeliveryCount();
}
@Override
public Message getMessage() {
return ref.getMessage();
}
@Override
public long getMessageID() {
return ref.getMessageID();
}
@Override
public SimpleString getLastValueProperty() {
return prop;
}
@Override
public Queue getQueue() {
return ref.getQueue();
}
@Override
public long getScheduledDeliveryTime() {
return ref.getScheduledDeliveryTime();
}
@Override
public void incrementDeliveryCount() {
ref.incrementDeliveryCount();
}
@Override
public void setDeliveryCount(final int deliveryCount) {
ref.setDeliveryCount(deliveryCount);
}
@Override
public void setScheduledDeliveryTime(final long scheduledDeliveryTime) {
ref.setScheduledDeliveryTime(scheduledDeliveryTime);
}
@Override
public void acknowledge(Transaction tx) throws Exception {
ref.acknowledge(tx);
}
@Override
public void acknowledge(Transaction tx, ServerConsumer consumer) throws Exception {
ref.acknowledge(tx, consumer);
}
@Override
public void acknowledge(Transaction tx, AckReason reason, ServerConsumer consumer) throws Exception {
ref.acknowledge(tx, reason, consumer);
}
@Override
public void setPersistedCount(int count) {
ref.setPersistedCount(count);
}
@Override
public int getPersistedCount() {
return ref.getPersistedCount();
}
@Override
public boolean isPaged() {
return false;
}
/* (non-Javadoc)
* @see org.apache.activemq.artemis.core.server.MessageReference#acknowledge(org.apache.activemq.artemis.core.server.MessageReference)
*/
@Override
public void acknowledge() throws Exception {
ref.getQueue().acknowledge(this);
}
/* (non-Javadoc)
* @see org.apache.activemq.artemis.core.server.MessageReference#getMessageMemoryEstimate()
*/
@Override
public int getMessageMemoryEstimate() {
return ref.getMessage().getMemoryEstimate();
}
@Override
public void emptyConsumerID() {
this.hasConsumerID = false;
}
@Override
public void setConsumerId(long consumerID) {
this.hasConsumerID = true;
this.consumerID = consumerID;
}
@Override
public boolean hasConsumerId() {
return hasConsumerID;
}
@Override
public long getConsumerId() {
if (!this.hasConsumerID) {
throw new IllegalStateException("consumerID isn't specified: please check hasConsumerId first");
}
return this.consumerID;
}
@Override
public long getPersistentSize() throws ActiveMQException {
return ref.getPersistentSize();
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((map == null) ? 0 : map.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof LastValueQueue)) {
return false;
}
LastValueQueue other = (LastValueQueue) obj;
if (map == null) {
if (other.map != null) {
return false;
}
} else if (!map.equals(other.map)) {
return false;
}
return true;
}
}