自行百度如何安装rabbitmq
- 点击链接下载rabbitmq插件
- 找到
rabbitmq_delayed_message_exchange
,点击Releases
- 找到自己mq版本对应下载
- 移动到rabbitmq目录下
plugins
- 执行命令
rabbitmq-plugins.bat enable rabbitmq_delayed_message_exchange
安装插件
- 此时就会出现
x-delayed-message
-
创建一个交换机
-
引入maven
<!--2. rabbitmq--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
-
yml配置
java
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: 账号
password: 密码
virtual-host: 路径 默认是/
- 定义一些参数
java
public class RabbitMqConstant {
//类型
public static final String DELAY_TYPE = "x-delayed-message";
//交换机名称
public static final String EXCHANGE_TEST = "exchange.test";
//路由
public static final String ROUTING_TEST = "routing.test";
//队列
public static final String QUEUE_TEST = "queue.test";
}
- 代码块
java
@Service
public class TestServiceImpl implements TestService {
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
public void send() {
HashMap<Object, Object> socketData = new HashMap<>();
socketData.put("message", "收到消息");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
socketData.put("date", sdf1.format(new Date()));
rabbitTemplate.convertAndSend(RabbitMqConstant.EXCHANGE_TEST, RabbitMqConstant.ROUTING_TEST, new Gson().toJson(socketData), a -> {
a.getMessageProperties().setDelay(2000);//延迟2秒
return a;
});
}
@RabbitListener(bindings = @QueueBinding(
value = @Queue(RabbitMqConstant.QUEUE_TEST),
key = RabbitMqConstant.ROUTING_TEST,
exchange = @Exchange(value = RabbitMqConstant.EXCHANGE_TEST, type = RabbitMqConstant.DELAY_TYPE)
))
public void responseToUser(String content) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
String format = sdf1.format(new Date());
System.out.println("接受到消息时间----" + format);
HashMap<Object, Object> socketData = new Gson().fromJson(content, new TypeToken<HashMap<Object, Object>>() {
}.getType());
String date = String.valueOf(socketData.get("date"));
System.out.println("发送消息时间----" + date);
System.out.println("消息----" + content);
}
}