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);
}
}