赞
踩
1.安装插件
2.启动rabbitmq
注:这里可以修改账号密码
3.防火墙配置端口
4.下载延时插件
Release v3.12.0 · rabbitmq/rabbitmq-delayed-message-exchange · GitHub
下载的rabbitmq插件的版本要和宝塔下载延时插件的要差不多 差太多的适配不上
我这里下载的rabbitmq插件是rabbitmq 3.12.4 延时插件下载的是Release v3.12.0
5.将下载好的延时插件放到/usr/lib/rabbitmq/plugins/中
6.打开终端执行命令
rabbitmq-plugins enable rabbitmq_delayed_message_exchange
7.开启权限
访问web页面 http://自己服务器地址:15672/
点击admin
进去点击set permission
8.java yml文件中spring:下添加rabbitmq配置
rabbitmq: host: 19.100.100.100 # 服务器的主机名或IP地址 port: 5672 # RabbitMQ服务器的端口号,默认是5672 username: guest # 也就是图二的账号密码 password: guest # 也就是图二的账号密码 listener: simple: retry: enabled: true # 开启消费者进行重试 max-attempts: 5 # 最大重试次数 initial-interval: 3000 # 重试时间间隔
9.java代码DEMO
相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
队列、交换机、key枚举 /** * queue、exchange、routingKey名称统一定义枚举 */ public class RabbitConst { // 请求队列 public static final String TEST_QUEUE = "test.queue"; // 请求交换机 public static final String TEST_EXCHANGE = "test.exchange"; // 请求key public static final String TEST_KEY = "test.key"; // 请求队列 public static final String TEST_DELAY_QUEUE = "test.delay.queue"; // 请求交换机 public static final String TEST_DELAY_EXCHANGE = "test.delay.exchange"; // 请求key public static final String TEST_DELAY_KEY = "test.delay.key"; }
生产者
/** * 生产者 */ @Component @Slf4j public class TestRabbitProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sender(String content){ JSONObject jsonObject = new JSONObject(); jsonObject.put("content", content); rabbitTemplate.convertAndSend(RabbitConst.TEST_EXCHANGE, RabbitConst.TEST_KEY, JSONObject.toJSONString(jsonObject)); } //延时队列 public void senderDelay(String content,Integer delayTime){ JSONObject jsonObject = new JSONObject(); jsonObject.put("content", content); rabbitTemplate.convertAndSend(RabbitConst.TEST_DELAY_EXCHANGE, RabbitConst.TEST_DELAY_KEY, JSONObject.toJSONString(jsonObject),message -> { message.getMessageProperties().setDelay(delayTime); log.info("发送延时消息时间:" + new Date() + ",延时: " + delayTime + "毫秒"); return message; }); } }
消费者
/** * 消费者 */ @Component @EnableRabbit @Slf4j public class TestRabbitConsumer { @Autowired private IAbutmentApiService abutmentApiService; @RabbitListener(queues = RabbitConst.TEST_QUEUE) @RabbitHandler public void receive(String msg) { log.info("MQ消费:msg: " + msg); System.out.println(msg); } @RabbitListener(queues = RabbitConst.TEST_DELAY_QUEUE) @RabbitHandler public void receiveDelay(String msg) { log.info("MQ消费延时队列:msg: " + msg); System.out.println(msg); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。