springboot集成多个rabbitmq

springboot版本:1.5.19.RELEASE

Gradle版本:4.10

 

Gradle的build.gradle中增加引入

Java代码 

compile('org.springframework.boot:spring-boot-starter-amqp')  

 

application.yaml中增加配置

Yaml代码 

buddie:
  rabbitmq:
    consume:
      host: 127.0.0.1
      port: 5672
      username: admin
      password: admin
    produce:
      host: 127.0.0.1
      port: 5674
      username: admin
      password: admin

 

增加配置类,配置我们的两个rabbitMQ:

Java代码 

import org.springframework.amqp.core.*;
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 RabbitConfig {

    public ConnectionFactory rabbitConfiguration(String host, int port, String username, String password) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    @Bean("consumeRabbitConnectionFactory")
    @Primary
    public ConnectionFactory innerRabbitConfiguration(@Value("${buddie.rabbitmq.consume.host}") String host,
                                                      @Value("${buddie.rabbitmq.consume.port}") int port,
                                                      @Value("${buddie.rabbitmq.consume.username}") String username,
                                                      @Value("${buddie.rabbitmq.consume.password}") String password) {
        return this.rabbitConfiguration(host, port, username, password);
    }

    @Bean("consumeRabbitTemplate")
    @Primary
    public RabbitTemplate consumeRabbitTemplate(
            @Qualifier("consumeRabbitConnectionFactory") ConnectionFactory connectionFactory
    ) {
        return new RabbitTemplate(connectionFactory);
    }

    public SimpleRabbitListenerContainerFactory rabbitFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }

    @Bean("consumeRabbitFactory")
    public SimpleRabbitListenerContainerFactory consumeRabbitFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("consumeRabbitConnectionFactory") ConnectionFactory connectionFactory
    ) {
        return this.rabbitFactory(configurer, connectionFactory);
    }

    @Bean("produceRabbitConnectionFactory")
    public ConnectionFactory outerRabbitConfiguration(@Value("${buddie.rabbitmq.produce.host}") String host,
                                                      @Value("${buddie.rabbitmq.produce.port}") int port,
                                                      @Value("${buddie.rabbitmq.produce.username}") String username,
                                                      @Value("${buddie.rabbitmq.produce.password}") String password) {
        return this.rabbitConfiguration(host, port, username, password);
    }

    @Bean("produceRabbitTemplate")
    public RabbitTemplate produceRabbitTemplate(
            @Qualifier("produceRabbitConnectionFactory") ConnectionFactory connectionFactory
    ) {
        return new RabbitTemplate(connectionFactory);
    }

    @Bean("produceRabbitFactory")
    public SimpleRabbitListenerContainerFactory outerRabbitFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("produceRabbitConnectionFactory") ConnectionFactory connectionFactory
    ) {
        return this.rabbitFactory(configurer, connectionFactory);
    }

    @Bean
    public Queue topicQueueCreate() {
        return new Queue("topic.task");
    }


    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange("topic.exchange");
    }

    @Bean
    public Binding topicBindingCreate() {
        return BindingBuilder.bind(this.topicQueueCreate()).to(this.topicExchange()).with("topic.task.#");
    }

}

注意事项:

做为生产者,在启服时,并不会对连接rabbitMQ,更不会去创建Topic,Queue及绑定。

而作为消费者,在启服后,会连接rabbitMQ,并检查Queue是否有消息可消费。

所以应该将消费的rabbitMQ配置,加上@Primary,否则在rabbitMQ上没有对应的Queue时,报错,无法启动服务器

 

使用:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class MessageConsumeService {
    private static final Logger logger = LoggerFactory.getLogger(MessageConsumeService.class);
    @Resource(name = "produceRabbitTemplate")
    private RabbitTemplate outerRabbitTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queues = PropConstants.TOPIC_TASK, containerFactory = "consumeRabbitFactory")
    public void receiveTopicCreate(String srcMessage) {
        try {
            outerRabbitTemplate.convertAndSend("topic.exchange", "topic.task.#", srcMessage);
        } catch (Exception e) {
            logger.error("MessageConsumeService.receiveTopicCreate error", e);
        }
    }
}

 

转载于:https://my.oschina.net/buddie/blog/3015421

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot集成RabbitMQ可以通过以下步骤完成: 1. 添加Maven依赖:在pom.xml文件中添加RabbitMQSpring Boot Starter依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 配置RabbitMQ连接信息:在application.properties(或application.yml)文件中配置RabbitMQ的连接信息。 ```properties spring.rabbitmq.host=your_rabbitmq_host spring.rabbitmq.port=your_rabbitmq_port spring.rabbitmq.username=your_rabbitmq_username spring.rabbitmq.password=your_rabbitmq_password ``` 3. 创建RabbitMQ发送者:创建一个发送消息的类,使用`RabbitTemplate`发送消息到指定的交换机和队列。 ```java import org.springframework.amqp.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RabbitMQSender { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String exchange, String routingKey, Object message) { rabbitTemplate.convertAndSend(exchange, routingKey, message); } } ``` 4. 创建RabbitMQ接收者:创建一个接收消息的类,使用`@RabbitListener`注解监听指定的队列,处理接收到的消息。 ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class RabbitMQReceiver { @RabbitListener(queues = "your_queue_name") public void receiveMessage(Object message) { // 处理接收到的消息 System.out.println("Received message: " + message.toString()); } } ``` 5. 发送和接收消息:在需要发送或接收消息的地方调用对应的方法。 ```java @Autowired private RabbitMQSender rabbitMQSender; public void sendMessage() { rabbitMQSender.sendMessage("your_exchange_name", "your_routing_key", "Hello, RabbitMQ!"); } ``` 以上是基本的使用方式,你可以根据实际需求进行扩展和配置。注意,你还需要安装并启动RabbitMQ服务。 希望对你有所帮助!如果有任何疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值