springboot整合RabbitMQ
首先在docker上安装rabbitmq:
docker pull rabbitmq:3-management
docker images
docker run -d -p 5672:5672 -p 15672:15672 --name myrabbitmq rabbitmq镜像images
第二次启动时:
docker ps -a找到id
docker start rabbitmq容器id
连接:http://172.20.10.10:15672/看连接是否成功
springboot设置:
application.yml:
spring:
rabbitmq:
host: 172.20.10.10
username: guest
password: guest
# virtual-host: 默认/
@SpringBootTest
class Springboot08AmqpApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;//发送和接收消息队列
}
测试接收和发送消息
测试发送消息:
@Test
public void contextLoads() {
//message需要自己构造一个;定义消息体内容和消息头
// rabbitTemplate.send(exchange,routeKey,message);
//object默认当成消息体,只需要传入要发送的对象,自动序列化发送给rabbitmq
Map<String, Object> map = new HashMap<>();
map.put("msg","123");
map.put("data",Arrays.asList("213",123,true));
// rabbitTemplate.convertAndSend("exchange.direct","lbl.news",map);
rabbitTemplate.convertAndSend("exchange.direct","lbl.news",new Book
(1,"wudi",123));
}
测试接收消息
@Test
public void receive(){
Object o = rabbitTemplate.receiveAndConvert("lbl.news");
System.out.println(o.getClass());
System.out.println(o);
}
解决发送的值反序列化时不能返回json:修改amqp的config:
@Configuration
public class MyAmqpConfig {
@Bean
public Jackson2JsonMessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
测试通过springboot创建和删除Queue,exchange,binding
@SpringBootTest
class Springboot08AmqpApplicationTests {
@Autowired
AmqpAdmin amqpAdmin;//创建和删除Queue,exchange,binding
}
@Test
public void creatExchange(){
amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
// amqpAdmin.declareQueue(new Queue("amqp.exchange",true));
amqpAdmin.declareBinding(new Binding("amqpadmin.queue",Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.hh",null));//绑定amqpadmin.exchange
System.out.println("创建成功");
}