当前项目用的是spring cloud,已封装好了RabbitMQ,但是只能访问、操作一套数据源,当需要操作多套mq的时候,默认的方式就不满足了。
以下是配置spring cloud rabbitmq,使其支持多套数据源的步骤。
1、在配置目录下新加“RabbitMqConfiguration.java”,如下:
package com.xxx.xx.x.configuration; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 目前线上有2套rabbitMQ,分别为php、java * phpConnectionFactory: php集群 */ @Configuration public class RabbitMqConfiguration { @Bean(name = "phpConnectionFactory") public ConnectionFactory phpConnectionFactory( @Value("${spring.rabbitmq.php.host}") String host, @Value("${spring.rabbitmq.php.port}") int port, @Value("${spring.rabbitmq.php.username}") String username, @Value("${spring.rabbitmq.php.password}") String password ) { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setHost(host); connectionFactory.setPort(port); connectionFactory.setUsername(username); connectionFactory.setPassword(password); return connectionFactory; } /** * 用法举例:@RabbitListener(queues = "bb_test", containerFactory = "phpQueueFactory") * * @param configurer * @param connectionFactory * @return */ @Bean(name = "phpQueueFactory") public SimpleRabbitListenerContainerFactory phpQueueFactory( SimpleRabbitListenerContainerFactoryConfigurer configurer, @Qualifier("phpConnectionFactory") ConnectionFactory connectionFactory ) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); return factory; } @Bean(name = "phpRabbitTemplate") public RabbitTemplate phpRabbitTemplate(@Qualifier("phpConnectionFactory") ConnectionFactory connectionFactory) { RabbitTemplate phpRabbitTemplate = new RabbitTemplate(connectionFactory); return phpRabbitTemplate; } }
2、生产者调用方式
@Autowired @Qualifier("phpRabbitTemplate") private RabbitTemplate rabbitTemplate; /** * 发送消息 * * @param message */ private void sendMessage(JSONObject message) { rabbitTemplate.convertAndSend(queueName, message); }
3、消费者调用方式
@RabbitListener(queues = "bb_test", containerFactory = "phpQueueFactory")
温馨提示:如果不指定队列,则连接默认的。
文章出自:https://www.daixiaorui.com/read/285.html 本站所有文章,除注明出处外皆为原创,转载请注明本文地址,版权所有。
gg修改器http://www.98sjj.com/ gg修改器免root版https://www.n012.cn/ gg修改器下载http://www.zavx.cn/
王者荣耀修改器http://www.98sjj.com/
喜欢你,始于颜值,陷于才华,忠于人品 https://coinzine.news
阿士大夫阿士大夫撒地方