首页 > 其他分享 >SpringBoot配置多个RabbitMq

SpringBoot配置多个RabbitMq

时间:2023-06-05 14:31:53浏览次数:29  
标签:connectionFactory SpringBoot 多个 RabbitMq springframework import org message publ


  • YML
rabbitmq:
    first:
      username: ${app.appkey}
      password: ${app.appkey}
      virtual-host: ${app.appid}
      addresses: x.x.x.x:5672,x.x.x.x:5672 #集群
    second:
      username: guest 
      password: guest
      virtual-host: /
      host: 127.0.0.1
      port: 5672
  • 配置源
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;

/**
 * RabbitMq多源配置
 *
 * @author Lenovo
 */
@Configuration
public class RabbitConfig {

    @Bean(name = "firstConnectionFactory")
    @Primary
    public ConnectionFactory firstConnectionFactory(
            @Value("${spring.rabbitmq.first.addresses}") String addresses,
            @Value("${spring.rabbitmq.first.username}") String username,
            @Value("${spring.rabbitmq.first.password}") String password,
            @Value("${spring.rabbitmq.first.virtual-host}") String virtualHost
    ) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();

        connectionFactory.setAddresses(addresses);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        return connectionFactory;
    }

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

    @Bean(name = "firstRabbitTemplate")
    @Primary
    public RabbitTemplate firstRabbitTemplate(
            @Qualifier("firstConnectionFactory") ConnectionFactory connectionFactory
    ) {
        RabbitTemplate firstRabbitTemplate = new RabbitTemplate(connectionFactory);
        return firstRabbitTemplate;
    }

    @Bean(name = "secondRabbitTemplate")
    public RabbitTemplate secondRabbitTemplate(
            @Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory
    ) {
        RabbitTemplate secondRabbitTemplate = new RabbitTemplate(connectionFactory);
        return secondRabbitTemplate;
    }


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

    @Bean(name = "secondFactory")
    public SimpleRabbitListenerContainerFactory secondFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory
    ) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }
}
  • 信道构建器
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;

/**
 * 信道构建器
 *
 * @author Lenovo
 */
@Configuration
public class CreateQueue {

    @Bean
    public String chargeQueue(@Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory) {
        try {
            connectionFactory.createConnection().createChannel(false).queueDeclare("test.add", true, false, false, null);
        }catch (IOException e){
            e.printStackTrace();
        }
        return "test.add";
    }
}
  • 信道监听器
package com.ciih.authcenter.client.mq;

import com.ciih.authcenter.manager.entity.Permission;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 信道监听器
 *
 * @author Lenovo
 */
@Slf4j
@Component
public class ListeningHandle {

    public static final String ENCODING = "UTF-8";

    @RabbitHandler
    @RabbitListener(queues = {RabbitConfig.USERS_ADD}, containerFactory = "firstFactory")
    @SneakyThrows
    public void onMessageUserAdd(Message message, Channel channel) {
        log.info("[listenerManualAck 监听的消息userAdd] - [{}]", new String(message.getBody(), ENCODING));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (
                IOException e) {
        }
    }

    @RabbitHandler
    @RabbitListener(queues = {RabbitConfig.USERS_UPDATE}, containerFactory = "firstFactory")
    @SneakyThrows
    public void onMessageUserUpdate(Message message, Channel channel) {
        log.info("[listenerManualAck 监听的消息userUpdate] - [{}]", new String(message.getBody(), ENCODING));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (
                IOException e) {
        }
    }

    @RabbitHandler
    @RabbitListener(queues = {RabbitConfig.USERS_DELETE}, containerFactory = "firstFactory")
    @SneakyThrows
    public void onMessageUserDelete(Message message, Channel channel) {
        log.info("[listenerManualAck 监听的消息userDelete] - [{}]", new String(message.getBody(), ENCODING));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (
                IOException e) {
        }
    }

    @RabbitHandler
    @RabbitListener(queues = {RabbitConfig.ORGS_ADD}, containerFactory = "firstFactory")
    @SneakyThrows
    public void onMessageOrgsAdd(Message message, Channel channel) {
        log.info("[listenerManualAck 监听的消息orgsAdd] - [{}]", new String(message.getBody(), ENCODING));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (
                IOException e) {
        }
    }

    @RabbitHandler
    @RabbitListener(queues = {RabbitConfig.ORGS_UPDATE}, containerFactory = "firstFactory")
    @SneakyThrows
    public void onMessageOrgsUpdate(Message message, Channel channel) {
        log.info("[listenerManualAck 监听的消息orgsUpdate] - [{}]", new String(message.getBody(), ENCODING));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (
                IOException e) {
        }
    }

    @RabbitHandler
    @RabbitListener(queues = {RabbitConfig.ORGS_DELETE}, containerFactory = "firstFactory")
    @SneakyThrows
    public void onMessageOrgsDelete(Message message, Channel channel) {
        log.info("[listenerManualAck 监听的消息orgsDelete] - [{}]", new String(message.getBody(), ENCODING));
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (
                IOException e) {
        }
    }

    @RabbitListener(queues = {"test.add"}, containerFactory = "secondFactory")
    @SneakyThrows
    public void hospitalAdd(List<Permission> permissions, Message message, Channel channel) {
        System.out.println(permissions);
    }
}
  • 发送消息
import com.ciih.authcenter.manager.entity.Permission;
import com.ciih.authcenter.manager.service.PermissionService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class Sender {

    @Resource
    PermissionService permissionService;

    @Resource(name = "secondRabbitTemplate")
    private RabbitTemplate secondRabbitTemplate;

    @GetMapping("test1")
    public void send1() {
        List<Permission> list = permissionService.lambdaQuery().last("limit 0, 10").list();
        this.secondRabbitTemplate.convertAndSend("test.add", list);
    }
}
  • 依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

标签:connectionFactory,SpringBoot,多个,RabbitMq,springframework,import,org,message,publ
From: https://blog.51cto.com/u_14121041/6415457

相关文章

  • springboot 项目打war包
    修改主类,参照以下格式EducationErverApplication.class@SpringBootApplication//war包启动类publicclassEducationErverApplicationextendsSpringBootServletInitializer{publicstaticvoidmain(String[]args){SpringApplication.run(EducationErve......
  • springboot 发送邮箱验证码
    0步骤总览开启邮箱的POP3/SMTP服务。新建springboot项目。导入依赖。配置配置文件。编写controller测试接口。postman中测试1开启邮箱的POP3/SMTP服务这里我用的网易邮箱,其它邮箱类似步骤,不清楚的可以百度。总之就是要打开pop3/smtp服务,如果按照我的方法......
  • springboot集成Knife4j
    1.springboot我用的2.7.X引入maven<!--整合Knife4j--><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency>......
  • SpringBoot中的定时任务的同步与异步
    SpringBoot中的定时任务的同步与异步你确定真的知道?授人以渔Java领域;架构知识;面试心得;互联网行业最新资讯定时任务调度功能在我们的开发中是非常常见的,随便举几个例子:定时清除一些过期的数据,定时发送邮件等等,实现定时任务调度的方式也十分多样,本篇文章主要学习各种实现定时任务......
  • RabbitMQ配置文件及环境变量
    http://www.rabbitmq.com/configure.htmlMechanismDescriptionConfigurationFile(s)definesserverandpluginsettingsforTCPlistenersandothernetworking-relatedsettingsTLSresourceconstraints(alarms)authenticationandauthorizationbackendsmessagestore......
  • SpringBoot中的MapStruct使用
    目的:MapStruct可以实现对象之间的转换一、引入依赖<!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--mapstruct--><dependency><groupId>org.m......
  • Springboot 链接DataSource前检查或创建库,并设置时区及sql_mode
    /**Copyright(c)2022.AsiacomTechnologyInc.Allrightsreserved*/importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Configuration;......
  • SpringBoot打包成WAR包的时候把第三方jar包打到LIB文件夹下和把第三方jar包打入到Spri
    SpringBoot打包成WAR包的时候把第三方jar包打到LIB文件夹下和把第三方jar包打入到SpringBootjar包中转载首先我们应该知道我们把SPRINGBOOT项目打包成WAR包和JAR包的时候分别需要何种插件我们最常用的把springBoot打成jar包的插件是下面这样的一个插件,这是把我们的springBoot......
  • springboot案列
    当创建多个springboot项目在同一个文件时,注意每一个springboot项目的serverport(端口)要不一样,否则会报错;另外要注意的是:在创建的springboot目录中;其他它文件的目录必须在springboot的项目的内部,否则会找不到指定的内容,报404错误 ......
  • RabbitMQ
    一、消息队列介绍MQ的全称是MessageQueue——消息队列。MQ是一种应用程序对应用程序的通信方法。MQ是消费者-生产者模型的一个典型的代表,一端往消息队列中不断写入消息,而另一端则可以读取队列中的消息。这样发布者和使用者都不用知道对方的存在。生产者-消费者模式是通过一......