1.导入相应依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
2.在测试类里进行测试
package com.ws; import org.junit.jupiter.api.Test; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @SpringBootTest class Springboot02AmqpApplicationTests { @Autowired RabbitTemplate rabbitTemplate; @Test void contextLoads() { /*message需要自己构造一个;定义消息体内容和消息头 *rabbitTemplate.send(exchange,routeKey,message) * * object默认当成消息体,只需要传入发送的对象,自动序列化发给rabbitmq * rabbitTemplate.convertAnd Send(exchange,routeKey,object) * */ Map<String, Object> map = new HashMap<>(); map.put("msg","one"); map.put("data", Arrays.asList("HelloWorld",111)); rabbitTemplate.convertAndSend("exchange.direct","ws.news",map); } @Test void test2(){ Object o = rabbitTemplate.receiveAndConvert("ws.news"); System.out.println(o.getClass()); System.out.println(o); } }
3.编写自己的序列化Bean
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.amqp.support.converter.MessageConverter; @Configuration public class MyAMQPConfig { @Bean public MessageConverter messageConverter(){ return new Jackson2JsonMessageConverter(); } }
4.使用监听时需要在主启动类上加上@EnableRabbit注解
在方法上加@RabbitListener(queues="")注解,当消息队列里有值的时候就会被取出
@RabbitListener(queues = "ws.news") public void get(User user){ System.out.println("get"+user); } @RabbitListener(queues = "ws.news") public void get2(Message message){ System.out.println(message.getBody()); System.out.println(message.getMessageProperties()); }