2.1 消费者
package com.example.mq.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 消费者
*/
@Component
public class Receiver {
// 处理消息
@RabbitListener(queues ={"${mq.queue.name}"})
public void process(String msg){
System.out.println("receive:"+msg);
}
}
2.2 生产者
package com.example.provider;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 生产者
*/
@Component
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
@Value("${mq.queue.name}")
private String queueName;
/**
* 发送消息到队列
* @param msg
*/
public void send(String msg){
amqpTemplate.convertAndSend(queueName,msg);
}
}
2.3 测试
- 启动服务,消费者处于监听状态
- 调用send方法发送消息