记录RabbitMQ的简单应用
1、springboot项目中引入maven包,也是springboot官方的插件
<dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> </dependency>
2、配置application.yml文件或者是properties文件
spring: application: #指定应用的名字 name: rabbit-add #配置rabbitmq rabbitmq: #链接主机 host: 127.0.0.1 #端口 port: 5672 #已经授权的用户账号密码 username: user password: user #指定的虚拟主机,默认/, virtual-host: my_vhost
3、如果想要发送消息就需要创建队列,接下来配置队列信息,注意:Queue引入的是springframework中的对象。
package com.niu.cloud.config; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author niunafei * @function * @email niunafei0315@163.com * @date 2020/4/28 4:06 PM */ @Configuration public class RabbitMqConfig { /** * 创建消息队列 * * @return */ @Bean public Queue queue() { //设置队列名称叫 test-queue-name return new Queue("test-queue-name"); } }
4、创建消息发送方对象,进行发送消息
1 package com.niu.cloud.modules; 2 3 import org.springframework.amqp.core.Message; 4 import org.springframework.amqp.core.MessageProperties; 5 import org.springframework.amqp.rabbit.core.RabbitTemplate; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Component; 8 9 /** 10 * @author niunafei 11 * @function 12 * 消息生产类 13 * @email niunafei0315@163.com 14 * @date 2020/4/28 4:09 PM 15 */ 16 @Component 17 public class Sender { 18 19 /** 20 * spring整合的操作类 21 * Message 发送的消息对象 22 * void send(Message var1) throws AmqpException; 23 * 24 * var1 指定队列名称 Message 发送的消息对象 25 * void send(String var1, Message var2) throws AmqpException; 26 * 27 * var1 指定交换机名称 var2 指定队列名称 Message 发送的消息对象 28 * void send(String var1, String var2, Message var3) throws AmqpException; 29 */ 30 @Autowired 31 private RabbitTemplate rabbitTemplate; 32 33 34 public void send(String msg){ 35 Message message = new Message(msg.getBytes(),new MessageProperties()); 36 rabbitTemplate.send("test-queue-name",message); 37 } 38 }
5、创建消息接受消费方,消费消息
1 package com.niu.cloud.modules; 2 3 import lombok.extern.slf4j.Slf4j; 4 import org.springframework.amqp.rabbit.annotation.RabbitListener; 5 import org.springframework.stereotype.Component; 6 7 /** 8 * @author niunafei 9 * @function 监听这 10 * @email niunafei0315@163.com 11 * @date 2020/4/28 4:15 PM 12 */ 13 @Component 14 @Slf4j 15 public class Receiver { 16 17 18 /** 19 * 指定监听队列的名字 20 */ 21 @RabbitListener(queues = "test-queue-name") 22 public void process(String msg) { 23 log.info("接受到消息:{}", msg); 24 } 25 }
6、进行简单测试即可。
原文:https://www.cnblogs.com/niunafei/p/12796347.html