SpringBoot整合rabbitmq
1、引入相关依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> |
2、服务配置信息:
spring.rabbitmq.host=118.24.44.169 spring.rabbitmq.username=guest spring.rabbitmq.password=guest |
3、发送、接收、广播消息:
//点对点发送 public void sendMessage() { Map<String,Object> map = new HashMap<>(); map.put("msg","这是第一个消息"); map.put("data", Arrays.asList("helloworld",123,true)); //对象被默认序列化以后发送出去 rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",map); } |
//接收消息 public void receive(){ Object o = rabbitTemplate.receiveAndConvert("atguigu.news"); System.out.println(o.getClass()); System.out.println(o); } |
//广播 public void sendMsg(){ rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹")); } |
4、对象被发送时默认采用java的方式序列化发送出去的,我们可以自定义一个MessageConverter将数据转为json发送出去,这样发送过去的数据就是json格式的:
@Configuration public class MyAMQPConfig { @Bean public MessageConverter messageConverter(){ return new Jackson2JsonMessageConverter(); } } |
5、@EnableRabbit + @RabbitListener 监听消息队列的内容:
场景:订单系统只要下了订单,往消息队列中加了消息,库存系统就会自动监听到数据进行计算。
@EnableRabbit//开启基于注解的RabbitMQ模式 @SpringBootApplication public class SpringbootAmqpApplication { public static void main(String[] args) { SpringApplication.run(SpringbootAmqpApplication.class, args); } } |
@Service public class BookService { @RabbitListener(queues = "atguigu.news") public void receive(Book book){ System.out.println("收到消息:"+book); } @RabbitListener(queues = "atguigu") public void receive02(Message message){ System.out.println(message.getBody()); System.out.println(message.getMessageProperties()); } } |