暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

RabbitMQ 使用之 spring-boot 方式

iWenhao 2022-02-19
153

spring boot 通过配置类的方式,不用向spring 配置xml的方式,让配置变得更加简单。


application.yml 文件

server:
port: 8080
spring:
rabbitmq:
port: 5672
username: admin
password: admin
addresses: 10.211.55.6
virtual-host: /conan
connection-timeout: 15000
publisher-returns: true # 路由失败回调
publisher-confirms: true # 发生确认
template:
mandatory: true # 必须设置成 true , 路由消息失败通知监听者, 而不是将消息丢弃
listener:
simple:
prefetch: 1 # 消费者 每次取的消息数量
        acknowledge-mode: manual  # 手动签收, 需要手动 ACK


消费者


普通的消费者

@Component
public class RabbitMQListener {
@RabbitListener(queues = {"spring_boot_queue_publish_subcrible"})
public void ListenerQueue(Message message) {
System.out.println("message:" + message.getBody());
    }
}


带消息确认ACK的回调

 @RabbitListener(queues = {"spring_boot_queue_publish_subcrible2"})
    public void listenerWithAck(Message message, Channel channel) throws IOException {
System.out.println("message:" + message.getBody());
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
}



生产者


简单模式 HelloWorld 交换机,队列配置

@Configuration
public class HelloWorldRabbitMqConfig {


//定义交换机的名字
public static final String HELLO_EXCHANGE_NAME = "";
//定义队列的名字
public static final String HELLO_QUEUE_NAME = "spring_boot_queue_hello_world";


//1、声明交换机
@Bean("helloExchange")
public Exchange helloExchange(){
return ExchangeBuilder.topicExchange(HELLO_EXCHANGE_NAME).durable(true).build();
}


//2、声明队列
@Bean("helloQueue")
public Queue helloQueue(){
return QueueBuilder.durable(HELLO_QUEUE_NAME).build();
}
}



Publish-subcrible, Routing,Topic 交换机,队列配置

@Configuration
public class PublisRabbitMqConfig {
//定义交换机的名字
public static final String EXCHANGE_NAME = "spring_boot_exchange_publish_subcrible";
//定义队列的名字
public static final String QUEUE_NAME = "spring_boot_queue_publish_subcrible";
//1、声明交换机
@Bean("publishExchange")
public Exchange publishExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2、声明队列
@Bean("publishQueue")
public Queue publishQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3、队列与交换机进行绑定
@Bean
public Binding bindQueueExchange(@Qualifier("publishQueue") Queue queue, @Qualifier("publishExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("aaa").noargs();
}
}




文章转载自iWenhao,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论