SpringBoot项目中连接两个RabbitMq

今天在写项目的时候遇到新需求,一个mq的功能要使用我们公司的服务器的mq,一个mq的功能要使用部署的那边的服务器的mq,话不多说直接上代码。

配置文件application.yml:

  spring: 
      rabbitmq:
        yjdpeservice:
          host: xxx.xxx.xxx.xxx
          port: 5672
          username: admin
          password: admin
        yjservice:
          host: xxx.xxx.xxx.xxx
          port: 5672
          username: admin
          password: admin

配置类:

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
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;
import org.springframework.context.annotation.Primary;

@Configuration
public class RabbitPlusConfig {

    @Bean(name="mergeConnectionFactory")
    @Primary
    public ConnectionFactory MergeConnectionFactory(
            @Value("${spring.rabbitmq.yjdpeservice.host}") String host,
            @Value("${spring.rabbitmq.yjdpeservice.port}") int port,
            @Value("${spring.rabbitmq.yjdpeservice.username}") String username,
            @Value("${spring.rabbitmq.yjdpeservice.password}") String password
    ){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    @Bean(name="LocalConnectionFactory")
    public ConnectionFactory LocalConnectionFactory(
            @Value("${spring.rabbitmq.yjservice.host}") String host,
            @Value("${spring.rabbitmq.yjservice.port}") int port,
            @Value("${spring.rabbitmq.yjservice.username}") String username,
            @Value("${spring.rabbitmq.yjservice.password}") String password
    ){
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    @Bean(name="mergeRabbitTemplate")
    @Primary
    public RabbitTemplate mergeRabbitTemplate(
            @Qualifier("mergeConnectionFactory") ConnectionFactory connectionFactory
    ){
        RabbitTemplate yjdpRabbitTemplate = new RabbitTemplate(connectionFactory);
        return yjdpRabbitTemplate;
    }

    @Bean(name="LocalRabbitTemplate")
    public RabbitTemplate LocalRabbitTemplate(
            @Qualifier("LocalConnectionFactory") ConnectionFactory connectionFactory
    ){
        RabbitTemplate yjRabbitTemplate = new RabbitTemplate(connectionFactory);
        return yjRabbitTemplate;
    }

    @Bean(name="mergeFactory")
    public SimpleRabbitListenerContainerFactory mergeFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("mergeConnectionFactory") ConnectionFactory connectionFactory
    ) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }

    @Bean(name="LocalFactory")
    public SimpleRabbitListenerContainerFactory LocalFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("LocalConnectionFactory") ConnectionFactory connectionFactory
    ) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }


}

发送消息类:

import io.renren.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

@Api(tags = "测试双mq发送")
@RestController
@RequestMapping("rbt/mq")
public class RbtMqController {


    @Autowired
    @Qualifier(value = "mergeRabbitTemplate")
    private RabbitTemplate mergerabbitTemplate;

    @Autowired
    @Qualifier(value = "LocalRabbitTemplate")
    private RabbitTemplate LocalrabbitTemplate;


    @ApiOperation("测试发送mq")
    @PostMapping("/PostMq/{mqone}/{mqtwo}")
    public Object PostMq(@RequestParam("token") String token, @PathVariable String mqone, @PathVariable String mqtwo){

        mergerabbitTemplate.convertAndSend("CeshiQueue", (Object) mqone, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                long l = 40000;
                //设置定时发布的时间发送到延时队列 到时间后转交给死信队列
                message.getMessageProperties().setExpiration(String.valueOf(l));
                return message;

            }
        });

        String msgTwo = "success";
        LocalrabbitTemplate.convertAndSend("CeshiQueue", (Object) mqtwo, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                long l = 40000;
                //设置定时发布的时间发送到延时队列 到时间后转交给死信队列
                message.getMessageProperties().setExpiration(String.valueOf(l));
                return message;

            }
        });
        return R.ok();
    }

}

消费者端:

消费LocalFactory对应的mq中的my-dlx-queue-Ceshi

@Component
@RabbitListener(queues = "my-dlx-queue-Ceshi",containerFactory = "LocalFactory")
@Log4j2
public class locallistener {

    @RabbitHandler
    public void RegularlyAddAsCheckIn(String msg) throws Exception {
        log.info(new Date() + "::LocalFactory收到信息::" + msg);
    }
}

消费mergeFactoryFactory对应的mq中的my-dlx-queue-Ceshi

@Component
@RabbitListener(queues = "my-dlx-queue-Ceshi",containerFactory = "mergeFactory")
@Log4j2
public class mergerlistener {

    @RabbitHandler
    public void RegularlyAddAsCheckIn(String msg) throws Exception {
        log.info(new Date() + "::mergeFactory收到信息::" + msg);
    }

}

完事,实测有效。

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要在Spring Boot项目配置RabbitMQ,需要完成以下步骤: 1. 添加RabbitMQ的依赖包,例如在Maven添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 在application.properties或application.yml文件添加RabbitMQ的配置信息,例如: ``` spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 3. 在Spring Boot应用程序创建RabbitMQ连接工厂和RabbitMQ模板,例如: ``` @Configuration public class RabbitMQConfig { @Value("${spring.rabbitmq.host}") private String rabbitMqHost; @Value("${spring.rabbitmq.port}") private int rabbitMqPort; @Value("${spring.rabbitmq.username}") private String rabbitMqUsername; @Value("${spring.rabbitmq.password}") private String rabbitMqPassword; @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(rabbitMqHost, rabbitMqPort); connectionFactory.setUsername(rabbitMqUsername); connectionFactory.setPassword(rabbitMqPassword); return connectionFactory; } @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory()); return rabbitTemplate; } } ``` 在上面的代码,我们创建了一个使用RabbitMQ连接工厂和RabbitMQ模板的配置类,其连接工厂使用application.properties或application.yml文件的属性值来配置。 4. 在应用程序使用RabbitMQ模板发送和接收消息,例如: ``` @Autowired private RabbitTemplate rabbitTemplate; public void sendMyMessage(MyMessage message) { rabbitTemplate.convertAndSend("my-exchange", "my-routing-key", message); } @RabbitListener(queues = "my-queue") public void receiveMyMessage(MyMessage message) { System.out.println("Received message: " + message); } ``` 在上面的代码,我们使用RabbitMQ模板发送和接收消息,其发送的消息将被发送到名为“my-exchange”的交换机,并使用名为“my-routing-key”的路由键进行路由。接收方监听名为“my-queue”的队列,并在接收到消息时打印消息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲代码的小松

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值