您的位置:首页 > 编程语言 > Java开发

spring-boot 集成 rabbitmq

2017-09-15 15:01 676 查看
本文示例主要参看官方的demo

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-amqp

https://github.com/spring-projects/spring-amqp-samples


RabbitMQ


介绍

RabbitMQ是流行的开源消息队列系统,用erlang语言开发。RabbitMQ是AMQP(高级消息队列协议)的标准实现。




概念

Broker:简单来说就是消息队列服务器实体。
Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列。
Queue:消息队列载体,每个消息都会被投入到一个或多个队列。
Binding:绑定,它的作用就是把exchange和queue按照路由规则绑定起来。
Routing Key:路由关键字,exchange根据这个关键字进行消息投递。
vhost:虚拟主机,一个broker里可以开设多个vhost,用作不同用户的权限分离。
producer:消息生产者,就是投递消息的程序。
consumer:消息消费者,就是接受消息的程序。
channel:消息通道,在客户端的每个连接里,可建立多个channel,每个channel代表一个会话任务。


使用过程

客户端连接到消息队列服务器,打开一个channel。
客户端声明一个exchange,并设置相关属性。
客户端声明一个queue,并设置相关属性。
客户端使用routing key,在exchange和queue之间建立好绑定关系。
客户端投递消息到exchange。

exchange接收到消息后,就根据消息的key和已经设置的binding,进行消息路由,将消息投递到一个或多个队列里。

exchange也有几个类型,完全根据key进行投递的叫做Direct交换机,例如,绑定时设置了routing key为”abc”,那么客户端提交的消息,只有设置了key为”abc”的才会投递到队列。对key进行模式匹配后进行投递的叫做Topic交换机,符号”#”匹配一个或多个词,符号”*”匹配正好一个词。例如”abc.#”匹配”abc.def.ghi”,”abc.*”只匹配”abc.def”。还有一种不需要key的,叫做Fanout交换机,它采取广播模式,一个消息进来时,投递到与该交换机绑定的所有队列。

RabbitMQ支持消息的持久化,也就是数据写在磁盘上,为了数据安全考虑,我想大多数用户都会选择持久化。消息队列持久化包括3个部分:

exchange持久化,在声明时指定durable => 1
queue持久化,在声明时指定durable => 1
消息持久化,在投递时指定delivery_mode => 2(1是非持久化)

如果exchange和queue都是持久化的,那么它们之间的binding也是持久化的。如果exchange和queue两者之间有一个持久化,一个非持久化,就不允许建立绑定。

以上内容抄自百度百科,RabbitMQ
百度百科

其它关于RabbitMQ的介绍可以看 http://www.cnblogs.com/qiyebao/p/4205626.html


Spring-boot 集成 rabbitmq


添加maven依赖

[html] view
plain copy

 print?

<dependency>  

      <groupId>org.springframework.boot</groupId>  

      <artifactId>spring-boot-starter-amqp</artifactId>  

</dependency>  

简单实现


配置

在application.properties中增加如下配置

[plain] view
plain copy

 print?

spring.rabbitmq.addresses=127.0.0.1:5672  

spring.rabbitmq.username=guest  

spring.rabbitmq.password=guest  

spring.rabbitmq.publisher-confirms=true  

spring.rabbitmq.virtual-host=/  

rabbitmq端口说明:5672-amqp,25672-clustering,61613-stomp,1883-mqtt

消息生产者

[java] view
plain copy

 print?

package com.rabbitmq.send;  

  

import org.springframework.amqp.rabbit.core.RabbitTemplate;  

import org.springframework.beans.factory.annotation.Autowired;  

import org.springframework.stereotype.Component;  

  

1fff7
@Component  

public class Sender {  

  

    @Autowired  

    private RabbitTemplate rabbitTemplate;  

  

    public void send(String msg) {  

        this.rabbitTemplate.convertAndSend("foo", msg);  

    }  

}  

消息监听者

[java] view
plain copy

 print?

package com.rabbitmq.listener;  

  

import org.slf4j.Logger;  

import org.slf4j.LoggerFactory;  

import org.springframework.amqp.core.Queue;  

import org.springframework.amqp.rabbit.annotation.RabbitHandler;  

import org.springframework.amqp.rabbit.annotation.RabbitListener;  

import org.springframework.context.annotation.Bean;  

import org.springframework.context.annotation.Configuration;  

import org.springframework.messaging.handler.annotation.Payload;  

  

@Configuration  

@RabbitListener(queues = "foo")  

public class Listener {  

  

    private static final Logger LOGGER = LoggerFactory.getLogger(Listener.class);  

  

    @Bean  

    public Queue fooQueue() {  

        return new Queue("foo");  

    }  

  

    @RabbitHandler  

    public void process(@Payload String foo) {  

        LOGGER.info("Listener: " + foo);  

    }  

}  

测试Controller

[java] view
plain copy

 print?

package com.rabbitmq.controller;  

  

import com.rabbitmq.send.Sender;  

import org.springframework.beans.factory.annotation.Autowired;  

import org.springframework.web.bind.annotation.GetMapping;  

import org.springframework.web.bind.annotation.RestController;  

  

import javax.servlet.http.HttpServletRequest;  

  

@RestController  

public class RabbitmqController {  

  

    @Autowired  

    private Sender sender;  

  

    @GetMapping("/send")  

    public String send(HttpServletRequest request, String msg) {  

        sender.send(msg);  

        return "Send OK.";  

    }  

}  

测试

启动服务,在浏览器输入 http://127.0.0.1:8080/send?msg=this%20is%20a%20test,点击回车可以在控制台看到如下输出

[plain] view
plain copy

 print?

INFO 5559 --- [cTaskExecutor-1] c.rabbitmq.listener.Listener  : Listener: this is a test  

[SimpleAsyncTaskExecutor-1] INFO  c.rabbitmq.listener.Listener - Listener: this is a test  

带ConfirmCallback的使用

增加回调处理,这里不再使用application.properties默认配置的方式,会在程序中显示的使用文件中的配置信息。


配置

[java] view
plain copy

 print?

package com.rabbitmq.config;  

  

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;  

import org.springframework.amqp.rabbit.connection.ConnectionFactory;  

import org.springframework.amqp.rabbit.core.RabbitTemplate;  

import org.springframework.beans.factory.annotation.Value;  

import org.springframework.beans.factory.config.ConfigurableBeanFactory;  

import org.springframework.context.annotation.Bean;  

import org.springframework.context.annotation.Configuration;  

import org.springframework.context.annotation.Scope;  

  

@Configuration  

public class AmqpConfig {  

  

    public static final String FOO_EXCHANGE   = "callback.exchange.foo";  

    public static final String FOO_ROUTINGKEY = "callback.routingkey.foo";  

    public static final String FOO_QUEUE      = "callback.queue.foo";  

  

    @Value("${spring.rabbitmq.addresses}")  

    private String addresses;  

    @Value("${spring.rabbitmq.username}")  

    private String username;  

    @Value("${spring.rabbitmq.password}")  

    private String password;  

    @Value("${spring.rabbitmq.virtual-host}")  

    private String virtualHost;  

    @Value("${spring.rabbitmq.publisher-confirms}")  

    private boolean publisherConfirms;  

  

    @Bean  

    public ConnectionFactory connectionFactory() {  

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();  

        connectionFactory.setAddresses(addresses);  

        connectionFactory.setUsername(username);  

        connectionFactory.setPassword(password);  

        connectionFactory.setVirtualHost(virtualHost);  

        /** 如果要进行消息回调,则这里必须要设置为true */  

        connectionFactory.setPublisherConfirms(publisherConfirms);  

        return connectionFactory;  

    }  

  

    @Bean  

    /** 因为要设置回调类,所以应是prototype类型,如果是singleton类型,则回调类为最后一次设置 */  

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)  

    public RabbitTemplate rabbitTemplate() {  

        RabbitTemplate template = new RabbitTemplate(connectionFactory());  

        return template;  

    }  

  

}  


消息生产者

[java] view
plain copy

 print?

package com.rabbitmq.send;  

  

import com.rabbitmq.config.AmqpConfig;  

import org.slf4j.Logger;  

import org.slf4j.LoggerFactory;  

import org.springframework.amqp.rabbit.core.RabbitTemplate;  

import org.springframework.amqp.rabbit.support.CorrelationData;  

import org.springframework.beans.factory.annotation.Autowired;  

import org.springframework.stereotype.Component;  

  

import java.util.UUID;  

  

@Component  

public class Sender implements RabbitTemplate.ConfirmCallback {  

  

    private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class);  

  

    private RabbitTemplate rabbitTemplate;  

  

    @Autowired  

    public Sender(RabbitTemplate rabbitTemplate) {  

        this.rabbitTemplate = rabbitTemplate;  

        this.rabbitTemplate.setConfirmCallback(this);  

    }  

  

    public void send(String msg) {  

        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());  

        LOGGER.info("send: " + correlationData.getId());  

        this.rabbitTemplate.convertAndSend(AmqpConfig.FOO_EXCHANGE, AmqpConfig.FOO_ROUTINGKEY, msg, correlationData);  

    }  

  

    /** 回调方法 */  

    @Override  

    public void confirm(CorrelationData correlationData, boolean ack, String cause) {  

        LOGGER.info("confirm: " + correlationData.getId());  

    }  

}  

消息监听者

[java] view
plain copy

 print?

package com.rabbitmq.listener;  

  

import com.rabbitmq.config.AmqpConfig;  

import org.slf4j.Logger;  

import org.slf4j.LoggerFactory;  

import org.springframework.amqp.core.Binding;  

import org.springframework.amqp.core.BindingBuilder;  

import org.springframework.amqp.core.DirectExchange;  

import org.springframework.amqp.core.Queue;  

import org.springframework.amqp.rabbit.annotation.RabbitHandler;  

import org.springframework.amqp.rabbit.annotation.RabbitListener;  

import org.springframework.context.annotation.Bean;  

import org.springframework.context.annotation.Configuration;  

import org.springframework.messaging.handler.annotation.Payload;  

  

@Configuration  

@RabbitListener(queues = AmqpConfig.FOO_QUEUE)  

public class Listener {  

  

    private static final Logger LOGGER = LoggerFactory.getLogger(Listener.class);  

  

    /** 设置交换机类型  */  

    @Bean  

    public DirectExchange defaultExchange() {  

        /** 

         * DirectExchange:按照routingkey分发到指定队列 

         * TopicExchange:多关键字匹配 

         * FanoutExchange: 将消息分发到所有的绑定队列,无routingkey的概念 

         * HeadersExchange :通过添加属性key-value匹配 

         */  

        return new DirectExchange(AmqpConfig.FOO_EXCHANGE);  

    }  

  

    @Bean  

    public Queue fooQueue() {  

        return new Queue(AmqpConfig.FOO_QUEUE);  

    }  

  

    @Bean  

    public Binding binding() {  

        /** 将队列绑定到交换机 */  

        return BindingBuilder.bind(fooQueue()).to(defaultExchange()).with(AmqpConfig.FOO_ROUTINGKEY);  

    }  

  

    @RabbitHandler  

    public void process(@Payload String foo) {  

        LOGGER.info("Listener: " + foo);  

    }  

}  

或者使用下面的代码来代替@RabbitHandler注解的process方法

[java] view
plain copy

 print?

@Bean  

public SimpleMessageListenerContainer messageContainer() {  

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());  

    container.setQueues(fooQueue());  

    container.setExposeListenerChannel(true);  

    container.setMaxConcurrentConsumers(1);  

    container.setConcurrentConsumers(1);  

    container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认  

    container.setMessageListener(new ChannelAwareMessageListener() {  

  

        @Override  

        public void onMessage(Message message, Channel channel) throws Exception {  

            byte[] body = message.getBody();  

            LOGGER.info("Listener onMessage : " + new String(body));  

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费  

        }  

    });  

    return container;  

}  

这里参看了这篇博文 http://blog.csdn.net/liaokailin/article/details/49559571

测试

运行服务,刷新上面的测试链接,可以在控制台看到如下输出

[plain] view
plain copy

 print?

INFO 15122 --- [nio-8080-exec-1] com.jikefriend.rabbitmq.send.Sender      : send: c678afb7-af8b-42b2-9370-ea7f9d6004a0  

[http-nio-8080-exec-1] INFO  com.jikefriend.rabbitmq.send.Sender - send: c678afb7-af8b-42b2-9370-ea7f9d6004a0  

INFO 15122 --- [ 127.0.0.1:5672] com.jikefriend.rabbitmq.send.Sender      : confirm: c678afb7-af8b-42b2-9370-ea7f9d6004a0  

[AMQP Connection 127.0.0.1:5672] INFO  com.jikefriend.rabbitmq.send.Sender - confirm: c678afb7-af8b-42b2-9370-ea7f9d6004a0  

INFO 15122 --- [cTaskExecutor-1] c.jikefriend.rabbitmq.listener.Listener  : Listener: this is a test  

[SimpleAsyncTaskExecutor-1] INFO  c.j.rabbitmq.listener.Listener - Listener: this is a test  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: