一、项目配置
1)引入maven坐标
<!--amqp--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId><version>2.0.3.RELEASE</version></dependency>
2)application.yml加入RabbitMQ的连接配置
spring.rabbitmq.host: localhostspring.rabbitmq.port: 5672spring.rabbitmq.username: guestspring.rabbitmq.password: guest
二、消息的发送和接收
1)创建指定名称的消息队列
@Configurationpublic class RabbitConfig {@Beanpublic Queue helloQueue() {return new Queue("hello");}}
2)创建消息接收者
@Component@RabbitListener(queues = "hello")public class Receiver {@RabbitHandlerpublic void process(String hello) {System.out.println("Receiver : " + hello);}}
3)创建消息发送着
@Componentpublic class Sender {@Autowiredprivate AmqpTemplate rabbitTemplate;public void send() {String context = "hello " + new Date();System.out.println("Sender : " + context);this.rabbitTemplate.convertAndSend("hello", context);}}
4)创建发送消息的测试类
@RunWith(SpringRunner.class)@WebAppConfiguration@SpringBootTestpublic class RabbitMQSenderTest {@Autowiredprivate Sender sender;@Testpublic void hello() throws Exception {sender.send();}}