一、rabbitmq安装
二、引入maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>2.5.15</version> </dependency>
三、配置yml
spring: rabbitmq: host: localhost port: 5674 username: admin password: 123456 virtual-host: delayed_vhost # 创建对应的Virtual Hosts listener: simple: concurrency: 5 prefetch: 10 retry: enabled: true # 允许消息消费失败的重试 max-attempts: 3 # 消息最多消费次数3次 initial-interval: 2000 # 消息多次消费的间隔2秒
四、RabbitmqConfig
package com.base.framework.config; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.CustomExchange; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; @Configuration public class RabbitmqConfig { /** * 延时队列交换机 * 注意这里的交换机类型:CustomExchange * * @return */ @Bean public CustomExchange delayExchange() { Map<String, Object> args = new HashMap<>(); args.put("x-delayed-type", "direct"); //属性参数 交换机名称 交换机类型 是否持久化 是否自动删除 配置参数 return new CustomExchange("delay_exchange", "x-delayed-message", true, false, args); } /** * 延时队列 * * @return */ @Bean public Queue delayQueue() { //属性参数 队列名称 是否持久化 return new Queue("delay_queue", true); } /** * 给延时队列绑定交换机 * * @return */ @Bean public Binding cfgDelayBinding() { return BindingBuilder.bind(delayQueue()).to(delayExchange()).with("delay_key").noargs(); } }
五、配置RabbitListener
package com.base.system.listener; import com.base.common.core.domain.entity.SysUser; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Slf4j @Component public class UserRabbitListener { @RabbitListener(queues = "delay_queue") public void consumeMessage(SysUser user) { log.info("收到消息:" + user.getUserName()); } }
六、发送消息
private final RabbitTemplate rabbitTemplate; @GetMapping("createMessageTest") public String createMessageTest(@RequestParam Integer time) { SysUser sysUser = userService.selectUserById(1L); this.rabbitTemplate.convertAndSend( "delay_exchange", "delay_key", sysUser, message -> { message.getMessageProperties().setDelay(time); return message; } ); return "创建消息成功"; }
标签:return,springboot,队列,springframework,rabbitmq,org,import,public,amqp From: https://www.cnblogs.com/fyiyy/p/18379099