ActiveMQ入门及与SpringBoot整合

ActiveMQ简介

1. ActiveMQ

ActiveMQ是Apache所提供的一个开源的消息系统,完全采用Java来实现,因此,它能很好地支持J2EE提出的JMS(Java Message Service,即Java消息服务)规范。JMS是一组Java应用程序接口,它提供消息的创建、发送、读取等一系列服务。JMS提供了一组公共应用程序接口和响应的语法,类似于Java数据库的统一访问接口JDBC,它是一种与厂商无关的API,使得Java程序能够与不同厂商的消息组件很好地进行通信。

2. Java Message Service(JMS)

JMS支持两种消息发送和接收模型。

点对点模式

PTP:Point To Point,采用点对点的方式发送消息。基于队列的,消息生产者发送消息到队列,消息消费者从队列中接收消息,队列的存在使得消息的异步传输称为可能,P2P模型在点对点的情况下进行消息传递时采用。
image.png

发布-订阅模式

Pub/Sub:Publish/Subscribe,发布订阅消息模型。定义了如何向一个内容节点发布和订阅消息,这个内容节点称为topic(主题)。主题可以认为是消息传递的中介,消息发布这将消息发布到某个主题,而消息订阅者则从主题订阅消息。主题使得消息的订阅者与消息的发布者互相保持独立,不需要进行接触即可保证消息的传递,发布-订阅模型在消息的一对多广播时采用。
image.png

3. JMS术语

Provider/MessageProvider:生产者
Consumer/MessageConsumer:消费者
PTP:Point To Point,点对点通信消息模型
Pub/Sub:Publish/Subscribe,发布订阅消息模型
Queue:队列,目标类型之一,和PTP结合
Topic:主题,目标类型之一,和Pub/Sub结合
ConnectionFactory:连接工厂,JMS用它创建连接
Connnection:JMS Client到JMS Provider的连接
Destination:消息目的地,由Session创建
Session:会话,由Connection创建,实质上就是发送、接受消息的一个线程,因此生产者、消费者都是Session创建的

1、下载安装

1、windows安装

1、下载地址:http://activemq.apache.org/download-archives.html ,本文用的是windows版的5.15.3版本,下载下来是压缩包。apache-activemq-5.15.3-bin.zip  
2、将压缩包解压一个到目录下,CMD进入到解压目录下的bin目录下,执行 activemq.bat start 启动。                                                                              
如果能成功访问 http://localhost:8161/admin(用户名和密码默认为admin),则启动成功。

2、docker安装

# 设置Docker镜像加速
vi /etc/docker/daemon.json       # 如果该文件不存在就手动创建
# 添加内容:  {"registry-mirrors":["https://docker.mirrors.ustc.edu.cn"]}
# 或者: {"registry-mirrors":["https://hub.daocloud.io"]}
# 之后重新启动服务:
systemctl daemon-reload
systemctl restart docker

# 查找镜像
docker search activemq
# 或者在hub.docker.com 上查找对应mq及标签信息
# 拉取镜像,镜像名称:webcenter/activemq  镜像标签:5.14.3
docker pull webcenter/activemq:5.14.3
# 生成后台运行的容器   
docker run -id --name=activemq webcenter/activemq:5.14.3 -p:8161:8161 -p:61616:61616
#后台运行:-id 
#容器名称: --name=容器名称(自己定义)    
#端口映射: -p:宿主机端口:容器端口

#访问http://192.168.56.102:8161/  其中192.168.56.102为宿主机的ip,如果能正常访问,则ActiveMQ的环境已经正常搭建。

2、JMS入门小Demo

引入依赖


        org.apache.activemq
        activemq-client
        5.13.4

点对点模式

消息生产者

public class QueueProducer {
    public static void main(String[] args) throws JMSException {
        // 1.创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.56.101:61616");
        // 2.获取连接
        Connection connection = connectionFactory.createConnection();
        // 3.启动连接
        connection.start();
        // 4.获取session (参数1:是否启动事务,参数2:消息确认模式)
        // AUTO_ACKNOWLEDGE = 1    自动确认;
        // CLIENT_ACKNOWLEDGE = 2    客户端手动确认 
        // DUPS_OK_ACKNOWLEDGE = 3    自动批量确认
        // SESSION_TRANSACTED = 0    事务提交并确认
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 5.创建队列对象
        Queue queue = session.createQueue("test-queue");
        // 6.创建消息生产者
        MessageProducer producer = session.createProducer(queue);
        // 7.创建消息
        TextMessage textMessage = session.createTextMessage("点对点消息发送");
        // 8.发送消息
        producer.send(textMessage);
        // 9.关闭资源
        producer.close();
        session.close();
        connection.close();
    }
}

消息消费者

public class QueueConsumer {
    public static void main(String[] args) throws JMSException, IOException {
        // 1.创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.56.101:61616");
        // 2.获取连接
        Connection connection = connectionFactory.createConnection();
        // 3.启动连接
        connection.start();
        // 4.获取session (参数1:是否启动事务,参数2:消息确认模式)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 5.创建队列对象
        Queue queue = session.createQueue("test-queue");
        // 6.创建消息消费
        MessageConsumer consumer = session.createConsumer(queue);

        // 7.监听消息
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage)message;
                try {
                    System.out.println("接收到消息:" + textMessage.getText());
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        // 8.等待键盘输入
        System.in.read();
        // 9.关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
}

发布/订阅模式

消息生产者

public class TopicProducer {
    public static void main(String[] args) throws JMSException {
        //1.创建连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://192.168.56.101:61616");
        //2.获取连接
        Connection connection = connectionFactory.createConnection();
        //3.启动连接
        connection.start();
        //4.获取session  (参数1:是否启动事务,参数2:消息确认模式)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5.创建主题对象
        Topic topic = session.createTopic("test-topic");
        //6.创建消息生产者
        MessageProducer producer = session.createProducer(topic);
        //7.创建消息
        TextMessage textMessage = session.createTextMessage("发布/订阅模式消息发送");
        //8.发送消息
        producer.send(textMessage);
        //9.关闭资源
        producer.close();
        session.close();
        connection.close();
    }
}

消息消费者

public class TopicProducer {
    public static void main(String[] args) throws JMSException {
        //1.创建连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory("tcp://192.168.56.101:61616");
        //2.获取连接
        Connection connection = connectionFactory.createConnection();
        //3.启动连接
        connection.start();
        //4.获取session  (参数1:是否启动事务,参数2:消息确认模式)
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5.创建主题对象
        Topic topic = session.createTopic("test-topic");
        //6.创建消息生产者
        MessageProducer producer = session.createProducer(topic);
        //7.创建消息
        TextMessage textMessage = session.createTextMessage("发布/订阅模式消息发送");
        //8.发送消息
        producer.send(textMessage);
        //9.关闭资源
        producer.close();
        session.close();
        connection.close();
    }
}

3、SpringBoot整合JMS

1. 添加依赖

创建一个标准springboot项目,避免maven依赖冲突,添加如下依赖



  org.springframework.boot
  spring-boot-starter-activemq



  org.apache.activemq
  activemq-pool

2. 配置文件

server:
  port: 8081

spring:
  activemq:
    broker-url: tcp://192.168.56.101:61616
    user: admin
    password: admin
    close-timeout: 15s   # 在考虑结束之前等待的时间
    in-memory: true      # 默认代理URL是否应该在内存中。如果指定了显式代理,则忽略此值。
    non-blocking-redelivery: false  # 是否在回滚回滚消息之前停止消息传递。这意味着当启用此命令时,消息顺序不会被保留。
    send-timeout: 0     # 等待消息发送响应的时间。设置为0等待永远。
    queue-name: active.queue
    topic-name: active.topic.name.model

  #  packages:
  #    trust-all: true #不配置此项,会报错
  pool:
    enabled: true
    max-connections: 10   #连接池最大连接数
    idle-timeout: 30000   #空闲的连接过期时间,默认为30秒

  # jms:
  #   pub-sub-domain: true  #默认情况下activemq提供的是queue模式,若要使用topic模式需要配置下面配置

# 是否信任所有包
#spring.activemq.packages.trust-all=
# 要信任的特定包的逗号分隔列表(当不信任所有包时)
#spring.activemq.packages.trusted=
# 当连接请求和池满时是否阻塞。设置false会抛“JMSException异常”。
#spring.activemq.pool.block-if-full=true
# 如果池仍然满,则在抛出异常前阻塞时间。
#spring.activemq.pool.block-if-full-timeout=-1ms
# 是否在启动时创建连接。可以在启动时用于加热池。
#spring.activemq.pool.create-connection-on-startup=true
# 是否用Pooledconnectionfactory代替普通的ConnectionFactory。
#spring.activemq.pool.enabled=false
# 连接过期超时。
#spring.activemq.pool.expiry-timeout=0ms
# 连接空闲超时
#spring.activemq.pool.idle-timeout=30s
# 连接池最大连接数
#spring.activemq.pool.max-connections=1
# 每个连接的有效会话的最大数目。
#spring.activemq.pool.maximum-active-session-per-connection=500
# 当有"JMSException"时尝试重新连接
#spring.activemq.pool.reconnect-on-exception=true
# 在空闲连接清除线程之间运行的时间。当为负数时,没有空闲连接驱逐线程运行。
#spring.activemq.pool.time-between-expiration-check=-1ms
# 是否只使用一个MessageProducer
#spring.activemq.pool.use-anonymous-producers=true

3. 启动类增加 @EnableJms 注解

@SpringBootApplication
@EnableJms //启动消息队列
public class MqDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MqDemoApplication.class, args);
    }

}

4. 初始化和配置 ActiveMQ 的连接

@Component
public class BeanConfig {

    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;

    @Value("${spring.activemq.user}")
    private String username;

    @Value("${spring.activemq.topic-name}")
    private String password;

    @Value("${spring.activemq.queue-name}")
    private String queueName;

    @Value("${spring.activemq.topic-name}")
    private String topicName;

    @Bean(name = "queue")
    public Queue queue() {
        return new ActiveMQQueue(queueName);
    }

    @Bean(name = "topic")
    public Topic topic() {
        return new ActiveMQTopic(topicName);
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        return new ActiveMQConnectionFactory(username, password, brokerUrl);
    }

    @Bean
    public JmsMessagingTemplate jmsMessageTemplate() {
        return new JmsMessagingTemplate(connectionFactory());
    }

    /**
     * 在Queue模式中,对消息的监听需要对containerFactory进行配置
     */
    @Bean("queueListener")
    public JmsListenerContainerFactory queueJmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(false);
        return factory;
    }

    /**
     * 在Topic模式中,对消息的监听需要对containerFactory进行配置
     */
    @Bean("topicListener")
    public JmsListenerContainerFactory topicJmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(true);
        return factory;
    }
}

5. 生产者(queue 和 topic)

@RestController
public class ProducerController {
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Queue queue;

    @Autowired
    private Topic topic;

    /**
     * 点对点模式
     */
    @PostMapping("/queue/test")
    public String sendQueue(@RequestBody String str) {
        this.sendMessage(queue, str);
        return "success";
    }

    /**
     * 发布/订阅模式
     */
    @PostMapping("/topic/test")
    public String sendTopic(@RequestBody String str) {
        this.sendMessage(topic, str);
        return "success";
    }

    /**
     * 发送消息,destination是发送到的队列,message是待发送的消息
     */
    private void sendMessage(Destination destination, final String message) {
        jmsMessagingTemplate.convertAndSend(destination, message);
        // 将消息封装并发送到点对点模式队列:active.test
        //jmsMessagingTemplate.convertAndSend("active.test", message);
    }
}

6. 消费者(queue模式、topic模式)

@Component
public class TopicAndQueueConsumerListener {
    /**
     * queue模式的消费者
     * SendTo("active.queue.result") 会将此方法返回的数据, 写入到 active.queue.result 中去.
     */
    @SendTo("active.queue.result")
    @JmsListener(destination="${spring.activemq.queue-name}", containerFactory="queueListener")
    public String readP2PQActiveueue(String message) {
        System.out.println("queue接受到:" + message);
        return message;
    }

    /**
     * queue模式的消费者
     */
    @JmsListener(destination="active.queue.result", containerFactory="queueListener")
    public void readP2PActiveQueue1(String message) {
        System.out.println("active.queue.result接受到:" + message);
    }

    /**
     * topic模式的消费者
     */
    @JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
    public void readTopicActiveQueue(String message) {
        System.out.println("topic接受到:" + message);
    }
}

你可能感兴趣的:(ActiveMQ入门及与SpringBoot整合)