-
Notifications
You must be signed in to change notification settings - Fork 613
/
CachingConnectionFactory.java
1601 lines (1448 loc) · 52.1 KB
/
CachingConnectionFactory.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-2024 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.connection;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.springframework.amqp.AmqpApplicationContextClosedException;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.AmqpTimeoutException;
import org.springframework.amqp.rabbit.support.ActiveObjectCounter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.SmartLifecycle;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import com.rabbitmq.client.Address;
import com.rabbitmq.client.AlreadyClosedException;
import com.rabbitmq.client.BlockedListener;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import com.rabbitmq.client.impl.recovery.AutorecoveringChannel;
/**
* A {@link ConnectionFactory} implementation that (when the cache mode is {@link CacheMode#CHANNEL} (default)
* returns the same Connection from all {@link #createConnection()}
* calls, and ignores calls to {@link com.rabbitmq.client.Connection#close()} and caches
* {@link com.rabbitmq.client.Channel}.
* <p>
* By default, only one Channel will be cached, with further requested Channels being created and disposed on demand.
* Consider raising the {@link #setChannelCacheSize(int) "channelCacheSize" value} in case of a high-concurrency
* environment.
* <p>
* When the cache mode is {@link CacheMode#CONNECTION}, a new (or cached) connection is used for each
* {@link #createConnection()};
* connections are cached according to the {@link #setConnectionCacheSize(int) "connectionCacheSize" value}.
* Both connections and channels are cached in this mode.
* <p>
* <b>{@link CacheMode#CONNECTION} is not compatible with a Rabbit Admin that auto-declares queues etc.</b>
* <p>
* <b>NOTE: This ConnectionFactory requires explicit closing of all Channels obtained from its Connection(s).</b>
* This is the usual recommendation for native Rabbit access code anyway. However, with this ConnectionFactory, its use
* is mandatory in order to actually allow for Channel reuse. {@link Channel#close()} returns the channel to the
* cache, if there is room, or physically closes the channel otherwise.
*
* @author Mark Pollack
* @author Mark Fisher
* @author Dave Syer
* @author Gary Russell
* @author Artem Bilan
* @author Steve Powell
* @author Will Droste
* @author Leonardo Ferreira
*/
@ManagedResource
public class CachingConnectionFactory extends AbstractConnectionFactory
implements InitializingBean, ShutdownListener, SmartLifecycle {
private static final String UNUSED = "unused";
private static final int DEFAULT_CHANNEL_CACHE_SIZE = 25;
private static final String DEFAULT_DEFERRED_POOL_PREFIX = "spring-rabbit-deferred-pool-";
private static final int CHANNEL_EXEC_SHUTDOWN_TIMEOUT = 30;
/**
* Create a unique ID for the pool.
*/
private static final AtomicInteger threadPoolId = new AtomicInteger(); // NOSONAR lower case
private static final Set<String> txStarts = Set.of("basicPublish", "basicAck", "basicNack", "basicReject");
private static final Set<String> ackMethods = Set.of("basicAck", "basicNack", "basicReject");
private static final Set<String> txEnds = Set.of("txCommit", "txRollback");
private final ChannelCachingConnectionProxy connection = new ChannelCachingConnectionProxy(null);
/**
* The cache mode.
*/
public enum CacheMode {
/**
* Cache channels - single connection.
*/
CHANNEL,
/**
* Cache connections and channels within each connection.
*/
CONNECTION
}
/**
* The type of publisher confirms to use.
*/
public enum ConfirmType {
/**
* Use {@code RabbitTemplate#waitForConfirms()} or {@code waitForConfirmsOrDie()}
* within scoped operations.
*/
SIMPLE,
/**
* Use with {@code CorrelationData} to correlate confirmations with sent messages.
*/
CORRELATED,
/**
* Publisher confirms are disabled (default).
*/
NONE
}
private final Set<ChannelCachingConnectionProxy> allocatedConnections = new HashSet<>();
private final Map<ChannelCachingConnectionProxy, LinkedList<ChannelProxy>>
allocatedConnectionNonTransactionalChannels = new HashMap<>();
private final Map<ChannelCachingConnectionProxy, LinkedList<ChannelProxy>>
allocatedConnectionTransactionalChannels = new HashMap<>();
private final BlockingDeque<ChannelCachingConnectionProxy> idleConnections = new LinkedBlockingDeque<>();
private final Deque<ChannelProxy> cachedChannelsNonTransactional = new LinkedList<>(); // NOSONAR removeFirst()
private final Deque<ChannelProxy> cachedChannelsTransactional = new LinkedList<>(); // NOSONAR removeFirst()
private final Map<Connection, Semaphore> checkoutPermits = new HashMap<>();
private final Map<String, AtomicInteger> channelHighWaterMarks = new HashMap<>();
private final AtomicInteger connectionHighWaterMark = new AtomicInteger();
/**
* Synchronization lock for the shared Connection.
*/
private final Lock connectionLock = new ReentrantLock();
private final Condition connectionAvailableCondition = this.connectionLock.newCondition();
private final ActiveObjectCounter<Channel> inFlightAsyncCloses = new ActiveObjectCounter<>();
private final AtomicBoolean running = new AtomicBoolean();
private long channelCheckoutTimeout = 0;
private CacheMode cacheMode = CacheMode.CHANNEL;
private int channelCacheSize = DEFAULT_CHANNEL_CACHE_SIZE;
private int connectionCacheSize = 1;
private int connectionLimit = Integer.MAX_VALUE;
private ConfirmType confirmType = ConfirmType.NONE;
private boolean publisherReturns;
private PublisherCallbackChannelFactory publisherChannelFactory = PublisherCallbackChannelImpl.factory();
private boolean defaultPublisherFactory = true;
private volatile boolean active = true;
private volatile boolean initialized;
/**
* Executor used for channels if no explicit executor set.
*/
private volatile ExecutorService channelsExecutor;
private volatile boolean stopped;
/**
* Create a new CachingConnectionFactory initializing the hostname to be the value returned from
* InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception.
*/
public CachingConnectionFactory() {
this((String) null);
}
/**
* Create a new CachingConnectionFactory given a host name.
* @param hostname the host name to connect to
*/
public CachingConnectionFactory(@Nullable String hostname) {
this(hostname, com.rabbitmq.client.ConnectionFactory.DEFAULT_AMQP_PORT);
}
/**
* Create a new CachingConnectionFactory given a port on the hostname returned from
* InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception.
* @param port the port number
*/
public CachingConnectionFactory(int port) {
this(null, port);
}
/**
* Create a new CachingConnectionFactory given a host name
* and port.
* @param hostNameArg the host name to connect to
* @param port the port number
*/
public CachingConnectionFactory(@Nullable String hostNameArg, int port) {
super(newRabbitConnectionFactory());
String hostname = hostNameArg;
if (!StringUtils.hasText(hostname)) {
hostname = getDefaultHostName();
}
setHost(hostname);
setPort(port);
doSetPublisherConnectionFactory(new CachingConnectionFactory(getRabbitConnectionFactory(), true));
}
/**
* Create a new CachingConnectionFactory given a {@link URI}.
* @param uri the amqp uri configuring the connection
* @since 1.5
*/
public CachingConnectionFactory(URI uri) {
super(newRabbitConnectionFactory());
setUri(uri);
doSetPublisherConnectionFactory(new CachingConnectionFactory(getRabbitConnectionFactory(), true));
}
/**
* Create a new CachingConnectionFactory for the given target ConnectionFactory.
* @param rabbitConnectionFactory the target ConnectionFactory
*/
public CachingConnectionFactory(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) {
this(rabbitConnectionFactory, false);
}
/**
* Create a new CachingConnectionFactory for the given target ConnectionFactory.
* @param rabbitConnectionFactory the target ConnectionFactory
* @param isPublisherFactory true if this is the publisher sub-factory.
*/
private CachingConnectionFactory(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory,
boolean isPublisherFactory) {
super(rabbitConnectionFactory);
if (!isPublisherFactory) {
if (rabbitConnectionFactory.isAutomaticRecoveryEnabled()) {
rabbitConnectionFactory.setAutomaticRecoveryEnabled(false);
logger.warn("""
***
Automatic Recovery was Enabled in the provided connection factory;
while Spring AMQP is generally compatible with this feature, there
are some corner cases where problems arise. Spring AMQP
prefers to use its own recovery mechanisms; when this option is true, you may receive
'AutoRecoverConnectionNotCurrentlyOpenException's until the connection is recovered.
It has therefore been disabled; if you really wish to enable it, use
'getRabbitConnectionFactory().setAutomaticRecoveryEnabled(true)',
but this is discouraged.""");
}
super.setPublisherConnectionFactory(new CachingConnectionFactory(getRabbitConnectionFactory(), true));
}
else {
super.setPublisherConnectionFactory(null);
this.defaultPublisherFactory = false;
}
}
private static com.rabbitmq.client.ConnectionFactory newRabbitConnectionFactory() {
com.rabbitmq.client.ConnectionFactory connectionFactory = new com.rabbitmq.client.ConnectionFactory();
connectionFactory.setAutomaticRecoveryEnabled(false);
return connectionFactory;
}
@Override
public void setPublisherConnectionFactory(@Nullable AbstractConnectionFactory publisherConnectionFactory) {
super.setPublisherConnectionFactory(publisherConnectionFactory);
this.defaultPublisherFactory = false;
}
/**
* The number of channels to maintain in the cache. By default, channels are allocated on
* demand (unbounded) and this represents the maximum cache size. To limit the available
* channels, see {@link #setChannelCheckoutTimeout(long)}.
* @param sessionCacheSize the channel cache size.
* @see #setChannelCheckoutTimeout(long)
*/
public void setChannelCacheSize(int sessionCacheSize) {
Assert.isTrue(sessionCacheSize >= 1, "Channel cache size must be 1 or higher");
this.channelCacheSize = sessionCacheSize;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).setChannelCacheSize(sessionCacheSize); // NOSONAR
}
}
public int getChannelCacheSize() {
return this.channelCacheSize;
}
public CacheMode getCacheMode() {
return this.cacheMode;
}
public void setCacheMode(CacheMode cacheMode) {
Assert.isTrue(!this.initialized, "'cacheMode' cannot be changed after initialization.");
Assert.notNull(cacheMode, "'cacheMode' must not be null.");
this.cacheMode = cacheMode;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).setCacheMode(cacheMode); // NOSONAR
}
}
public int getConnectionCacheSize() {
return this.connectionCacheSize;
}
public void setConnectionCacheSize(int connectionCacheSize) {
Assert.isTrue(connectionCacheSize >= 1, "Connection cache size must be 1 or higher.");
this.connectionCacheSize = connectionCacheSize;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).setConnectionCacheSize(connectionCacheSize); // NOSONAR
}
}
/**
* Set the connection limit when using cache mode CONNECTION. When the limit is
* reached and there are no idle connections, the
* {@link #setChannelCheckoutTimeout(long) channelCheckoutTimeLimit} is used to wait
* for a connection to become idle.
* @param connectionLimit the limit.
* @since 1.5.5
*/
public void setConnectionLimit(int connectionLimit) {
Assert.isTrue(connectionLimit >= 1, "Connection limit must be 1 or higher.");
this.connectionLimit = connectionLimit;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).setConnectionLimit(connectionLimit); // NOSONAR
}
}
@Override
public boolean isPublisherConfirms() {
return ConfirmType.CORRELATED.equals(this.confirmType);
}
@Override
public boolean isPublisherReturns() {
return this.publisherReturns;
}
public void setPublisherReturns(boolean publisherReturns) {
this.publisherReturns = publisherReturns;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).setPublisherReturns(publisherReturns); // NOSONAR
}
}
@Override
public boolean isSimplePublisherConfirms() {
return this.confirmType.equals(ConfirmType.SIMPLE);
}
/**
* Set the confirm type to use; default {@link ConfirmType#NONE}.
* @param confirmType the confirm type.
* @since 2.2
*/
public void setPublisherConfirmType(ConfirmType confirmType) {
Assert.notNull(confirmType, "'confirmType' cannot be null");
this.confirmType = confirmType;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).setPublisherConfirmType(confirmType); // NOSONAR
}
}
/**
* Sets the channel checkout timeout. When greater than 0, enables channel limiting
* in that the {@link #channelCacheSize} becomes the total number of available channels per
* connection rather than a simple cache size. Note that changing the {@link #channelCacheSize}
* does not affect the limit on existing connection(s), invoke {@link #destroy()} to cause a
* new connection to be created with the new limit.
* <p>
* Since 1.5.5, also applies to getting a connection when the cache mode is CONNECTION.
* @param channelCheckoutTimeout the timeout in milliseconds; default 0 (channel limiting not enabled).
* @since 1.4.2
* @see #setConnectionLimit(int)
*/
public void setChannelCheckoutTimeout(long channelCheckoutTimeout) {
this.channelCheckoutTimeout = channelCheckoutTimeout;
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory())
.setChannelCheckoutTimeout(channelCheckoutTimeout); // NOSONAR
}
}
/**
* Set the factory to use to create {@link PublisherCallbackChannel} instances.
* @param publisherChannelFactory the factory.
* @since 2.1.6
*/
public void setPublisherChannelFactory(PublisherCallbackChannelFactory publisherChannelFactory) {
Assert.notNull(publisherChannelFactory, "'publisherChannelFactory' cannot be null");
this.publisherChannelFactory = publisherChannelFactory;
}
@Override
public int getPhase() {
return Integer.MIN_VALUE;
}
@Override
public void afterPropertiesSet() {
this.initialized = true;
if (this.cacheMode == CacheMode.CHANNEL) {
Assert.isTrue(this.connectionCacheSize == 1,
"When the cache mode is 'CHANNEL', the connection cache size cannot be configured.");
}
initCacheWaterMarks();
if (this.defaultPublisherFactory) {
((CachingConnectionFactory) getPublisherConnectionFactory()).afterPropertiesSet(); // NOSONAR
}
}
@Override
public void start() {
this.running.set(true);
}
@Override
public void stop() {
this.running.set(false);
resetConnection();
}
@Override
public boolean isRunning() {
return this.running.get();
}
private void initCacheWaterMarks() {
this.channelHighWaterMarks.put(ObjectUtils.getIdentityHexString(this.cachedChannelsNonTransactional),
new AtomicInteger());
this.channelHighWaterMarks.put(ObjectUtils.getIdentityHexString(this.cachedChannelsTransactional),
new AtomicInteger());
}
@Override
public void setConnectionListeners(List<? extends ConnectionListener> listeners) {
super.setConnectionListeners(listeners); // handles publishing sub-factory
// If the connection is already alive we assume that the new listeners want to be notified
if (this.connection.target != null) {
this.getConnectionListener().onCreate(this.connection);
}
}
@Override
public void addConnectionListener(ConnectionListener listener) {
super.addConnectionListener(listener); // handles publishing sub-factory
// If the connection is already alive we assume that the new listener wants to be notified
if (this.connection.target != null) {
listener.onCreate(this.connection);
}
}
private Channel getChannel(ChannelCachingConnectionProxy connection, boolean transactional) {
Semaphore permits = null;
if (this.channelCheckoutTimeout > 0) {
permits = obtainPermits(connection);
}
Deque<ChannelProxy> channelList = determineChannelList(connection, transactional);
ChannelProxy channel = null;
if (connection.isOpen()) {
channel = findOpenChannel(channelList, connection.channelListLock);
if (channel != null && logger.isTraceEnabled()) {
logger.trace("Found cached Rabbit Channel: " + channel);
}
}
if (channel == null) {
try {
channel = getCachedChannelProxy(connection, channelList, transactional);
}
catch (RuntimeException e) {
if (permits != null) {
permits.release();
if (logger.isDebugEnabled()) {
logger.debug("Could not get channel; released permit for " + connection + ", remaining:"
+ permits.availablePermits());
}
}
throw e;
}
}
return channel;
}
private Semaphore obtainPermits(ChannelCachingConnectionProxy connection) {
Semaphore permits;
permits = this.checkoutPermits.get(connection);
if (permits != null) {
try {
if (!permits.tryAcquire(this.channelCheckoutTimeout, TimeUnit.MILLISECONDS)) {
throw new AmqpTimeoutException("No available channels");
}
if (logger.isDebugEnabled()) {
logger.debug(
"Acquired permit for " + connection + ", remaining:" + permits.availablePermits());
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AmqpTimeoutException("Interrupted while acquiring a channel", e);
}
}
else {
throw new IllegalStateException("No permits map entry for " + connection);
}
return permits;
}
@Nullable
private ChannelProxy findOpenChannel(Deque<ChannelProxy> channelList, Lock channelListLock) {
ChannelProxy channel = null;
channelListLock.lock();
try {
while (!channelList.isEmpty()) {
channel = channelList.removeFirst();
if (logger.isTraceEnabled()) {
logger.trace(channel + " retrieved from cache");
}
if (channel.isOpen()) {
break;
}
else {
cleanUpClosedChannel(channel);
channel = null;
}
}
}
finally {
channelListLock.unlock();
}
return channel;
}
private void cleanUpClosedChannel(ChannelProxy channel) {
try {
Channel target = channel.getTargetChannel();
if (target != null) {
target.close();
/*
* To remove it from auto-recovery if so configured,
* and nack any pending confirms if PublisherCallbackChannel.
*/
}
}
catch (AlreadyClosedException e) {
if (logger.isTraceEnabled()) {
logger.trace(channel + " is already closed");
}
}
catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Unexpected Exception closing channel " + e.getMessage());
}
}
catch (TimeoutException e) {
if (logger.isWarnEnabled()) {
logger.warn("TimeoutException closing channel " + e.getMessage());
}
}
}
private Deque<ChannelProxy> determineChannelList(ChannelCachingConnectionProxy connection, boolean transactional) {
Deque<ChannelProxy> channelList;
if (this.cacheMode == CacheMode.CHANNEL) {
channelList = transactional ? this.cachedChannelsTransactional : this.cachedChannelsNonTransactional;
}
else {
channelList = transactional ? this.allocatedConnectionTransactionalChannels.get(connection)
: this.allocatedConnectionNonTransactionalChannels.get(connection);
}
if (channelList == null) {
throw new IllegalStateException("No channel list for connection " + connection);
}
return channelList;
}
private ChannelProxy getCachedChannelProxy(ChannelCachingConnectionProxy connection,
Deque<ChannelProxy> channelList, boolean transactional) {
Channel targetChannel = createBareChannel(connection, transactional);
if (logger.isDebugEnabled()) {
logger.debug("Creating cached Rabbit Channel from " + targetChannel);
}
getChannelListener().onCreate(targetChannel, transactional);
Class<?>[] interfaces;
if (ConfirmType.CORRELATED.equals(this.confirmType) || this.publisherReturns) {
interfaces = new Class<?>[] {ChannelProxy.class, PublisherCallbackChannel.class};
}
else {
interfaces = new Class<?>[] {ChannelProxy.class};
}
return (ChannelProxy) Proxy.newProxyInstance(ChannelProxy.class.getClassLoader(),
interfaces, new CachedChannelInvocationHandler(connection, targetChannel, channelList,
transactional));
}
private Channel createBareChannel(ChannelCachingConnectionProxy connection, boolean transactional) {
if (this.cacheMode == CacheMode.CHANNEL) {
if (!this.connection.isOpen()) {
this.connectionLock.lock();
try {
if (!this.connection.isOpen()) {
this.connection.notifyCloseIfNecessary();
}
if (!this.connection.isOpen()) {
this.connection.target = null;
createConnection();
}
}
finally {
this.connectionLock.unlock();
}
}
return doCreateBareChannel(this.connection, transactional);
}
else if (this.cacheMode == CacheMode.CONNECTION) {
if (!connection.isOpen()) {
this.connectionLock.lock();
try {
this.allocatedConnectionNonTransactionalChannels.get(connection).clear();
this.allocatedConnectionTransactionalChannels.get(connection).clear();
connection.notifyCloseIfNecessary();
refreshProxyConnection(connection);
}
finally {
this.connectionLock.unlock();
}
}
return doCreateBareChannel(connection, transactional);
}
return null; // NOSONAR doCreate will throw an exception
}
private Channel doCreateBareChannel(ChannelCachingConnectionProxy conn, boolean transactional) {
Channel channel = conn.createBareChannel(transactional);
if (!ConfirmType.NONE.equals(this.confirmType)) {
try {
channel.confirmSelect();
}
catch (IOException e) {
logger.error("Could not configure the channel to receive publisher confirms", e);
}
}
if ((ConfirmType.CORRELATED.equals(this.confirmType) || this.publisherReturns)
&& !(channel instanceof PublisherCallbackChannelImpl)) {
channel = this.publisherChannelFactory.createChannel(channel, getChannelsExecutor());
}
channel.addShutdownListener(this);
return channel; // NOSONAR - Simple connection throws exception
}
@Override
public final Connection createConnection() throws AmqpException {
if (this.stopped) {
throw new AmqpApplicationContextClosedException(
"The ApplicationContext is closed and the ConnectionFactory can no longer create connections.");
}
this.connectionLock.lock();
try {
if (this.cacheMode == CacheMode.CHANNEL) {
if (this.connection.target == null) {
this.connection.target = super.createBareConnection();
// invoke the listener *after* this.connection is assigned
if (!this.checkoutPermits.containsKey(this.connection)) {
this.checkoutPermits.put(this.connection, new Semaphore(this.channelCacheSize));
}
this.connection.closeNotified.set(false);
getConnectionListener().onCreate(this.connection);
}
return this.connection;
}
else if (this.cacheMode == CacheMode.CONNECTION) {
return connectionFromCache();
}
}
finally {
this.connectionLock.unlock();
}
return null; // NOSONAR - never reach here - exceptions
}
private Connection connectionFromCache() {
ChannelCachingConnectionProxy cachedConnection = findIdleConnection();
long now = System.currentTimeMillis();
if (cachedConnection == null && countOpenConnections() >= this.connectionLimit) {
cachedConnection = waitForConnection(now);
}
if (cachedConnection == null) {
if (countOpenConnections() >= this.connectionLimit
&& System.currentTimeMillis() - now >= this.channelCheckoutTimeout) {
throw new AmqpTimeoutException("Timed out attempting to get a connection");
}
cachedConnection = new ChannelCachingConnectionProxy(super.createBareConnection());
if (logger.isDebugEnabled()) {
logger.debug("Adding new connection '" + cachedConnection + "'");
}
this.allocatedConnections.add(cachedConnection);
this.allocatedConnectionNonTransactionalChannels.put(cachedConnection, new LinkedList<>());
this.channelHighWaterMarks.put(ObjectUtils.getIdentityHexString(
this.allocatedConnectionNonTransactionalChannels.get(cachedConnection)), new AtomicInteger());
this.allocatedConnectionTransactionalChannels.put(cachedConnection, new LinkedList<>());
this.channelHighWaterMarks.put(
ObjectUtils
.getIdentityHexString(this.allocatedConnectionTransactionalChannels.get(cachedConnection)),
new AtomicInteger());
this.checkoutPermits.put(cachedConnection, new Semaphore(this.channelCacheSize));
getConnectionListener().onCreate(cachedConnection);
}
else if (!cachedConnection.isOpen()) {
try {
refreshProxyConnection(cachedConnection);
}
catch (Exception e) {
this.idleConnections.addLast(cachedConnection);
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Obtained connection '" + cachedConnection + "' from cache");
}
}
return cachedConnection;
}
@Nullable
private ChannelCachingConnectionProxy waitForConnection(long now) {
ChannelCachingConnectionProxy cachedConnection = null;
while (cachedConnection == null && System.currentTimeMillis() - now < this.channelCheckoutTimeout) {
if (countOpenConnections() >= this.connectionLimit) {
try {
if (this.connectionAvailableCondition.await(this.channelCheckoutTimeout, TimeUnit.MILLISECONDS)) {
cachedConnection = findIdleConnection();
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AmqpException("Interrupted while waiting for a connection", e);
}
}
}
return cachedConnection;
}
/*
* Iterate over the idle connections looking for an open one. If there are no idle,
* return null, if there are no open idle, return the first closed idle so it can
* be reopened.
*/
@Nullable
private ChannelCachingConnectionProxy findIdleConnection() {
ChannelCachingConnectionProxy cachedConnection = null;
ChannelCachingConnectionProxy lastIdle = this.idleConnections.peekLast();
while (cachedConnection == null) {
cachedConnection = this.idleConnections.poll();
if (cachedConnection != null) {
if (!cachedConnection.isOpen()) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping closed connection '" + cachedConnection + "'");
}
cachedConnection.notifyCloseIfNecessary();
this.idleConnections.addLast(cachedConnection);
if (cachedConnection.equals(lastIdle)) {
// all the idled connections are closed.
cachedConnection = this.idleConnections.poll();
break;
}
cachedConnection = null;
}
}
else {
break;
}
}
return cachedConnection;
}
private void refreshProxyConnection(ChannelCachingConnectionProxy connection) {
connection.destroy();
connection.notifyCloseIfNecessary();
connection.target = super.createBareConnection();
connection.closeNotified.set(false);
getConnectionListener().onCreate(connection);
if (logger.isDebugEnabled()) {
logger.debug("Refreshed existing connection '" + connection + "'");
}
}
/**
* Close the underlying shared connection. Use {@link #resetConnection()} to close the
* connection while the application is still running.
* <p>
* As this bean implements DisposableBean, a bean factory will automatically invoke
* this on destruction of its cached singletons.
* <p>
* If called after the context is closed, the connection factory can no longer server
* up connections.
*/
@Override
public final void destroy() {
super.destroy();
resetConnection();
if (getContextStopped()) {
this.stopped = true;
this.connectionLock.lock();
try {
if (this.channelsExecutor != null) {
try {
if (!this.inFlightAsyncCloses.await(CHANNEL_EXEC_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
this.logger
.warn("Async closes are still in-flight: " + this.inFlightAsyncCloses.getCount());
}
this.channelsExecutor.shutdown();
if (!this.channelsExecutor.awaitTermination(CHANNEL_EXEC_SHUTDOWN_TIMEOUT, TimeUnit.SECONDS)) {
this.logger.warn("Channel executor failed to shut down");
}
}
catch (@SuppressWarnings(UNUSED) InterruptedException e) {
Thread.currentThread().interrupt();
}
finally {
this.channelsExecutor = null;
}
}
}
finally {
this.connectionLock.unlock();
}
}
}
/**
* Close the connection(s). This will impact any in-process operations. New
* connection(s) will be created on demand after this method returns. This might be
* used to force a reconnect to the primary broker after failing over to a secondary
* broker.
*/
@Override
public void resetConnection() {
this.connectionLock.lock();
try {
if (this.connection.target != null) {
this.connection.destroy();
}
this.allocatedConnections.forEach(ChannelCachingConnectionProxy::destroy);
this.channelHighWaterMarks.values().forEach(count -> count.set(0));
this.connectionHighWaterMark.set(0);
}
finally {
this.connectionLock.unlock();
}
if (this.defaultPublisherFactory) {
getPublisherConnectionFactory().resetConnection(); // NOSONAR
}
}
/*
* Reset the Channel cache and underlying shared Connection, to be reinitialized on next access.
*/
protected void reset(Deque<ChannelProxy> channels, Deque<ChannelProxy> txChannels,
Map<Channel, ChannelProxy> channelsAwaitingAcks) {
this.active = false;
closeAndClear(channels);
closeAndClear(txChannels);
closeChannels(channelsAwaitingAcks.values());
channelsAwaitingAcks.clear();
this.active = true;
}
protected void closeAndClear(Collection<ChannelProxy> theChannels) {
closeChannels(theChannels);
theChannels.clear();
}
protected void closeChannels(Collection<ChannelProxy> theChannels) {
for (ChannelProxy channel : theChannels) {
try {
channel.close();
}
catch (Exception ex) {
logger.trace("Could not close cached Rabbit Channel", ex);
}
}
}
@ManagedAttribute
public Properties getCacheProperties() {
Properties props = new Properties();
props.setProperty("cacheMode", this.cacheMode.name());
this.connectionLock.lock();
try {
props.setProperty("channelCacheSize", Integer.toString(this.channelCacheSize));
if (this.cacheMode.equals(CacheMode.CONNECTION)) {
props.setProperty("connectionCacheSize", Integer.toString(this.connectionCacheSize));
props.setProperty("openConnections", Integer.toString(countOpenConnections()));
props.setProperty("idleConnections", Integer.toString(this.idleConnections.size()));
props.setProperty("idleConnectionsHighWater", Integer.toString(this.connectionHighWaterMark.get()));
for (ChannelCachingConnectionProxy proxy : this.allocatedConnections) {
putConnectionName(props, proxy, ":" + proxy.getLocalPort());
}
for (Entry<ChannelCachingConnectionProxy, LinkedList<ChannelProxy>> entry :
this.allocatedConnectionTransactionalChannels.entrySet()) {
int port = entry.getKey().getLocalPort();
if (port > 0 && entry.getKey().isOpen()) {
LinkedList<ChannelProxy> channelList = entry.getValue();
props.put("idleChannelsTx:" + port, Integer.toString(channelList.size()));
props.put("idleChannelsTxHighWater:" + port, Integer.toString(
this.channelHighWaterMarks.get(ObjectUtils.getIdentityHexString(channelList)).get()));
}
}
for (Entry<ChannelCachingConnectionProxy, LinkedList<ChannelProxy>> entry :
this.allocatedConnectionNonTransactionalChannels.entrySet()) {
int port = entry.getKey().getLocalPort();
if (port > 0 && entry.getKey().isOpen()) {
LinkedList<ChannelProxy> channelList = entry.getValue();
props.put("idleChannelsNotTx:" + port, Integer.toString(channelList.size()));
props.put("idleChannelsNotTxHighWater:" + port, Integer.toString(
this.channelHighWaterMarks.get(ObjectUtils.getIdentityHexString(channelList)).get()));
}
}
}
else {
props.setProperty("localPort",
Integer.toString(this.connection.target == null ? 0 : this.connection.getLocalPort()));
props.setProperty("idleChannelsTx", Integer.toString(this.cachedChannelsTransactional.size()));
props.setProperty("idleChannelsNotTx", Integer.toString(this.cachedChannelsNonTransactional.size()));
props.setProperty("idleChannelsTxHighWater", Integer.toString(this.channelHighWaterMarks
.get(ObjectUtils.getIdentityHexString(this.cachedChannelsTransactional)).get()));
props.setProperty("idleChannelsNotTxHighWater", Integer.toString(this.channelHighWaterMarks
.get(ObjectUtils.getIdentityHexString(this.cachedChannelsNonTransactional)).get()));
putConnectionName(props, this.connection, "");
}
}
finally {
this.connectionLock.unlock();
}