学习内容来自尚硅谷 雷丰阳老师的课程尚硅谷-SpringBoot整合篇
一、为什么需要消息队列?
二、
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
550253309e6b 68bdffcb99c0 "docker-entrypoint..." About an hour ago Up About an hour 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp myrabbitmq
f1ca149fdbd5 71a81cb279e3 "docker-entrypoint..." 5 days ago Up About an hour 0.0.0.0:6379->6379/tcp myredis
848c6f760608 mysql:5.5 "docker-entrypoint..." 13 days ago Up About an hour 0.0.0.0:3306->3306/tcp mysql01
550253309e6b 68bdffcb99c0 "docker-entrypoint..." About an hour ago Up About an hour 4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp myrabbitmq
f1ca149fdbd5 71a81cb279e3 "docker-entrypoint..." 5 days ago Up About an hour 0.0.0.0:6379->6379/tcp myredis
848c6f760608 mysql:5.5 "docker-entrypoint..." 13 days ago Up About an hour 0.0.0.0:3306->3306/tcp mysql01
docker start rabbitmq
连接http://192.168.100.152:15672,用户名密码:guest,add new Exchanges and Queues, test publish message and get message:
在Springboot工程中加入rabbitmq 的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.xml中配置rabbitmq
spring.rabbitmq.host=192.168.100.152
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
使用RabbitTemplate 测试发送消息,可以看到发送消息成功,但是消息内容像乱码,这是因为content_type:application/x-java-serialized-object,我们可以使用MessageConverter来自定义序列化机制
@Autowired
RabbitTemplate rabbitTemplate;
@Test
public void testSend(){
Map<String,Object> map = new HashMap<>();
map.put("msg","this exchange:exchange.direct to routingKey:atguitu.emp");
map.put("data", Arrays.asList("hello",true,123));
rabbitTemplate.convertAndSend("exchange.direct","atguigu.emps",map);
}
@Test
public void testRecive(){
//Message msg = rabbitTemplate.receive("atguigu.emps");
Object msg = rabbitTemplate.receiveAndConvert("atguigu.emps");
System.out.println(msg.getClass());
System.out.println(msg);
}
@Configuration
public class MyAmqpConfig {
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
class org.springframework.amqp.core.Message
(Body:'[B@1473b8c0(byte[19])' MessageProperties [headers={}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=null, contentEncoding=null, contentLength=0, deliveryMode=null, receivedDeliveryMode=NON_PERSISTENT, expiration=null, priority=null, redelivered=true, receivedExchange=exchange.topic, receivedRoutingKey=atguigu, receivedDelay=null, deliveryTag=1, messageCount=2, consumerTag=null, consumerQueue=null])