rabbitmq中exchange对应的消息推送/接收模式:direct模式、fanout模式、topic模式
topic模式:创建 RabbitMqConfig下列代码
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMqConfig {
/**
* 队列
*/
@Bean
public Queue TestTopicQueue() {
return new Queue("dh-send-queue", true);
}
/**
* topic交换机
*/
@Bean
TopicExchange TestTopicExchange() {
return new TopicExchange("dh-send-exchange");
}
/**
* 绑定 将队列和交换机绑定
*/
@Bean
Binding bindingDirect() {
return BindingBuilder.bind(TestTopicQueue()).to(TestTopicExchange()).with("event.from.survey");
}
}
direct模式:创建 RabbitMqConfig下列代码
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMqConfig {
/**
* 队列
*/
@Bean
public Queue TestDirectQueue() {
return new Queue("dh-send-queue", true);
}
/**
* Direct交换机
*/
@Bean
DirectExchange TestDirectExchange() {
return new DirectExchange("dh-send-exchange");
}
/**
* 绑定 将队列和交换机绑定
*/
@Bean
Binding bindingDirect() {
return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("event.from.survey");
}
}
application.yml下加入
# Spring配置
spring:
#配置rabbitMq 服务器
rabbitmq:
password: admin
username: admin
port: 5672
#rabbitmq启动的ip地址
addresses: 127.0.0.1
#虚拟host 可以不设置,使用server默认host
# virtual-host: /
#开启发送失败返回
publisher-returns: true
#开启发送确认
# publisher-confirms: true
listener:
simple:
#指定最小的消费者数量.
concurrency: 12
#指定最大的消费者数量.
max-concurrency: 12
#开启ack
acknowledge-mode: auto
#开启ack
direct:
acknowledge-mode: auto
#支持消息的确认与返回
template:
mandatory: true
接受消息
@Component
public class ReceiveMsg {
private static final Logger log = LoggerFactory.getLogger(ReceiveMsg.class);
@RabbitListener(queues = "dh-send-queue")
public void receiveMessage(String content) {
log.info("dh-send-queue Received message: " , content);
}
}