myQueue2 是消息队列
发送方
package com.lm.test.controller;
import com.lm.test.message.StreamClient;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
//发送MQ测试
@RestController
public class SendMessage1Controller {
@Autowired
private AmqpTemplate amqpTemplate;
@GetMapping("/sendMessage1")
public void process(){
String message = "发送的消息:"+new Date();
amqpTemplate.convertAndSend("myQueue2",message);
}
}
接收方
注意三种接收方式
package com.lm.test.message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 接收方
*/
@Slf4j
@Component
public class MqReceiver {
// //1.需要手动在 RabbitMQ手动先创建好,否则未创建的异常
// @RabbitListener(queues = "myQueue2")
// public void process(String message){
// log.info("Mq 消息接受者:{}",message);
// }
// //2.自动创建队列
// @RabbitListener(queuesToDeclare = @Queue("myQueue2"))
// public void process(String message){
// log.info("Mq 消息接受者:{}",message);
// }
//3. 自动创建,Exchage与Queue绑定
@RabbitListener(bindings = @QueueBinding(
value = @Queue("myQueue2"),
exchange = @Exchange("myExchage")
))
public void process(String message){
log.info("Mq 消息接受者:{}",message);
}
}