spring boot 通过配置类的方式,不用向spring 配置xml的方式,让配置变得更加简单。
application.yml 文件
server:port: 8080spring:rabbitmq:port: 5672username: adminpassword: adminaddresses: 10.211.55.6virtual-host: /conanconnection-timeout: 15000publisher-returns: true # 路由失败回调publisher-confirms: true # 发生确认template:mandatory: true # 必须设置成 true , 路由消息失败通知监听者, 而不是将消息丢弃listener:simple:prefetch: 1 # 消费者 每次取的消息数量acknowledge-mode: manual # 手动签收, 需要手动 ACK
消费者
普通的消费者
@Componentpublic 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 交换机,队列配置
@Configurationpublic 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 交换机,队列配置
@Configurationpublic 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、队列与交换机进行绑定@Beanpublic Binding bindQueueExchange(@Qualifier("publishQueue") Queue queue, @Qualifier("publishExchange") Exchange exchange){return BindingBuilder.bind(queue).to(exchange).with("aaa").noargs();}}
文章转载自iWenhao,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




