spring boot版本:2.1.10.RELEASE
本文涉及两个项目 rabbitmq-fanout-provider
和 rabbitmq-fanout-consumer
,相关依赖和配置相同。
相关依赖
<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=106.15.120.126
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
#设置交换器(以下4个变量均为自定义变量)
mq.config.exchange=order.fanout
mq.config.queue.sms=order.sms
mq.config.queue.push=order.push
mq.config.queue.red=order.red
rabbitmq-fanout-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;
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String msg = "hello:" + new Date();
//广播路由键为空
this.rabbitTemplate.convertAndSend(this.exchange, "", msg);
}
}
(2)测试类
import com.ebook.rabbitmq.RabbitmqFanoutProvider;
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 = RabbitmqFanoutProvider.class)
public class RabbitMqFanoutApplicationTests {
@Autowired
private Sender sender;
@Test
public void send() throws InterruptedException {
this.sender.send();
}
}
rabbitmq-fanout-provider项目
(1)短信消息接收者
fanout交换器是广播发送,所以不需要指定路由键。
其他两个消息接收者只需将 mq.config.queue.sms
替换为配置文件中的其他消息队列即可。
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.sms}", autoDelete = "true"),//autoDelete表示队列为临时队列
exchange = @Exchange(value = "${mq.config.exchange}", type = ExchangeTypes.FANOUT)
))
public class SmsReciver {
@RabbitHandler
public void process(String msg) {
System.out.println("短信处理:" + msg);
}
}
Been_You
发布了276 篇原创文章 · 获赞 189 · 访问量 22万+
私信
关注