spring boot实战(第十四篇)整合RabbitMQ源码分析前言

前言

本篇开始讲述Spring Boot如何整合RabbitMQ(实际上Spring就整合了RabbitMQ)。

RabbitAdmin

在上篇中遗留AmqpAdmin没有讲解,现在来看下该部分代码
public AmqpAdmin amqpAdmin(CachingConnectionFactory connectionFactory) {
		return new RabbitAdmin(connectionFactory);
	}

创建RabbitAdmin实例,调用构造方法
	public RabbitAdmin(ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
		Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
		this.rabbitTemplate = new RabbitTemplate(connectionFactory);
	}

创建连接工厂、rabbitTemplate,其中ConnectionFactory采用上一篇中自定义bean
   public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses("127.0.0.1:5672");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setPublisherConfirms(true); //必须要设置
        return connectionFactory;
    }

为CachingConnectionFactory实例,其缓存模式为通道缓存
	private volatile CacheMode cacheMode = CacheMode.CHANNEL;

接下来看下RabbitAdmin类定义:
public class RabbitAdmin implements AmqpAdmin, ApplicationContextAware, InitializingBean {
...
}

实现接口AmqpAdmin(定义若干RabbitMQ操作父接口),这里需要强调的是InitializingBean,实现该接口则会调用afterPropertiesSet方法
public void afterPropertiesSet() {

		synchronized (this.lifecycleMonitor) {

			if (this.running || !this.autoStartup) {
				return;
			}

			if (this.connectionFactory instanceof CachingConnectionFactory &&
					((CachingConnectionFactory) this.connectionFactory).getCacheMode() == CacheMode.CONNECTION) {
				logger.warn("RabbitAdmin auto declaration is not supported with CacheMode.CONNECTION");
				return;
			}

			this.connectionFactory.addConnectionListener(new ConnectionListener() {

				// Prevent stack overflow...
				private final AtomicBoolean initializing = new AtomicBoolean(false);

				@Override
				public void onCreate(Connection connection) {
					if (!initializing.compareAndSet(false, true)) {
						// If we are already initializing, we don't need to do it again...
						return;
					}
					try {
						 
						initialize();
					}
					finally {
						initializing.compareAndSet(true, false);
					}
				}

				@Override
				public void onClose(Connection connection) {
				}

			});

			this.running = true;

		}
	}

synchronized
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值