Spring中配置多个RabbitMQ的步骤

最近在开发Spring项目,其中用到了多个RabbitMQ,现在总结如下。

如果要配置多个RabbitMQ,就将rabbitMq相关的xml中的配置再复制一份,然后创建对应的生产者消费者类即可。

1.pom.xml中进行配置,导入jar包:

<dependency>
  <groupId>org.springframework.amqp</groupId>
  <artifactId>spring-rabbit</artifactId>
  <version>1.3.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>com.rabbitmq</groupId>
  <artifactId>amqp-client</artifactId>
  <version>3.3.4</version>
</dependency>

 

2.创建rabbitmq的xml配置文件,路径例如:resources/context/context-rabbitMq.xml;这个路径与xml文件名可以自定义,只要spring配置文件中把这个xml包含了就行;内容如下:

<!-- 配置rabbitMq链接 -->
<bean id="connectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
  <property name="port" value="${port}"/>
  <property name="virtualHost" value="${vhost}"/>
  <property name="channelCacheSize" value="50"/>
  <property name="connectionTimeout" value="5000"/>
  <property name="addresses" value="${addresses}"/>
</bean>

<!-- 配置admin信息后,当前producer中的exchange和queue会在rabbitmq服务器上自动生成 -->
<rabbit:admin connection-factory="connectionFactory" />

<!-- 消息队列消费者 -->
<bean id="myConsumer" class="com.test.MyConsumer" />

<rabbit:listener-container connection-factory="connectionFactory">
  <rabbit:listener ref="myConsumer" queue-names="${queue}" />
</rabbit:listener-container>

<!-- rabbitMQ实例,生产者用 -->
<bean id="rabbitTemplate" class="org.springframework.amqp.rabbit.core.RabbitTemplate">
  <property name="connectionFactory" ref="connectionFactory" />
  <property name="channelTransacted" value="true" />
</bean>



<!-- 如果有多个mq,再复制一次上面的配置即可,bean的id设置成不同的,可以使用不同的链接信息 -->

 

3.编写properties配置文件,路径如:resources/properties/config.properties;路径与文件名可自定义,spring配置文件中把这个文件包含了就行,如:

<bean name="propertyConfiger" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
  <property name="ignoreResourceNotFound" value="true" />
  <property name="locations">
    <list>
      <value>classpath:properties/config.properties</value>
    </list>
  </property>
</bean>

“classpath:”指的就是resources文件夹。

config.properties内容如下,与rabbitmq中的${}对应:

host=10.111.11.111,10.111.11.112,10.111.11.113
port=5672
username=admin
password=admin
#交换机名,mq生产者用
exchange=e1.exchange
queue=q1.queue
vhost=v1.vhost

 

4.编写消费者类MyConsumer.java,这个类用来监听mq队列消息,如果队列中有数据,则拿出一个来处理。如下:

public class MyConsumer implements MessageListener {

  private static final Logger log = LoggerFactory.getLogger(MyConsumer.class);

  @Override
  public void onMessage(Message message){
    String msg = "";
    MyMsgBean bean = null;
    
    try{
      //这里有个小坑,下面会提到
      //msg = new String(message.getBody(), message.getMessageProperties().getContentEncoding());
      
      //获取mq中的消息,从byte[]转为string
      msg = new String(message.getBody());
      //项目中,这个msg是json格式的String,再把String转为bean,容易处理些
      bean = JSONObject.parseObject(msg, MyMsgBean.class);
      //TODO 以下省略处理步骤
    }
    catch(Exception e){
       log.error("mq消费者异常",e);
    }
  }
}

这个类在上方的context-rabbitMq.xml中配置过了(myConsumer),所以能实现自动监听mq队列并处理的功能。

 

5.编写生产者类MyProducer.java,这个类通过使用rabbitTemplate对象,把信息放入mq队列。如下:

public class MyProducer{
  
  private static final Logger log = LoggerFactory.geetLogger(MyProducer.class);
  
  //交换机名称
  @Value("${e1.exchange}")
  private String exchange;
  
  //@Autowired
  private RabbitTemplate rabbitTemplate;

  public void setRabbitTemplate(RabbitTemplate rabbitTemplate){
    this.rabbitTemplate = rabbitTemplate;
  }

  public RabbitTemplate getRabbitTemplate(){
    return this.rabbitTemplate;
  }


  public void sendMsg(String msg){
    Message info = MessageBuilder.withBody(msg.getBytes())
    .setContentType(MessageProperties.CONTENT_TYPE_JSON)
    .setContentEncoding("utf-8")    
    .build();
    
    try{

      rabbitTemplate.send(exchange,"",info);

    }catch(Exception e){
      log.error("生产者将信息放入mq失败!",e);
    } 
  }
}

这个类中的rabbitTemplate是第一步在xml中配置好的,所以能注入,用set方法注入的(也可以用注解注入,还可以用构造方法注入);

这个类本身也是在xml中配置的,然后其它类就可以注入这个类,调用这个类的sendMsg()方法把消息存入mq队列了(例如Controller.java类中注入这个类,然后给mq新增消息)

配置如:

<bean id="myProducer" class="com.test.MyProducer">
  <property name="rabbitTemplate" ref="rabbitTemplate"></property>  
</bean>

 

6.其它:

直接输入mq的ip,然后输入mq的账号密码,可以登录mq管理中心;

在这个界面,点击queues,找到自己在使用的队列,可以手动给队列添加信息;

具体如下:

(1)找到Publish message下拉框;

(2)Headers中可以写key与value,对应Message对象中的Headers字段。

(3)Properties中可以写key与value,对应Message对象中的某些字段,点击旁边的"?"查看有效果的key,区分大小写;例如:

content_encoding=utf-8

(4)Properties中可以写具体信息,对应Message对象的getBody()方法获得的内容,例如:

{"json":"123"}

 

7.rabbitmq相关文章

rabbitmq三种模式:https://blog.csdn.net/fxq8866/article/details/62049393

rabbitmq结构:https://blog.csdn.net/vipshop_fin_dev/article/details/81612935

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring Boot可以很容易地配置多个RabbitMQ实例。以下是配置多个RabbitMQ实例的步骤: 1. 在application.properties文件添加多个RabbitMQ实例的配置信息。例如: spring.rabbitmq.host=host1 spring.rabbitmq.port=5672 spring.rabbitmq.username=user1 spring.rabbitmq.password=password1 spring.rabbitmq.second.host=host2 spring.rabbitmq.second.port=5672 spring.rabbitmq.second.username=user2 spring.rabbitmq.second.password=password2 2. 创建多个RabbitTemplate和ConnectionFactory bean。例如: @Configuration public class RabbitMQConfig { @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setHost(env.getProperty("spring.rabbitmq.host")); connectionFactory.setPort(env.getProperty("spring.rabbitmq.port", Integer.class)); connectionFactory.setUsername(env.getProperty("spring.rabbitmq.username")); connectionFactory.setPassword(env.getProperty("spring.rabbitmq.password")); return connectionFactory; } @Bean public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); return template; } @Bean(name = "secondConnectionFactory") public ConnectionFactory secondConnectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory(); connectionFactory.setHost(env.getProperty("spring.rabbitmq.second.host")); connectionFactory.setPort(env.getProperty("spring.rabbitmq.second.port", Integer.class)); connectionFactory.setUsername(env.getProperty("spring.rabbitmq.second.username")); connectionFactory.setPassword(env.getProperty("spring.rabbitmq.second.password")); return connectionFactory; } @Bean(name = "secondRabbitTemplate") public RabbitTemplate secondRabbitTemplate() { RabbitTemplate template = new RabbitTemplate(secondConnectionFactory()); return template; } } 3. 在需要使用RabbitMQ的地方,注入对应的RabbitTemplate或ConnectionFactory bean即可。例如: @Autowired private RabbitTemplate rabbitTemplate; @Autowired @Qualifier("secondRabbitTemplate") private RabbitTemplate secondRabbitTemplate; 使用以上步骤,就可以在Spring Boot应用配置多个RabbitMQ实例了。 ### 回答2: 在Spring Boot配置多个RabbitMQ会让应用程序变得更加灵活,这意味着应用可以与多个RabbitMQ实例连接,并能够发送和接收消息。 Spring Boot通过在配置文件(application.properties或application.yml)定义多个RabbitMQ实例来实现多个RabbitMQ配置。下面是在同一应用程序配置两个RabbitMQ实例的示例: 在application.yml文件添加以下内容: ``` spring.rabbitmq.host=server1 spring.rabbitmq.port=5672 spring.rabbitmq.username=user1 spring.rabbitmq.password=password1 spring.rabbitmq.virtual-host=/vhost1 spring.rabbitmq.second.host=server2 spring.rabbitmq.second.port=5672 spring.rabbitmq.second.username=user2 spring.rabbitmq.second.password=password2 spring.rabbitmq.second.virtual-host=/vhost2 ``` 在上面的示例,我们定义了两个RabbitMQ实例,一个用于服务器1,另一个用于服务器2。对于每个实例,我们指定了名称,主机名,端口,用户名,密码和虚拟主机。 为了使用以上配置,我们需要通过@Resource注解或@Autowired注解在Java定义一个RabbitTemplate bean。同时在需要连接第二个RabbitMQ实例的地方指定使用哪个RabbitMQ实例即可。例如: ``` @SpringBootApplication public class DemoApplication implements CommandLineRunner { @Autowired private RabbitTemplate rabbitTemplate; @Autowired @Qualifier("secondRabbitTemplate") private RabbitTemplate secondRabbitTemplate; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String... args) throws Exception { rabbitTemplate.convertAndSend("queue1", "message1"); secondRabbitTemplate.convertAndSend("queue2", "message2"); } } ``` 在上面的代码,我们注入了两个不同的RabbitTemplate实例,分别用于发送到不同的RabbitMQ实例。我们可以使用这两个实例来发送消息到不同的队列。在这个例子,我们把“message1”发送到“queue1”,把“message2” 发送到“queue2”。 总之,配置多个RabbitMQ实例可以让Spring Boot应用程序与多个RabbitMQ连接,并实现更复杂的异构应用程序。我们只需要简单地在配置文件添加多个实例,并通过Java的@Resource或@Autowired注解即可使用。 ### 回答3: Spring Boot 是一种流行的 Java 框架,用于快速构建基于 Spring 框架的应用程序。RabbitMQ 是一个流行的开源消息队列,常用于构建分布式系统。Spring Boot 提供了对 RabbitMQ 的支持,并允许用户配置多个 RabbitMQ配置多个 RabbitMQ,可以通过在 application.properties 或 application.yml 文件添加多个 RabbitMQ配置来实现。如下所示: application.yml: ``` spring: rabbitmq: 1: host: localhost port: 5672 username: guest password: guest virtual-host: / 2: host: localhost port: 5673 username: guest password: guest virtual-host: / ... ``` application.properties: ``` spring.rabbitmq.1.host=localhost spring.rabbitmq.1.port=5672 spring.rabbitmq.1.username=guest spring.rabbitmq.1.password=guest spring.rabbitmq.1.virtual-host=/ spring.rabbitmq.2.host=localhost spring.rabbitmq.2.port=5673 spring.rabbitmq.2.username=guest spring.rabbitmq.2.password=guest spring.rabbitmq.2.virtual-host=/ ... ``` 其,`1` 和 `2` 表示 RabbitMQ 的标识符。我们可以根据需要添加更多的标识符。在我们的应用程序,我们可以使用以下方式注入多个RabbitMQ: ``` @Bean @Primary public ConnectionFactory connectionFactory1() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", 5672); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); return connectionFactory; } @Bean public RabbitTemplate rabbitTemplate1(ConnectionFactory connectionFactory1) { return new RabbitTemplate(connectionFactory1); } @Bean public SimpleMessageListenerContainer messageListenerContainer1( ConnectionFactory connectionFactory1) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory1); container.setQueueNames("queue1"); container.setDefaultRequeueRejected(false); container.setMessageListener(messageListenerAdapter1()); return container; } @Bean public MessageListenerAdapter messageListenerAdapter1() { return new MessageListenerAdapter(new MyMessageListener()); } @Bean public ConnectionFactory connectionFactory2() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost", 5673); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); return connectionFactory; } @Bean public RabbitTemplate rabbitTemplate2(ConnectionFactory connectionFactory2) { return new RabbitTemplate(connectionFactory2); } @Bean public SimpleMessageListenerContainer messageListenerContainer2( ConnectionFactory connectionFactory2) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory2); container.setQueueNames("queue2"); container.setDefaultRequeueRejected(false); container.setMessageListener(messageListenerAdapter2()); return container; } @Bean public MessageListenerAdapter messageListenerAdapter2() { return new MessageListenerAdapter(new MyMessageListener()); } ``` 这样,在我们的应用程序就可以使用`rabbitTemplate1`和`rabbitTemplate2`来发送消息,使用 `messageListenerContainer1`和`messageListenerContainer2`监听队列消息。 总结: 在 Spring Boot 配置多个 RabbitMQ 的过程,我们需要在 application.properties 或 application.yml 添加多个配置,注入多个 ConnectionFactory,RabbitTemplate 和 SimpleMessageListenerContainer 来进行发送和监听消息。同时,我们还需要根据实际情况调整配置,确保消息传递的正确性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

追逐梦想永不停

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

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

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

打赏作者

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

抵扣说明:

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

余额充值