多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 简单测试 ## 定义队列 ~~~ package com.jdxia.rabbitmq; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; //定义队列 @Configuration public class RabbitConfig { @Bean public Queue helloQueue() { return new Queue("hello"); } } ~~~ ## 发送者 ~~~ package com.jdxia.rabbitmq.hello; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; //发送者 @Component public class HelloSender { //默认实现 @Autowired private AmqpTemplate rabbitTemplate; public void send() { String context = "hello " + new Date(); System.out.println("Sender : " + context); //转换并发送 this.rabbitTemplate.convertAndSend("hello", context); } } ~~~ ## 接收者 ~~~ package com.jdxia.rabbitmq.hello; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.util.Date; /** * 接收者 * RabbitListener,使⽤ queues 指明队列名称 */ @Component @RabbitListener(queues = "hello") public class HelloReceiver { /** * 标记具体接收方法 */ @RabbitHandler public void process(String hello) { //接收的消息 System.out.println("Receiver : " + hello); } } ~~~ ## 测试 ~~~ @Autowired private HelloSender helloSender; @Test public void test() throws InterruptedException { helloSender.send(); Thread.sleep(1000L); } ~~~