RabbitMq | springboot (路由模式RoutingKey)整合Direct交換器

生產者發送消息到交換機並指定一個路由key,消費者隊列綁定到交換機時要制定路由key(key匹配就能接受消息,key不匹配就不能接受消息)

在這裏插入圖片描述

引入依賴:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
		</dependency>

消費者:

配置文件:

spring.application.name=springcloud-mq
spring.rabbitmq.host=192.168.70.131
spring.rabbitmq.port=5672
spring.rabbitmq.username=oldlu
spring.rabbitmq.password=123456
#設置交換器的名稱
mq.config.exchange=log.direct
#info 隊列名稱
mq.config.queue.info=log.info
#info 路由鍵
mq.config.queue.info.routing.key=log.info.routing.key
#error 隊列名稱
mq.config.queue.error=log.error
#error 路由鍵
mq.config.queue.error.routing.key=log.error.routing.key

消息接收者一:

/**
* 消息接收者
* @author Administrator
* @RabbitListener bindings:綁定隊列
* @QueueBinding value:綁定隊列的名稱
* exchange:配置交換器
*
* @Queue value:配置隊列名稱
* autoDelete:是否是一個可刪除的臨時隊列
*
* @Exchange value:爲交換器起個名稱
* type:指定具體的交換器類型
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.info}",autoDelete="tr
ue"),
exchange=@Exchange(value="${mq.config.exchange}",type=Excha
ngeTypes.DIRECT),
key="${mq.config.queue.info.routing.key}"
)
)
public class InfoReceiver {
/**
* 接收消息的方法。採用消息隊列監聽機制
* @param msg
*/
@RabbitHandler
public void process(String msg){
System.out.println("Info........receiver: "+msg);
}
}

消息接收者二:

/**
* 消息接收者
* @author Administrator
* @RabbitListener bindings:綁定隊列
* @QueueBinding value:綁定隊列的名稱
* exchange:配置交換器
*
* @Queue value:配置隊列名稱
* autoDelete:是否是一個可刪除的臨時隊列
*
* @Exchange value:爲交換器起個名稱
* type:指定具體的交換器類型
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.error}",autoDelete="t
rue"),
exchange=@Exchange(value="${mq.config.exchange}",type=Excha
ngeTypes.DIRECT),
key="${mq.config.queue.error.routing.key}"
)
)
public class ErrorReceiver {
/**
* 接收消息的方法。採用消息隊列監聽機制
* @param msg
*/
@RabbitHandler
public void process(String msg){
System.out.println("Error..........receiver: "+msg);
}
}

生產者:

spring.application.name=springcloud-mq
spring.rabbitmq.host=192.168.70.131
spring.rabbitmq.port=5672
spring.rabbitmq.username=oldlu
spring.rabbitmq.password=123456
#設置交換器的名稱
mq.config.exchange=log.direct
#info 隊列名稱
mq.config.queue.info=log.info
#info 路由鍵
mq.config.queue.info.routing.key=log.info.routing.key
#error 隊列名稱
mq.config.queue.error=log.error
#error 路由鍵
mq.config.queue.error.routing.key=log.error.routing.key
/**
* 消息發送者
* @author Administrator
*
*/
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitAmqpTemplate;
//exchange 交換器名稱
@Value("${mq.config.exchange}")
private String exchange;
//routingkey 路由鍵
@Value("${mq.config.queue.error.routing.key}")
private String routingkey;
/*
* 發送消息的方法
*/
public void send(String msg){
//向消息隊列發送消息
//參數一:交換器名稱。
//參數二:路由鍵
//參數三:消息
this.rabbitAmqpTemplate.convertAndSend(this.exchange,
this.routingkey, msg);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章