记录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 * @email niunafei0315@163.com 13 * @date 2020/4/28 4:09 PM 14 */ 15 @Component 16 public class Sender { 17 18 /** 19 * spring整合的操作类 20 * Message 发送的消息对象 21 * void send(Message var1) throws AmqpException; 22 * <p> 23 * var1 路由键 Message 发送的消息对象 24 * void send(String var1, Message var2) throws AmqpException; 25 * <p> 26 * var1 指定交换器名称 var2 路由键 Message 发送的消息对象 27 * void send(String var1, String var2, Message var3) throws AmqpException; 28 * 29 * 30 * void convertAndSend() 方法不需要指定MessageProperties属性即可发布 31 */ 32 @Autowired 33 private RabbitTemplate rabbitTemplate; 34 35 36 public void send(String msg) { 37 Message message = new Message(msg.getBytes(), new MessageProperties()); 38 rabbitTemplate.send("test-queue-name", message); 39 } 40 }