Rabbit MQ实战【direct交换器】
spring boot版本:2.1.10.RELEASE
本文涉及两个项目 rabbitmq-direct-consumer
和 rabbitmq-direct-provider
,所需maven依赖和配置相同。
相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
相关配置
#rabbitmq配置
spring.rabbitmq.host=192.168.xxx.xxx
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
#设置交换器(以下5个变量均为自定义变量)
mq.config.exchange=log.direct
mq.config.queue.info=log.info
mq.config.queue.info.routing.key=log.info.routing.key
rabbitmq-direct-consumer项目
创建消息接收类
package com.ebook.rabbitmq;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
/** * @author:JZ * @date:2020/2/2 */
@Component
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "${mq.config.queue.info}", autoDelete = "true"),//autoDelete表示队列为临时队列
exchange = @Exchange(value = "${mq.config.exchange}", type = ExchangeTypes.DIRECT),
key = "${mq.config.queue.info.routing.key}"
))
public class InfoReciver {
@RabbitHandler
public void process(String msg) {
System.out.println("接收到INFO日志:" + msg);
}
}
rabbitmq-direct-provider项目
(1)创建消息发送类
package com.ebook.rabbitmq;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
/** * @author:JZ * @date:2020/2/2 */
@Component
public class Sender {
@Value("${mq.config.exchange}")
private String exchange;
@Value("${mq.config.queue.info.routing.key}")
private String infoRoutingKey;
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String msg = "hello:" + new Date();
this.rabbitTemplate.convertAndSend(this.exchange, this.infoRoutingKey, msg);
}
}
(2)创建测试类
import com.ebook.rabbitmq.RabbitmqDirectProvider;
import com.ebook.rabbitmq.Sender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitmqDirectProvider.class)
public class RabbitMqHelloApplicationTests {
@Autowired
private Sender sender;
@Test
public void send() throws InterruptedException {
this.sender.send();
}
}
运行
启动rabbitmq-direct-consumer
项目,然后运行测试类,在consumer的控制台查看收到的消息。
还没有评论,来说两句吧...