1.引入rabbitmq依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId></dependency>
在application.yml中配置rabbitmq参数
spring: rabbitmq: host: xx.xx.xx.xx port: 5672 username: xxxx password: xxxx virtual-host: /xxxx queue: xxx
其中host
为rabbitmq的服务器地址,port为端口,username是用户名,password为密码,virtual-host为虚拟路径,queue为自定义的队列名称。
编写消息生产者
import org.springframework.amqp.core.AmqpTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;@Servicepublic class RabbitSender { @Autowired private AmqpTemplate amqpTemplate; @Value("${spring.rabbitmq.queue}") private String queue; public void send(String msg){ amqpTemplate.convertAndSend(queue, msg); } }
4.编写消息消费者
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.amqp.rabbit.annotation.RabbitHandler;import org.springframework.amqp.rabbit.annotation.RabbitListener;import org.springframework.stereotype.Component;@Componentpublic class RabbitReceiver { private Logger logger = LoggerFactory.getLogger(RabbitReceiver.class); @RabbitListener(queues = "${spring.rabbitmq.queue}") @RabbitHandler public void process(byte[] msg){ logger.info("msg:{}",new String(msg)); } }
作者:褪色的记忆1994
链接:https://www.jianshu.com/p/e24491b7dea5
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦