SpringBoot 集成 RabbitMQ 消息队列

一、添加依赖

  • 创建 SpringBoot 项目时,勾选 Messaging—>RabbitMQ,自动添加
  • 或者在 pom.xml 文件添加依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>

二、在 Application.yml 配置文件中添加配置信息

spring:
	rabbitmq:
	    host: ip
	    port: 端口
	    username: 用户名
	    password: 密码
	
	cloud:
	  stream:
	    bindings:
	      input:
	        content-type: application/json
	        destination: "消息队列名"
	        consumer:
	          concurrency: 20
	      output:
	        content-type: application/json
	        destination: "消息队列名"
	        
mqEnabled: true

三、定义消息队列

@Component
public interface Processor {
    String INPUT  = "input";
    String OUTPUT = "output";


    @Input(INPUT)
    SubscribableChannel input();

    @Output(OUTPUT)
    MessageChannel output();
}

四、配置生产者

@Service
public class Producer {

    @Autowired(required = false)
    private Processor Processor;

    /**
     * 发送至mq
     * @param monitorInfo 要发送的消息
     * @return
     */
    public boolean sendMonitorInfo(MonitorInfo monitorInfo){
        boolean sendResult = processor.output().send(new GenericMessage<>(monitorInfo));
        return sendResult;
    }
}

五、配置消费者

@EnableBinding(value = Processor.class)
@ConditionalOnProperty(name = "mqEnabled" ,havingValue = "true")
public class Consumer {

    @Autowired
    private DoSomethingService doSomethingService;


    /**
     * 消费
     *
     * @param monitorInfo
     * @throws Exception
     */
    @StreamListener(Processor.INPUT)
    public void consume(MonitorInfo monitorInfo) {
        doSomethingService.doSomething(monitorInfo);
    }
}

六、编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MqTest {

    @Autowired
    private Processor processor;

    @Test
    public void sendMq() throws InterruptedException {
        Thread.sleep(2000);
        processor.Output().send(new GenericMessage<>("111"));
        Thread.sleep(2000);
    }
}

七、附图

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值