1.在大多应用中,我们系统之间需要进行异步通信,即异步消息。
2.异步消息中两个重要概念:消息代理(message broker)和目的地(destination)
当消息发送者发送消息以后,将由消息代理接管,消息代理保证消息传递到指定目的地。
3.异步消息主要有两种形式的目的地
4.点对点式:
5.发布订阅式:
核心概念:
Producer&Consumer
Broker
Queue
Exchange
Binding
virtual host(vhosts )
RabbitMQ配置由spring.rabbitmq。*中的外部配置属性控制。 例如,您可以在application.properties中声明以下部分:
spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=secret
.....
发送消息
Spring的AmqpTemplate和AmqpAdmin是自动配置的,您可以将它们直接自动装入自己的bean中:
package com.ustc.rabbitmq; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.HashMap; @RunWith(SpringRunner.class) @SpringBootTest public class RabbitmqApplicationTests { @Autowired RabbitTemplate rabbitTemplate; @Test public void contextLoads() { HashMap map = new HashMap(); map.put("msg","this is idea send"); map.put("data", Arrays.asList("hahaha",185,true)); rabbitTemplate.convertAndSend("exchange.direct","ustc.emp",map); } @Test public void receive(){ Object o = rabbitTemplate.receiveAndConvert("ustc.news"); System.out.println(o.getClass()); System.out.println(o); } }
tips:默认的传输对象的测试是采用java自带的序列化机制,如果想更改默认的序列化机制,可以配置一个messagerConverter.
package com.ustc.rabbitmq.config; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitMQConfiguration { @Bean public MessageConverter messageConverter(){ return new Jackson2JsonMessageConverter(); } }
import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; @Service public class MessageService { @RabbitListener(queues = "ustc.emp") //指明要监听的队列 是一个数组 public void recive(Object o){ System.out.println(o); } }
tips:使用该注解时,需要先开启注解功能。
import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @EnableRabbit //开启基于注解的rabbitmq @SpringBootApplication public class RabbitmqApplication { public static void main(String[] args) { SpringApplication.run(RabbitmqApplication.class, args); } }
原文:https://www.cnblogs.com/ustc-anmin/p/11298777.html