SpringBoot 整合 RabbitMQ

本文详细介绍了如何使用Spring Boot框架整合RabbitMQ,包括引入依赖、配置启动注解、设置application.properties、创建配置类、实现生产者发送消息及消费者接收消息的全过程。

步骤一

pom.xml 引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!--<dependency>-->
  <!--<groupId>com.alibaba</groupId>-->
  <!--<artifactId>fastjson</artifactId>-->
  <!--<version>1.2.37</version>-->
<!--</dependency>-->

步骤二

启动类上,打上注解

@EnableRabbit

步骤三

application.properties 配置

spring.application.name=springboot-rabbitmq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

步骤四

配置类

//生产者配置
@Configuration
public class RabbitmqConfig {

	//Topic交换器
    @Bean
    public TopicExchange exchange() {
        return new TopicExchange("exchange");
    }
    
	//队列
    @Bean
    public Queue queue() {
        return new Queue("queue");
    }

	//如果前面定义了多个Queue或TopicExchange  可以用@Qualifier标明入参注入哪一个
    @Bean
    Binding bindingExchangeMessage(Queue queue,
                                   TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).
                with("routingKey");
    }
}

步骤五

生产者发消息

@Component
public class RabbitmqSender {

    @Autowired
    private AmqpTemplate amqpTemplate;
															//自定义一个pojo
    public void sendMessage(String exchange,String roukekey,Message content) {
        try {
            amqpTemplate.convertAndSend(exchange, roukekey,
            		//fastjson
                    JSONObject.toJSONString(content));
        }catch (Exception e) {

        }
    }
}

消费者消费

@Component
public class MessageListener {

    @RabbitListener(queues = "queue")
    public void process(String strmsg) {

        final Message message = JSONObject.parseObject(strmsg,Message.class);
       
    }
}

或者

@Component
@RabbitListener(queues = "queue")
public class MessageListener {

    @RabbitHandler
    public void process(String strmsg) {

        final Message message = JSONObject.parseObject(strmsg,Message.class);
       
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值