短视频电商系统,编写延迟消息实现代码
1、配置交换器和队列
import org.springframework.context.annotation.Configuration; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; /** * 延迟交换器和队列 */ @Configuration public class DelayedExchangeConfig { public static final String EXCHANGE_NAME = "myDelayedExchange"; public static final String QUEUE_NAME = "delayed.queue"; public static final String ROUTING_KEY = "delayed.routing.key"; @Bean public CustomExchange delayedExchange() { return new CustomExchange(EXCHANGE_NAME, "x-delayed-message", // 消息类型 true, // 是否持久化 false); // 是否自动删除 } @Bean public Queue delayedQueue() { return QueueBuilder.durable(QUEUE_NAME) .withArgument("x-delayed-type", "direct") .build(); } @Bean public Binding delayedBinding(Queue delayedQueue,CustomExchange delayedExchange) { return BindingBuilder.bind(delayedQueue()).to(delayedExchange()).with(ROUTING_KEY).noargs(); } }
2、定义消息发送方法
import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class DelayedMessageProducer { @Autowired private RabbitTemplate rabbitTemplate; @Scheduled(fixedDelay = 5000) public void sendDelayedMessage(String message) { rabbitTemplate.convertAndSend(DelayedExchangeConfig.EXCHANGE_NAME, DelayedExchangeConfig.ROUTING_KEY, message, messagePostProcessor -> { messagePostProcessor.getMessageProperties().setDelay(10000); // 设置延迟时间,单位毫秒 return messagePostProcessor; }); } }
3、发送延迟消息
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/delayed") public class DelayedMessageController { @Autowired private DelayedMessageProducer delayedMessageProducer; @GetMapping("/send") public String sendDirectMessage(@RequestParam String message) { delayedMessageProducer.sendDelayedMessage(message); return "Delayed message sent to Exchange: " + message; } }
4、接收延迟消息
import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class DelayedMessageConsumer { @RabbitListener(queues = DelayedExchangeConfig.QUEUE_NAME) public void receiveDelayedMessage(String message) { System.out.println("Received delayed message: " + message); } }
以上就是短视频电商系统,编写延迟消息实现代码, 更多内容欢迎关注之后的文章
标签:视频,springframework,annotation,org,import,message,电商,public,延迟 From: https://www.cnblogs.com/yunbaomengnan/p/18503619