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