1 环境搭建
1.1 创建项目
1.2 修改全局配置文件
properties注释不能输入中文问题
Eclipse–>Window-Preferences–>General–>Content Types,右侧Text–>java Properites File 在Default encoding:输入UTF-8,点击Update。
spring.application.name=rabbitmq-direct-consumer
spring.rabbitmq.host=192.168.40.96
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbitmq
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.errror=errror.info
# error路由键
mq.config.queue.errror.routing.key=errror.errror.routing.key
1.3 编写consumer
SpingbootServerApplication类代码
@SpringBootApplication
public class SpingbootServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpingbootServerApplication.class, args);
}
}
InfoReceiver代码
/**
*
* 消息接收者
* @author 85762
* @RabbitListener bindings:绑定队列
* @QueueBinding value:绑定队列的名称
* exchange:配置交换器
* key:配置路由键
*
*
* @Queue value:配置队列名称
* autoDelete:是否是一个可删除的临时队列
* @Exchange:交换器的名称
*
*
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.info}",autoDelete="true"),
exchange=@Exchange(value="${mq.config.exchange}",type=ExchangeTypes.DIRECT),
key="${mq.config.queue.info.routing.key}"
)
)
public class InfoReceiver {
/*
* 接受消息的方法,采用消息队列监听机制
*/
@RabbitHandler
public void process(String msg) {
System.out.println("Info.......receiver:"+msg);
}
}
ErrorReceiver代码
/**
*
* 消息接收者
* @author 85762
* @RabbitListener bindings:绑定队列
* @QueueBinding value:绑定队列的名称
* exchange:配置交换器
* key:配置路由键
*
*
* @Queue value:配置队列名称
* autoDelete:是否是一个可删除的临时队列
* @Exchange:交换器的名称
*
*
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.errror}",autoDelete="true"),
exchange=@Exchange(value="${mq.config.exchange}",type=ExchangeTypes.DIRECT),
key="${mq.config.queue.errror.routing.key}"
)
)
public class ErrorReceiver {
/*
* 接受消息的方法,采用消息队列监听机制
*/
@RabbitHandler
public void process(String msg) {
System.out.println("Error.....receiver:"+msg);
}
}
1.4 编写provider(将consumer项目拷贝一份)
编写 sender
/**
* 消息发送者
* @author 85762
*
*/
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbAmqpTemplate;
//exchange 交换器名称
@Value("${mq.config.exchange}")
private String exchange;
//routingkey 路由键
@Value("${mq.config.queue.errror.routing.key}")
private String routingkey;
/*
* 发送消息的方法
*
*/
public void send(String msg) {
//向消息队列发送消息
//参数一:交换器名称
//参数二:路由键
//参数三:消息
this.rabbAmqpTemplate.convertAndSend(this.exchange, this.routingkey, msg);
}
}
编写测试类
/**
* 消息队列测试类
* @author 85762
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes=SpingbootServerApplication.class)
public class QueueTest {
@Autowired
private Sender sender;
@Test
public void test1() throws InterruptedException {
while(true) {
Thread.sleep(1000);
this.sender.send("Hello RabbitMQ");
}
}
}