windows环境下安装RabbitMQ
注意事项:c盘下用户名一定不能为中文,不然无法运行
1、安装erlang并配置环境变量
1.1点击otp_win64_24.2.1.exe,一直点击next,选择安装位置
1.2 配置环境变量
新建系统变量名为:ERLANG_HOME 变量值为erlang安装地址
2.添加path环境变量 %ERLANG_HOME%\bin
1.1.3验证erlang是否安装成功
打开cmd,输入:erl,显示如下就安装成功
如果报错,就在用户变量中path也进行添加再次测试即可
2.安装RabbitMQ
2.1 双击下载的Rabbit安装包,一直next即可,安装完成后命令行打开安装目录下的sbin目录
2.2 安装管理界面插件
输入如下命令再运行:rabbitmq-plugins enable rabbitmq_management
2.3 看是否成功安装rabbitMQ
浏览器访问:http://127.0.0.1:15672
用户名:guest
密码:guest
3.springboot延时队列配置实现订单超时取消
3.1 导包
<!--rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
如图所示,新增一个延时交换机,一个延时队列,和一个死信交换机及死信队列。当订单创建完成同时向延时队列添加一个消息,当时间达到我们所预设过期时间时该消息将放入死信队列进行消费,即关闭订单
@Configuration
public class TopicRabbitConfig {
//交换机名称
public final static String DELAY_EXCHANGE_NAME = "order_delay";
public final static String DEATH_EXCHANGE_NAME = "order_death";
//队列名称同时也是路由键
public final static String TOPIC_DELAY = "delay";
public final static String TOPIC_DEATH = "death";
//死信路由键
private static final String DEATH_ROUTING_KEY = "msg.dlx";
//延时队列
@Bean
public Queue delayQueue() {
Map<String, Object> args = new HashMap<String, Object>();
// x-dead-letter-exchange 这里声明当前队列绑定的死信交换机
args.put("x-dead-letter-exchange",DEATH_EXCHANGE_NAME );
// x-dead-letter-routing-key 这里声明当前队列的死信路由key
args.put("x-dead-letter-routing-key", DEATH_ROUTING_KEY);
//过期时间15分钟
args.put("x-message-ttl", 900000);
// args.put("x-message-ttl", 10000);
return new Queue(TopicRabbitConfig.TOPIC_DELAY,true,false,false,args);
}
//死信队列
@Bean
public Queue deathQueue() {
return new Queue(TopicRabbitConfig.TOPIC_DEATH);
}
//延时交换机
@Bean
TopicExchange delayExchange() {
return new TopicExchange(DELAY_EXCHANGE_NAME);
}
//死信交换机
@Bean
TopicExchange deathExchange() {
return new TopicExchange(DEATH_EXCHANGE_NAME);
}
//绑定死信队列到死信交换机
@Bean
Binding bindingExchangeDeathMessage() {
return BindingBuilder.bind(deathQueue()).to(deathExchange()).with(DEATH_ROUTING_KEY);
}
//绑定延时队列到延时交换机
@Bean
Binding bindingExchangeDelayMessage() {
return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(TOPIC_DELAY);
}
编写消费者
@Service
@Slf4j
public class Message4Death {
@Autowired
private TradingShopOrderService orderService;
@RabbitListener(queues = "death")
public void dealDeathOrder(Long orderId) {
if (orderId != null) {
TradingShopOrder order = orderService.getEntity(orderId);
if (order != null) {
if (order.getStatus().equals("1")){
order.setStatus("0");
orderService.updateEntity(order);
log.info("订单号:"+order.getOrderNumber()+"过期");
}
}
}
}
}