开启基于注解的RabbitMQ模式
@EnableRabbit // 开启基于注解的RabbitMQ模式
@SpringBootApplication
public class Springboot02AmqpApplication {
public static void main(String[] args)
{
SpringApplication.run(Springboot02AmqpApplication.class, args);
}
}
监听队列消息
@Service
public class CarService {
//只要这个消息队列有内容进来,这个方法就会被调用
@RabbitListener(queues = {"ezerbel.news"})
public void receive(Car car){
System.out.println("ezerbel.news 队列中有消息进来了! car == " + car);
}
@RabbitListener(queues = {"lilith.news"})
public void receiveMsg(Message msg){
System.out.println("lilith.news 队列中有消息进来了! msg.prop == " + msg.getMessageProperties()
+" msg.body == " + msg.getBody());
}
}
发布消息
@Test
public void testPubBroadCast()
{
Car car = new Car("Losless",3050000);
rabbitTemplate.convertAndSend("exchange.fanout","",car);
}
得到结果
lilith.news 队列中有消息进来了! msg.prop == MessageProperties [headers={__TypeId__=com.ezerbelcn.amqp.bean.Car}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=exchange.fanout, receivedRoutingKey=, deliveryTag=1, consumerTag=amq.ctag-18MYR1bSu3W1UgLkzrPfRA, consumerQueue=lilith.news] msg.body == [B@2942f01e
ezerbel.news 队列中有消息进来了! car == Car{name='Losless', price=3050000}