2.1 消费者

  1. package com.example.mq.consumer;
  2. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * 消费者
  6. */
  7. @Component
  8. public class Receiver {
  9. // 处理消息
  10. @RabbitListener(queues ={"${mq.queue.name}"})
  11. public void process(String msg){
  12. System.out.println("receive:"+msg);
  13. }
  14. }

2.2 生产者

  1. package com.example.provider;
  2. import org.springframework.amqp.core.AmqpTemplate;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * 生产者
  8. */
  9. @Component
  10. public class Sender {
  11. @Autowired
  12. private AmqpTemplate amqpTemplate;
  13. @Value("${mq.queue.name}")
  14. private String queueName;
  15. /**
  16. * 发送消息到队列
  17. * @param msg
  18. */
  19. public void send(String msg){
  20. amqpTemplate.convertAndSend(queueName,msg);
  21. }
  22. }

2.3 测试

  • 启动服务,消费者处于监听状态
  • 调用send方法发送消息