随笔

771 阅读1分钟

CachingConnectionFactory

public class CachingConnectionFactory extends AbstractConnectionFactory
		implements InitializingBean, ShutdownListener {
  • CachingConnectionFactory实现了InitializingBean和ShutdownListener接口。在初始化的时候的代码:
@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.publisherConnectionFactory != null) {
		this.publisherConnectionFactory.afterPropertiesSet();
	}
}
  • initCacheWaterMarks()方法中提到了cachedChannelsNonTransactional和cachedChannelsTransactional,这两个LinkedList是用来缓存cacheMode=CHANNEL的时候的事务channel和非事务的channel,同样在cacheMode=CONNECTION的时候,会有allocatedConnectionNonTransactionalChannels和allocatedConnectionTransactionalChannels缓存相应的channel。
  • 对每个channelList设置了水位线标记 ???
private void initCacheWaterMarks() {
	this.channelHighWaterMarks.put(ObjectUtils.getIdentityHexString(this.cachedChannelsNonTransactional),
			new AtomicInteger());
	this.channelHighWaterMarks.put(ObjectUtils.getIdentityHexString(this.cachedChannelsTransactional),
			new AtomicInteger());
}
private CachingConnectionFactory(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory,
			boolean isPublisherFactory) {
	super(rabbitConnectionFactory);
	if (!isPublisherFactory) {
		if (rabbitConnectionFactory.isAutomaticRecoveryEnabled()) {
			rabbitConnectionFactory.setAutomaticRecoveryEnabled(false);
			logger.warn("***\nAutomatic Recovery was Enabled in the provided connection factory;\n"
					+ "while Spring AMQP is generally compatible with this feature, there\n"
					+ "are some corner cases where problems arise. Spring AMQP\n"
					+ "prefers to use its own recovery mechanisms; when this option is true, you may receive\n"
					+ "'AutoRecoverConnectionNotCurrentlyOpenException's until the connection is recovered.\n"
					+ "It has therefore been disabled; if you really wish to enable it, use\n"
					+ "'getRabbitConnectionFactory().setAutomaticRecoveryEnabled(true)',\n"
					+ "but this is discouraged.");
		}
		this.publisherConnectionFactory = new CachingConnectionFactory(getRabbitConnectionFactory(), true);
		setPublisherConnectionFactory(this.publisherConnectionFactory);
	}
	else {
		this.publisherConnectionFactory = null;
	}
}

构造器中调用了父类的构造器。并且拿com.rabbitmq.client.ConnectionFactory创建了一个新的CachingConnectionFactory,set到了publisherConnectionFactory,用于???。

public AbstractConnectionFactory(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) {
    Assert.notNull(rabbitConnectionFactory, "Target ConnectionFactory must not be null");
    this.rabbitConnectionFactory = rabbitConnectionFactory;
}