文章目录
- 一、依赖配置引入
- 1. 引入SpringBoot整合RabbitMQ依赖
- 2. 生产者配置文件
- 3. 主配置
- 二、代码Conding
- 2.1. 生产者代码
- 2.2. 实体对象
- 2.3. 测试类
一、依赖配置引入
1. 引入SpringBoot整合RabbitMQ依赖
<!--springboot整合RabbitMQ依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>
2. 生产者配置文件
#RabbitMQ 连接信息
spring:rabbitmq:addresses: 127.0.0.1port: 5672username: adminpassword: admin#虚拟主机virtual-host: /admin#连接超时时间connection-timeout: 15000##开启 confirm 确认机制#发送确认 对应RabbitTemplate.ConfirmCallback接口#消息发送成功 有2个重要参数# ack 状态为true correlationId 全局唯一ID用于标识每一支队列publisher-confirms: true#开启 return 确认机制publisher-returns: true#设置为 true 后 消费者在消息没有被路由到合适队列情况下会被return监听,而不会自动删除#发送失败回退,对应RabbitTemplate.ReturnCallback接口template:mandatory: true
3. 主配置
package com.gblfy.springboot.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@ComponentScan({"com.gblfy.springboot.*"})
public class MainConfig {
}
二、代码Conding
2.1. 生产者代码
package com.gblfy.springboot.producer;import com.gblfy.springboot.entity.Order;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;import java.util.Map;@Component
public class RabbitMQSender {//自动注入RabbitTemplate模板类@Autowiredprivate RabbitTemplate rabbitTemplate;/*** MQ发送 字符串类型消息+额外的属性** @param message* @param properties* @throws Exception*///发送消息方法调用: 构建Message消息public void send(Object message, Map<String, Object> properties) throws Exception {//构造一个添加额外属性的容器 储存额外消息MessageHeaders mhs = new MessageHeaders(properties);Message msg = MessageBuilder.createMessage(message, mhs);//自动签收rabbitTemplate.setConfirmCallback(confirmCallback);//消息确认rabbitTemplate.setReturnCallback(returnCallback);//id + 时间戳 全局唯一CorrelationData correlationData = new CorrelationData("1234567890");rabbitTemplate.convertAndSend("exchange-1", "springboot.abc", msg, correlationData);}/*** 发送MQ 对象类型消息** @param order* @throws Exception*///发送消息方法调用: 构建自定义对象消息public void sendOrder(Order order) throws Exception {rabbitTemplate.setConfirmCallback(confirmCallback);rabbitTemplate.setReturnCallback(returnCallback);//id + 时间戳 全局唯一CorrelationData correlationData = new CorrelationData("0987654321");rabbitTemplate.convertAndSend("exchange-2", "springboot.ff", order, correlationData);}//回调函数: confirm确认final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {@Overridepublic void confirm(CorrelationData correlationData, boolean ack, String cause) {System.err.println("correlationData: " + correlationData);System.err.println("ack: " + ack);if (!ack) {System.err.println("异常处理....");}}};//回调函数: return返回final ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {@Overridepublic void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText,String exchange, String routingKey) {System.err.println("return exchange: " + exchange + ", routingKey: "+ routingKey + ", replyCode: " + replyCode + ", replyText: " + replyText);}};
}
2.2. 实体对象
package com.gblfy.springboot.entity;import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;import java.io.Serializable;@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Order implements Serializable {private String id;private String name;
}
2.3. 测试类
package com.gblfy.springboot;import com.gblfy.springboot.entity.Order;
import com.gblfy.springboot.producer.RabbitMQSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;@RunWith(SpringRunner.class)
@SpringBootTest
public class ProducerApplicationTests {@Testpublic void contextLoads() {}@Autowiredprivate RabbitMQSender rabbitMQSender;private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");@Testpublic void testSender1() throws Exception {Map<String, Object> properties = new HashMap<>();properties.put("number", "12345");properties.put("send_time", simpleDateFormat.format(new Date()));rabbitMQSender.send("Hello RabbitMQ For Spring Boot!", properties);}@Testpublic void testSender2() throws Exception {Order order = new Order("001", "第一个订单");rabbitMQSender.sendOrder(order);}
}