SpringAmqp 之路由连接工厂的使用

配置路由连接工厂

  /**
     * Routing Connection Factory
     * 1.3以后添加了{@link AbstractRoutingConnectionFactory},路由连接工厂,
     * 他提供了一种将connectionFactory和lookupKey建立映射关系的机制,这种映射关系是基于线程绑定的,
     * Spring AMQP提供了一个简单的实现类{@link SimpleRoutingConnectionFactory},可以通过在当前线程
     * 中使用SimpleResourceHolder将lookupKey和connectionFactory绑定起来,然后执行业务操作,
     * 业务操作完以后要记得解绑。
     *
     * @return
     */
    @Bean
    public ConnectionFactory routeConnectionFactory(){
        SimpleRoutingConnectionFactory simpleRoutingConnectionFactory = new SimpleRoutingConnectionFactory();

        Map targetConnectionFactories = new HashMap<>();
        targetConnectionFactories.put("lookupKey1",rabbitConnectionFactory1());
        targetConnectionFactories.put("lookupKey2",rabbitConnectionFactory2());
        simpleRoutingConnectionFactory.setTargetConnectionFactories(targetConnectionFactories);
        return simpleRoutingConnectionFactory;
    }

使用

public class MyService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void service(String lookupKey, String payload) {

   public void service(String lookupKey, String payload) {
        //设置当前线程lookupKey,内部由ThreadLocal实现
        SimpleResourceHolder.bind(rabbitTemplate.getConnectionFactory(), lookupKey);
        //业务操作会根据线程中的lookupKey从routeConnectionFactory的targetConnectionFactories中选择对应的connectionFactory
        rabbitTemplate.convertAndSend(payload);
        //操作完以后记得解绑。不影响线程的后序其他工厂操作
        SimpleResourceHolder.unbind(rabbitTemplate.getConnectionFactory());
    }
    }

}

 

你可能感兴趣的:(Spring,AMQP)