-
Notifications
You must be signed in to change notification settings - Fork 619
/
RabbitTemplate.java
2913 lines (2568 loc) · 104 KB
/
RabbitTemplate.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.amqp.rabbit.core;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.amqp.AmqpConnectException;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.AmqpIOException;
import org.springframework.amqp.AmqpIllegalStateException;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.Address;
import org.springframework.amqp.core.AmqpMessageReturnedException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReceiveAndReplyCallback;
import org.springframework.amqp.core.ReceiveAndReplyMessageCallback;
import org.springframework.amqp.core.ReplyToAddressCallback;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.AbstractRoutingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ChannelProxy;
import org.springframework.amqp.rabbit.connection.ClosingRecoveryListener;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactoryUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.connection.PendingConfirm;
import org.springframework.amqp.rabbit.connection.PublisherCallbackChannel;
import org.springframework.amqp.rabbit.connection.RabbitAccessor;
import org.springframework.amqp.rabbit.connection.RabbitResourceHolder;
import org.springframework.amqp.rabbit.connection.RabbitUtils;
import org.springframework.amqp.rabbit.connection.ThreadChannelConnectionFactory;
import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.DirectReplyToMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.DirectReplyToMessageListenerContainer.ChannelHolder;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.support.ConsumerCancelledException;
import org.springframework.amqp.rabbit.support.DefaultMessagePropertiesConverter;
import org.springframework.amqp.rabbit.support.Delivery;
import org.springframework.amqp.rabbit.support.ListenerContainerAware;
import org.springframework.amqp.rabbit.support.MessagePropertiesConverter;
import org.springframework.amqp.rabbit.support.RabbitExceptionTranslator;
import org.springframework.amqp.rabbit.support.ValueExpression;
import org.springframework.amqp.rabbit.support.micrometer.RabbitMessageSenderContext;
import org.springframework.amqp.rabbit.support.micrometer.RabbitTemplateObservation;
import org.springframework.amqp.rabbit.support.micrometer.RabbitTemplateObservation.DefaultRabbitTemplateObservationConvention;
import org.springframework.amqp.rabbit.support.micrometer.RabbitTemplateObservationConvention;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.amqp.support.converter.SmartMessageConverter;
import org.springframework.amqp.support.postprocessor.MessagePostProcessorUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.context.expression.MapAccessor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.lang.Nullable;
import org.springframework.retry.RecoveryCallback;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.util.Assert;
import org.springframework.util.ErrorHandler;
import org.springframework.util.StringUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.Queue.DeclareOk;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.GetResponse;
import com.rabbitmq.client.Return;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
/**
* <p>
* Helper class that simplifies synchronous RabbitMQ access (sending and receiving messages).
* </p>
*
* <p>
* The default settings are for non-transactional messaging, which reduces the amount of data exchanged with the broker.
* To use a new transaction for every send or receive set the {@link #setChannelTransacted(boolean) channelTransacted}
* flag. To extend the transaction over multiple invocations (more efficient), you can use a Spring transaction to
* bracket the calls (with <code>channelTransacted=true</code> as well).
* </p>
*
* <p>
* The only mandatory property is the {@link #setConnectionFactory(ConnectionFactory) ConnectionFactory}. There are
* strategies available for converting messages to and from Java objects (
* {@link #setMessageConverter(MessageConverter) MessageConverter}) and for converting message headers (known as message
* properties in AMQP, see {@link #setMessagePropertiesConverter(MessagePropertiesConverter) MessagePropertiesConverter}
* ). The defaults probably do something sensible for typical use cases, as long as the message content-type is set
* appropriately.
* </p>
*
* <p>
* The "send" methods all have overloaded versions that allow you to explicitly target an exchange and a routing key, or
* you can set default values to be used in all send operations. The plain "receive" methods allow you to explicitly
* target a queue to receive from, or you can set a default value for the template that applies to all explicit
* receives. The convenience methods for send <b>and</b> receive use the sender defaults if no exchange or routing key
* is specified, but they always use a temporary queue for the receive leg, so the default queue is ignored.
* </p>
*
* @author Mark Pollack
* @author Mark Fisher
* @author Dave Syer
* @author Gary Russell
* @author Artem Bilan
* @author Ernest Sadykov
* @author Mark Norkin
* @author Mohammad Hewedy
* @author Alexey Platonov
* @author Leonardo Ferreira
*
* @since 1.0
*/
public class RabbitTemplate extends RabbitAccessor // NOSONAR type line count
implements BeanFactoryAware, RabbitOperations, ChannelAwareMessageListener, ApplicationContextAware,
ListenerContainerAware, PublisherCallbackChannel.Listener, BeanNameAware, DisposableBean {
private static final String UNCHECKED = "unchecked";
private static final String RETURN_CORRELATION_KEY = "spring_request_return_correlation";
/** Alias for amq.direct default exchange. */
private static final String DEFAULT_EXCHANGE = "";
private static final String DEFAULT_ROUTING_KEY = "";
private static final long DEFAULT_REPLY_TIMEOUT = 5000;
private static final long DEFAULT_CONSUME_TIMEOUT = 10000;
private static final String DEFAULT_ENCODING = "UTF-8";
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
/*
* Not static as normal since we want this TL to be scoped within the template instance.
*/
private final ThreadLocal<Channel> dedicatedChannels = new ThreadLocal<>();
private final AtomicInteger activeTemplateCallbacks = new AtomicInteger();
private final ConcurrentMap<Channel, RabbitTemplate> publisherConfirmChannels =
new ConcurrentHashMap<Channel, RabbitTemplate>();
private final Map<Object, PendingReply> replyHolder = new ConcurrentHashMap<Object, PendingReply>();
private final String uuid = UUID.randomUUID().toString();
private final AtomicInteger messageTagProvider = new AtomicInteger();
private final StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
private final ReplyToAddressCallback<?> defaultReplyToAddressCallback =
(request, reply) -> getReplyToAddress(request);
private final Map<ConnectionFactory, DirectReplyToMessageListenerContainer> directReplyToContainers =
new HashMap<>();
private final AtomicInteger containerInstance = new AtomicInteger();
private final Map<String, Object> consumerArgs = new HashMap<>();
private ApplicationContext applicationContext;
private String exchange = DEFAULT_EXCHANGE;
private String routingKey = DEFAULT_ROUTING_KEY;
// The default queue name that will be used for synchronous receives.
private String defaultReceiveQueue;
private long receiveTimeout = 0;
private long replyTimeout = DEFAULT_REPLY_TIMEOUT;
private MessageConverter messageConverter = new SimpleMessageConverter();
private MessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter();
private String encoding = DEFAULT_ENCODING;
private String replyAddress;
@Nullable
private ConfirmCallback confirmCallback;
private ReturnsCallback returnsCallback;
private Expression mandatoryExpression = new ValueExpression<Boolean>(false);
private String correlationKey = null;
private RetryTemplate retryTemplate;
private RecoveryCallback<?> recoveryCallback;
private Expression sendConnectionFactorySelectorExpression;
private Expression receiveConnectionFactorySelectorExpression;
private boolean useDirectReplyToContainer = true;
private boolean useTemporaryReplyQueues;
private Collection<MessagePostProcessor> beforePublishPostProcessors;
private Collection<MessagePostProcessor> afterReceivePostProcessors;
private CorrelationDataPostProcessor correlationDataPostProcessor;
private Expression userIdExpression;
private String beanName = "rabbitTemplate";
private Executor taskExecutor;
private boolean userCorrelationId;
private boolean usePublisherConnection;
private boolean noLocalReplyConsumer;
private ErrorHandler replyErrorHandler;
private boolean useChannelForCorrelation;
private boolean observationEnabled;
@Nullable
private RabbitTemplateObservationConvention observationConvention;
private volatile boolean usingFastReplyTo;
private volatile boolean evaluatedFastReplyTo;
private volatile boolean isListener;
private volatile boolean observationRegistryObtained;
/**
* Convenient constructor for use with setter injection. Don't forget to set the connection factory.
*/
public RabbitTemplate() {
initDefaultStrategies(); // NOSONAR - intentionally overridable; other assertions will check
}
/**
* Create a rabbit template with default strategies and settings.
*
* @param connectionFactory the connection factory to use
*/
public RabbitTemplate(ConnectionFactory connectionFactory) {
setConnectionFactory(connectionFactory);
}
/**
* Set up the default strategies. Subclasses can override if necessary.
*/
protected void initDefaultStrategies() {
setMessageConverter(new SimpleMessageConverter());
}
@Override
public final void setConnectionFactory(ConnectionFactory connectionFactory) {
super.setConnectionFactory(connectionFactory);
if (connectionFactory instanceof ThreadChannelConnectionFactory) {
this.usePublisherConnection = true;
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Enable observation via micrometer.
* @param observationEnabled true to enable.
* @since 3.0
*/
public void setObservationEnabled(boolean observationEnabled) {
this.observationEnabled = observationEnabled;
}
/**
* Set an observation convention; used to add additional key/values to observations.
* @param observationConvention the convention.
* @since 3.0
*/
public void setObservationConvention(RabbitTemplateObservationConvention observationConvention) {
this.observationConvention = observationConvention;
}
/**
* The name of the default exchange to use for send operations when none is specified. Defaults to <code>""</code>
* which is the default exchange in the broker (per the AMQP specification).
*
* @param exchange the exchange name to use for send operations
*/
public void setExchange(@Nullable String exchange) {
this.exchange = (exchange != null) ? exchange : DEFAULT_EXCHANGE;
}
/**
* @return the name of the default exchange used by this template.
*
* @since 1.6
*/
public String getExchange() {
return this.exchange;
}
/**
* The value of a default routing key to use for send operations when none is specified. Default is empty which is
* not helpful when using the default (or any direct) exchange, but fine if the exchange is a headers exchange for
* instance.
*
* @param routingKey the default routing key to use for send operations
*/
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
/**
* @return the default routing key used by this template.
*
* @since 1.6
*/
public String getRoutingKey() {
return this.routingKey;
}
/**
* The name of the default queue to receive messages from when none is specified explicitly.
* @param queue the default queue name to use for receive
* @since 2.1.2
*/
public void setDefaultReceiveQueue(String queue) {
this.defaultReceiveQueue = queue;
}
/**
* Return the configured default receive queue.
* @return the queue or null if not configured.
* @since 2.2.22
*/
@Nullable
public String getDefaultReceiveQueue() {
return this.defaultReceiveQueue;
}
/**
* The encoding to use when converting between byte arrays and Strings in message properties.
*
* @param encoding the encoding to set
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* The encoding used when converting between byte arrays and Strings in message properties.
* @return the encoding.
*/
public String getEncoding() {
return this.encoding;
}
/**
* An address for replies; if not provided, a temporary exclusive, auto-delete queue will
* be used for each reply, unless RabbitMQ supports 'amq.rabbitmq.reply-to' - see
* https://www.rabbitmq.com/direct-reply-to.html
* <p>The address can be a simple queue name (in which case the reply will be routed via the default
* exchange), or with the form {@code exchange/routingKey} to route the reply using an explicit
* exchange and routing key.
* @param replyAddress the replyAddress to set
*/
public synchronized void setReplyAddress(String replyAddress) {
this.replyAddress = replyAddress;
this.evaluatedFastReplyTo = false;
}
/**
* Specify the receive timeout in milliseconds when using {@code receive()} methods (for {@code sendAndReceive()}
* methods, refer to {@link #setReplyTimeout(long) replyTimeout}. By default, the value is zero, which
* means the {@code receive()} methods will return {@code null} immediately if there is no message
* available. Set to less than zero to wait for a message indefinitely.
* @param receiveTimeout the timeout.
* @since 1.5
*/
public void setReceiveTimeout(long receiveTimeout) {
this.receiveTimeout = receiveTimeout;
}
/**
* Specify the timeout in milliseconds to be used when waiting for a reply Message when using one of the
* sendAndReceive methods. The default value is defined as {@link #DEFAULT_REPLY_TIMEOUT}. A negative value
* indicates an indefinite timeout. Not used in the plain receive methods because there is no blocking receive
* operation defined in the protocol.
*
* @param replyTimeout the reply timeout in milliseconds
*
* @see #sendAndReceive(String, String, Message)
* @see #convertSendAndReceive(String, String, Object)
*/
public void setReplyTimeout(long replyTimeout) {
this.replyTimeout = replyTimeout;
}
/**
* Set the message converter for this template. Used to resolve Object parameters to convertAndSend methods and
* Object results from receiveAndConvert methods.
* <p>
* The default converter is a SimpleMessageConverter, which is able to handle byte arrays, Strings, and Serializable
* Objects depending on the message content type header.
*
* @param messageConverter The message converter.
*
* @see #convertAndSend
* @see #receiveAndConvert
* @see org.springframework.amqp.support.converter.SimpleMessageConverter
*/
public void setMessageConverter(MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
/**
* Set the {@link MessagePropertiesConverter} for this template. This converter is used to convert between raw byte
* content in the message headers and plain Java objects. In particular there are limitations when dealing with very
* long string headers, which hopefully are rare in practice, but if you need to use long headers you might need to
* inject a special converter here.
*
* @param messagePropertiesConverter The message properties converter.
*/
public void setMessagePropertiesConverter(MessagePropertiesConverter messagePropertiesConverter) {
Assert.notNull(messagePropertiesConverter, "messagePropertiesConverter must not be null");
this.messagePropertiesConverter = messagePropertiesConverter;
}
/**
* Return the properties converter.
* @return the converter.
* @since 2.0
*/
protected MessagePropertiesConverter getMessagePropertiesConverter() {
return this.messagePropertiesConverter;
}
/**
* Return the message converter for this template. Useful for clients that want to take advantage of the converter
* in {@link ChannelCallback} implementations.
*
* @return The message converter.
*/
public MessageConverter getMessageConverter() {
return this.messageConverter;
}
public void setConfirmCallback(ConfirmCallback confirmCallback) {
Assert.state(this.confirmCallback == null || this.confirmCallback.equals(confirmCallback),
"Only one ConfirmCallback is supported by each RabbitTemplate");
this.confirmCallback = confirmCallback;
}
/**
* Set a callback to receive returned messages.
* @param returnCallback the callback.
*/
public void setReturnsCallback(ReturnsCallback returnCallback) {
Assert.state(this.returnsCallback == null || this.returnsCallback.equals(returnCallback),
"Only one ReturnCallback is supported by each RabbitTemplate");
this.returnsCallback = returnCallback;
}
/**
* Set the mandatory flag when sending messages; only applies if a
* {@link #setReturnsCallback(ReturnsCallback) returnCallback} had been provided.
* @param mandatory the mandatory to set.
*/
public void setMandatory(boolean mandatory) {
this.mandatoryExpression = new ValueExpression<>(mandatory);
}
/**
* @param mandatoryExpression a SpEL {@link Expression} to evaluate against each
* request message, if a {@link #setReturnsCallback(ReturnsCallback) returnCallback} has
* been provided. The result of the evaluation must be a {@code boolean} value.
* @since 1.4
*/
public void setMandatoryExpression(Expression mandatoryExpression) {
Assert.notNull(mandatoryExpression, "'mandatoryExpression' must not be null");
this.mandatoryExpression = mandatoryExpression;
}
/**
* @param mandatoryExpression a SpEL {@link Expression} to evaluate against each
* request message, if a {@link #setReturnsCallback(ReturnsCallback) returnCallback} has
* been provided. The result of the evaluation must be a {@code boolean} value.
* @since 2.0
*/
public void setMandatoryExpressionString(String mandatoryExpression) {
Assert.notNull(mandatoryExpression, "'mandatoryExpression' must not be null");
this.mandatoryExpression = PARSER.parseExpression(mandatoryExpression);
}
/**
* A SpEL {@link Expression} to evaluate
* against each request message, if the provided {@link #getConnectionFactory()}
* is an instance of {@link AbstractRoutingConnectionFactory}.
* <p>
* The result of this expression is used as {@code lookupKey} to get the target
* {@link ConnectionFactory} from {@link AbstractRoutingConnectionFactory}
* directly.
* <p>
* If this expression is evaluated to {@code null}, we fallback to the normal
* {@link AbstractRoutingConnectionFactory} logic.
* <p>
* If there is no target {@link ConnectionFactory} with the evaluated {@code lookupKey},
* we fallback to the normal {@link AbstractRoutingConnectionFactory} logic
* only if its property {@code lenientFallback == true}.
* <p>
* This expression is used for {@code send} operations.
* @param sendConnectionFactorySelectorExpression a SpEL {@link Expression} to evaluate
* @since 1.4
*/
public void setSendConnectionFactorySelectorExpression(Expression sendConnectionFactorySelectorExpression) {
this.sendConnectionFactorySelectorExpression = sendConnectionFactorySelectorExpression;
}
/**
* A SpEL {@link Expression} to evaluate
* against each {@code receive} {@code queueName}, if the provided {@link #getConnectionFactory()}
* is an instance of {@link AbstractRoutingConnectionFactory}.
* <p>
* The result of this expression is used as {@code lookupKey} to get the target
* {@link ConnectionFactory} from {@link AbstractRoutingConnectionFactory}
* directly.
* <p>
* If this expression is evaluated to {@code null}, we fallback to the normal
* {@link AbstractRoutingConnectionFactory} logic.
* <p>
* If there is no target {@link ConnectionFactory} with the evaluated {@code lookupKey},
* we fallback to the normal {@link AbstractRoutingConnectionFactory} logic
* only if its property {@code lenientFallback == true}.
* <p>
* This expression is used for {@code receive} operations.
* @param receiveConnectionFactorySelectorExpression a SpEL {@link Expression} to evaluate
* @since 1.4
*/
public void setReceiveConnectionFactorySelectorExpression(Expression receiveConnectionFactorySelectorExpression) {
this.receiveConnectionFactorySelectorExpression = receiveConnectionFactorySelectorExpression;
}
/**
* If set to 'correlationId' (default) the correlationId property
* will be used; otherwise the supplied key will be used.
* @param correlationKey the correlationKey to set
*/
public void setCorrelationKey(String correlationKey) {
Assert.hasText(correlationKey, "'correlationKey' must not be null or empty");
if (!correlationKey.trim().equals("correlationId")) {
this.correlationKey = correlationKey.trim();
}
}
/**
* Add a {@link RetryTemplate} which will be used for all rabbit operations.
* @param retryTemplate The retry template.
*/
public void setRetryTemplate(RetryTemplate retryTemplate) {
this.retryTemplate = retryTemplate;
}
/**
* Add a {@link RecoveryCallback} which is used for the {@code retryTemplate.execute}.
* If {@link #retryTemplate} isn't provided {@link #recoveryCallback} is ignored.
* {@link RecoveryCallback} should produce result compatible with
* {@link #execute(ChannelCallback)} return type.
* @param recoveryCallback The retry recoveryCallback.
* @since 1.4
*/
public void setRecoveryCallback(RecoveryCallback<?> recoveryCallback) {
this.recoveryCallback = recoveryCallback;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));
this.evaluationContext.addPropertyAccessor(new MapAccessor());
}
/**
* Set {@link MessagePostProcessor}s that will be invoked immediately before invoking
* {@code Channel#basicPublish()}, after all other processing, except creating the
* {@link BasicProperties} from {@link MessageProperties}. May be used for operations
* such as compression. Processors are invoked in order, depending on {@code PriorityOrder},
* {@code Order} and finally unordered.
* @param beforePublishPostProcessors the post processor.
* @since 1.4.2
* @see #addBeforePublishPostProcessors(MessagePostProcessor...)
*/
public void setBeforePublishPostProcessors(MessagePostProcessor... beforePublishPostProcessors) {
Assert.notNull(beforePublishPostProcessors, "'beforePublishPostProcessors' cannot be null");
Assert.noNullElements(beforePublishPostProcessors, "'beforePublishPostProcessors' cannot have null elements");
this.beforePublishPostProcessors = MessagePostProcessorUtils.sort(Arrays.asList(beforePublishPostProcessors));
}
/**
* Add {@link MessagePostProcessor} that will be invoked immediately before invoking
* {@code Channel#basicPublish()}, after all other processing, except creating the
* {@link BasicProperties} from {@link MessageProperties}. May be used for operations
* such as compression. Processors are invoked in order, depending on {@code PriorityOrder},
* {@code Order} and finally unordered.
* <p>
* In contrast to {@link #setBeforePublishPostProcessors(MessagePostProcessor...)}, this
* method does not override the previously added beforePublishPostProcessors.
* @param beforePublishPostProcessors the post processor.
* @since 2.1.4
*/
public void addBeforePublishPostProcessors(MessagePostProcessor... beforePublishPostProcessors) {
Assert.notNull(beforePublishPostProcessors, "'beforePublishPostProcessors' cannot be null");
if (this.beforePublishPostProcessors == null) {
this.beforePublishPostProcessors = new ArrayList<>();
}
this.beforePublishPostProcessors.addAll(Arrays.asList(beforePublishPostProcessors));
this.beforePublishPostProcessors = MessagePostProcessorUtils.sort(this.beforePublishPostProcessors);
}
/**
* Remove the provided {@link MessagePostProcessor} from the {@link #beforePublishPostProcessors} list.
* @param beforePublishPostProcessor the MessagePostProcessor to remove.
* @return the boolean if the provided post processor has been removed.
* @since 2.1.4
* @see #addBeforePublishPostProcessors(MessagePostProcessor...)
*/
public boolean removeBeforePublishPostProcessor(MessagePostProcessor beforePublishPostProcessor) {
Assert.notNull(beforePublishPostProcessor, "'beforePublishPostProcessor' cannot be null");
if (this.beforePublishPostProcessors != null) {
return this.beforePublishPostProcessors.remove(beforePublishPostProcessor);
}
return false;
}
/**
* Set a {@link MessagePostProcessor} that will be invoked immediately after a {@code Channel#basicGet()}
* and before any message conversion is performed.
* May be used for operations such as decompression. Processors are invoked in order,
* depending on {@code PriorityOrder}, {@code Order} and finally unordered.
* @param afterReceivePostProcessors the post processor.
* @since 1.5
* @see #addAfterReceivePostProcessors(MessagePostProcessor...)
*/
public void setAfterReceivePostProcessors(MessagePostProcessor... afterReceivePostProcessors) {
Assert.notNull(afterReceivePostProcessors, "'afterReceivePostProcessors' cannot be null");
Assert.noNullElements(afterReceivePostProcessors, "'afterReceivePostProcessors' cannot have null elements");
this.afterReceivePostProcessors = MessagePostProcessorUtils.sort(Arrays.asList(afterReceivePostProcessors));
}
/**
* Return configured after receive {@link MessagePostProcessor}s or {@code null}.
* @return configured after receive {@link MessagePostProcessor}s or {@code null}.
* @since 2.1.5
*/
@Nullable
public Collection<MessagePostProcessor> getAfterReceivePostProcessors() {
return this.afterReceivePostProcessors != null
? Collections.unmodifiableCollection(this.afterReceivePostProcessors)
: null;
}
/**
* Add {@link MessagePostProcessor} that will be invoked immediately after a {@code Channel#basicGet()}
* and before any message conversion is performed.
* May be used for operations such as decompression. Processors are invoked in order,
* depending on {@code PriorityOrder}, {@code Order} and finally unordered.
* <p>
* In contrast to {@link #setAfterReceivePostProcessors(MessagePostProcessor...)}, this
* method does not override the previously added afterReceivePostProcessors.
* @param afterReceivePostProcessors the post processor.
* @since 2.1.4
*/
public void addAfterReceivePostProcessors(MessagePostProcessor... afterReceivePostProcessors) {
Assert.notNull(afterReceivePostProcessors, "'afterReceivePostProcessors' cannot be null");
if (this.afterReceivePostProcessors == null) {
this.afterReceivePostProcessors = new ArrayList<>();
}
this.afterReceivePostProcessors.addAll(Arrays.asList(afterReceivePostProcessors));
this.afterReceivePostProcessors = MessagePostProcessorUtils.sort(this.afterReceivePostProcessors);
}
/**
* Remove the provided {@link MessagePostProcessor} from the {@link #afterReceivePostProcessors} list.
* @param afterReceivePostProcessor the MessagePostProcessor to remove.
* @return the boolean if the provided post processor has been removed.
* @since 2.1.4
* @see #addAfterReceivePostProcessors(MessagePostProcessor...)
*/
public boolean removeAfterReceivePostProcessor(MessagePostProcessor afterReceivePostProcessor) {
Assert.notNull(afterReceivePostProcessor, "'afterReceivePostProcessor' cannot be null");
if (this.afterReceivePostProcessors != null) {
return this.afterReceivePostProcessors.remove(afterReceivePostProcessor);
}
return false;
}
/**
* Set a {@link CorrelationDataPostProcessor} to be invoked before publishing a message.
* Correlation data is used to correlate publisher confirms.
* @param correlationDataPostProcessor the post processor.
* @since 1.6.7
* @see #setConfirmCallback(ConfirmCallback)
*/
public void setCorrelationDataPostProcessor(CorrelationDataPostProcessor correlationDataPostProcessor) {
this.correlationDataPostProcessor = correlationDataPostProcessor;
}
/**
* By default, when the broker supports it and no
* {@link #setReplyAddress(String) replyAddress} is provided, send/receive
* methods will use Direct reply-to (https://www.rabbitmq.com/direct-reply-to.html).
* Setting this property to true will override that behavior and use
* a temporary, auto-delete, queue for each request instead.
* Changing this property has no effect once the first request has been
* processed.
* @param value true to use temporary queues.
* @since 1.6
*/
public void setUseTemporaryReplyQueues(boolean value) {
this.useTemporaryReplyQueues = value;
}
/**
* Set whether or not to use a {@link DirectReplyToMessageListenerContainer} when
* direct reply-to is available and being used. When false, a new consumer is created
* for each request (the mechanism used in versions prior to 2.0). Default true.
* @param useDirectReplyToContainer set to false to use a consumer per request.
* @since 2.0
* @see #setUseTemporaryReplyQueues(boolean)
*/
public void setUseDirectReplyToContainer(boolean useDirectReplyToContainer) {
this.useDirectReplyToContainer = useDirectReplyToContainer;
}
/**
* Set an expression to be evaluated to set the userId message property if it
* evaluates to a non-null value and the property is not already set in the
* message to be sent.
* See https://www.rabbitmq.com/validated-user-id.html
* @param userIdExpression the expression.
* @since 1.6
*/
public void setUserIdExpression(Expression userIdExpression) {
this.userIdExpression = userIdExpression;
}
/**
* Set an expression to be evaluated to set the userId message property if it
* evaluates to a non-null value and the property is not already set in the
* message to be sent.
* See https://www.rabbitmq.com/validated-user-id.html
* @param userIdExpression the expression.
* @since 1.6
*/
public void setUserIdExpressionString(String userIdExpression) {
this.userIdExpression = PARSER.parseExpression(userIdExpression);
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
/**
* Set a task executor to use when using a {@link DirectReplyToMessageListenerContainer}.
* @param taskExecutor the executor.
* @since 2.0
*/
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Set to true to use correlation id provided by the message instead of generating
* the correlation id for request/reply scenarios. The correlation id must be unique
* for all in-process requests to avoid cross talk.
* <p>
* <b>Users must therefore take create care to ensure uniqueness.</b>
* @param userCorrelationId true to use user correlation data.
*/
public void setUserCorrelationId(boolean userCorrelationId) {
this.userCorrelationId = userCorrelationId;
}
/**
* True if separate publisher connection(s) are used.
* @return true or false.
* @since 2.0.2
* @see #setUsePublisherConnection(boolean)
*/
public boolean isUsePublisherConnection() {
return this.usePublisherConnection;
}
/**
* To avoid deadlocked connections, it is generally recommended to use a separate
* connection for publishers and consumers (except when a publisher is participating
* in a consumer transaction). Default 'false'. When setting this to true, be careful
* in that a {@link RabbitAdmin} that uses this template will declare queues on the
* publisher connection; this may not be what you expect, especially with exclusive
* queues that might be consumed in this application.
* @param usePublisherConnection true to use a publisher connection.
* @since 2.0.2
*/
public void setUsePublisherConnection(boolean usePublisherConnection) {
this.usePublisherConnection = usePublisherConnection;
}
/**
* Set to true for a no-local consumer. Defaults to false.
* @param noLocalReplyConsumer true for a no-local consumer.
* @since 2.1
* @see AbstractMessageListenerContainer#setNoLocal(boolean)
* @see Channel#basicConsume(String, boolean, String, boolean, boolean, Map, com.rabbitmq.client.Consumer)
*/
public void setNoLocalReplyConsumer(boolean noLocalReplyConsumer) {
this.noLocalReplyConsumer = noLocalReplyConsumer;
}
/**
* When using a direct reply-to container for request/reply operations, set an error
* handler to be invoked when a reply delivery fails (e.g. due to a late reply).
* @param replyErrorHandler the reply error handler
* @since 2.0.11
* @see #setUseDirectReplyToContainer(boolean)
*/
public void setReplyErrorHandler(ErrorHandler replyErrorHandler) {
this.replyErrorHandler = replyErrorHandler;
}
/**
* When using direct reply-to, set this to true to avoid the server needing to
* send the correlation id in a reply header. Use the channel to correlate the reply
* to a request instead.
* @param useChannelForCorrelation true to use the channel.
* @since 2.3.7
*/
public void setUseChannelForCorrelation(boolean useChannelForCorrelation) {
this.useChannelForCorrelation = useChannelForCorrelation;
}
/**
* Invoked by the container during startup so it can verify the queue is correctly
* configured (if a simple reply queue name is used instead of exchange/routingKey).
* @return the queue name, if configured.
* @since 1.5
*/
@Override
@Nullable
public Collection<String> expectedQueueNames() {
this.isListener = true;
Collection<String> replyQueue = null;
if (this.replyAddress == null || this.replyAddress.equals(Address.AMQ_RABBITMQ_REPLY_TO)) {
throw new IllegalStateException("A listener container must not be provided when using direct reply-to");
}
else {
Address address = new Address(this.replyAddress);
if ("".equals(address.getExchangeName())) {
replyQueue = Collections.singletonList(address.getRoutingKey());
}
else {
if (logger.isInfoEnabled()) {
logger.info("Cannot verify reply queue because 'replyAddress' is not a simple queue name: "
+ this.replyAddress);
}
}
}
return replyQueue;
}
/**
* Gets unconfirmed correlation data older than age and removes them.
* @param age in milliseconds
* @return the collection of correlation data for which confirms have
* not been received or null if no such confirms exist.
*/
@Nullable
public Collection<CorrelationData> getUnconfirmed(long age) {
Set<CorrelationData> unconfirmed = new HashSet<>();
long cutoffTime = System.currentTimeMillis() - age;
for (Channel channel : this.publisherConfirmChannels.keySet()) {
Collection<PendingConfirm> confirms = ((PublisherCallbackChannel) channel).expire(this, cutoffTime);
for (PendingConfirm confirm : confirms) {
unconfirmed.add(confirm.getCorrelationData());
}
}
return unconfirmed.size() > 0 ? unconfirmed : null;
}
/**
* Gets unconfirmed messages count.
* @return The count of the messages that are not confirmed yet by RabbitMQ.
* @since 2.0
*/
public int getUnconfirmedCount() {
return this.publisherConfirmChannels.keySet()
.stream()
.mapToInt(channel -> ((PublisherCallbackChannel) channel).getPendingConfirmsCount(this))
.sum();
}
/**
* When using receive methods with a non-zero timeout, a
* {@link com.rabbitmq.client.Consumer} is created to receive the message. Use this
* property to add arguments to the consumer (e.g. {@code x-priority}).
* @param arg the argument name to pass into the {@code basicConsume} operation.
* @param value the argument value to pass into the {@code basicConsume} operation.
* @since 2.4.8
* @see #removeConsumerArg(String)
*/
public void addConsumerArg(String arg, Object value) {
this.consumerArgs.put(arg, value);
}
/**
* When using receive methods with a non-zero timeout, a
* {@link com.rabbitmq.client.Consumer} is created to receive the message. Use this
* method to remove an argument from those passed into the {@code basicConsume}
* operation.
* @param arg the argument name.
* @return the previous value.
* @since 2.4.8
* @see #addConsumerArg(String, Object)
*/
public Object removeConsumerArg(String arg) {
return this.consumerArgs.remove(arg);
}
@Override
public void start() {
doStart();
}
/**
* Perform additional start actions.
* @since 2.0
*/
protected void doStart() {
// NOSONAR
}
@Override
public void stop() {