RabbitMQ是一个由erlang开发的AMQP的开源实现
安装好RabbitMQ之后
登录进入
第一步,先创建exchanges
第二步,创建querus
第三步,创建exchanges和querus交互的路游键
大概理解步骤
生产者创建消息发送到exchanges(交换器)上,交换器根据路由键绑定的querus(消息队列), 将消息发送到消息队列上,最后消费者接收消息
1.加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.在配置文件配置rabbitmq
#配置rabbitmq
spring.rabbitmq.host=localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=5672
3.为了发送的消息为json格式,而不是jdk默认的序列化方式,配置rabbitmq配置类,
/**
* 配置rabbit接收消息序列化方式,默认为jdk序列化
* @author Administrator
*
*/
@Configuration
public class RabbitConfig {
@Bean
public MessageConverter getMessageConverter(){
return new Jackson2JsonMessageConverter();
}
}
4.发送的消息得到监听,需在主程序上开启基于注解的rabbimq
@EnableRabbit
@SpringBootApplication
public class Springboot009RabbitMqApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot009RabbitMqApplication.class, args);
}
}
5.测试发送消息
//发送direct类型消息
@Test
public void sendDirectMessage() {
//交换器
String exchange="exchanges.direct";
//路游键
String routingKey="athexunews";
//消息,发送的格式是jdk默认序列化,而不是json格式
Map<String,Object> map=new HashMap<String, Object>();
map.put("msg", "这是测试的消息");
map.put("status", "success");
map.put("putUser", "何旭");
rabbitTemplate.convertAndSend(exchange, routingKey, map);
}
6.监听方法会自动监听到发送的消息并接收
@Controller
public class RabbimqListener {
@Autowired
private RabbitTemplate rabbitTemplate;
/*
* 监听athexunews的消息队列
* queues:消息队列名称
*/
@RabbitListener(queues="athexunews")
public void listenerMessage(Map<String,Object> msg){
// Object msg = rabbitTemplate.receiveAndConvert("athexunews");
System.out.println("收到消息:"+msg);
}
}
--------------------------------------------------------------创建和删除exchenges,querus---------------------------------
@Autowired
private AmqpAdmin amqpAdmin;//管理组件
//创建交换器,队列,绑定规则
@Test
public void createExchangesQuerus(){
//exchanges四种:direct(默认的)
amqpAdmin.declareExchange(new DirectExchange("createExchanges"));
//创建队列
amqpAdmin.declareQueue(new Queue("createqueues",true));//true为持久化
//需要绑定到那个exchanges才能使用
amqpAdmin.declareBinding(new Binding("createqueues",DestinationType.QUEUE, "createExchanges", "springbootcreatequeues.luyou", null));
}
//删除建交换器,队列,绑定规则
@Test
public void delExchangesQuerus(){
amqpAdmin.declareBinding(new Binding("createqueues",DestinationType.QUEUE, "createExchanges", "springbootcreatequeues.luyou", null));
amqpAdmin.deleteExchange("createExchanges");
amqpAdmin.deleteQueue("createqueues");
}