springboot2.1.0、ActiveMQ简单使用

一)下载

从ActiveMQ官网下载:http://activemq.apache.org/components/classic/download/

下载完之后,把该文件解压,复制一份到一个固定的盘符下,比如直接到D盘下。

 

二)配置和启动步骤

由于ActiveMQ是Apache出品,可能需要修改一下环境变量启动配置,我windows操作系统是64位。

找到apache-activemq-5.15.9\bin\win64\wrapper.conf文件,修改wrapper.java.command属性。

1、如果配置了环境变量,修改为:wrapper.java.command=%JAVA_HOME%/bin/java

2、如果未配置环境变量,修改为:wrapper.java.command=C:/Program Files/Java/jdk1.8.0_162/bin/java

3、已管理员身份启动apache-activemq-5.15.9\bin\win64\InstallService.bat,在系统本地服务可以查看ActiveMQ服务。

4、如果上面都已配置,但本地服务中还显示未启动,建议重启一下电脑。

5、重启电脑之后,直接在浏览器中输入ActiveMQ地址:http://localhost:8161/

6、如访问:http://localhost:8161/admin/地址,ActiveMQ默认账号密码是Admin,登录之后即可操作。

 

三)ActiveMQ案例

pom.xml

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.15.9</version>
</dependency>

HelloActiveMQ.java:

package com.oysept.springboot.test;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * activemq demo测试
 * @author ouyangjun
 */
public class HelloActiveMQ {
	
    // TCP是ActiveMQ默认的协议,访问方式是 : tcp://hostname:port?key=value&key=value,如: tcp://localhost:61616?trace=true
    private final static String ACTIVEMQ_CONNECTION_URL = "tcp://localhost:61616";
	
    // 队列名称
    private final static String ACTIVEMQ_QUEUE_NAME = "QUEUE.OUYANGJUN";
	
    /**
     * 消息生产者
     */
    public static class HelloActiveMQProducer implements Runnable {
        @Override
        public void run() {
            int count = 1;
            while (true) {
                String text = "Hello ActiveMQ! Number: " + count;
                producer(text);
				
                count++;
                try {
                    // 睡眠
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
		
        public static void producer(String text) {
            ActiveMQConnectionFactory connectionFactory = null;
            Connection connection = null;
            Session session = null;
            MessageProducer messageProducer = null;
            try {
                // 创建activemq工厂,连接到activemq
                connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_CONNECTION_URL);
				
                // 创建连接
                connection = connectionFactory.createConnection();
                connection.start();
				
                // 创建session
                /*
                JMS规范的ack消息确认机制有一下四种,定于在session对象中:
                AUTO_ACKNOWLEDGE = 1 :自动确认
                CLIENT_ACKNOWLEDGE = 2:客户端手动确认
                DUPS_OK_ACKNOWLEDGE = 3: 自动批量确认
                SESSION_TRANSACTED = 0:事务提交并确认
                */
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
				
                // 创建目标(主题或队列)
                Destination destination = session.createQueue(ACTIVEMQ_QUEUE_NAME);
	            
                // 从会话到主题或队列创建MessageProducer
                messageProducer = session.createProducer(destination);
                messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

                // 创建文本消息
                System.out.println("HelloProducer Text Received: " + text);
                TextMessage message = session.createTextMessage(text);

                // 告诉制片人发送信息
                messageProducer.send(message);
            } catch (JMSException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭messageProducer
                    if (messageProducer != null) {
                        messageProducer.close();
                    }
                    // 关闭session
                    if (session != null) {
                        session.close();
                    }
                    // 关闭connection
                    if (connection != null) {
                        connection.close();
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
    /**
     * 消息消费者
     */
    public static class HelloActiveMQConsumer implements Runnable {

        @Override
        public void run() {
            while (true) {
                consumer();
            }
        }
		
        public static void consumer() {
            ActiveMQConnectionFactory connectionFactory = null;
            Connection connection = null;
            Session session = null;
            MessageConsumer messageConsumer = null;
            try {
                // 创建activemq工厂,连接到activemq
                connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_CONNECTION_URL);
				
                // 创建连接
                connection = connectionFactory.createConnection();
                connection.start();

                // 创建session
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                // 创建目标(主题或队列)
                Destination destination = session.createQueue(ACTIVEMQ_QUEUE_NAME);

                // 从会话到主题或队列创建MessageConsuer
                messageConsumer = session.createConsumer(destination);

                // 等待消息
                Message message = messageConsumer.receive(1000);
                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    String text = textMessage.getText();
                    System.out.println("HelloConsumer Text Received: " + text);
                } else {
                    System.out.println("HelloConsumer Received: " + message);
                }
            } catch (JMSException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭messageConsumer
                    if (messageConsumer != null) {
                        messageConsumer.close();
                    }
                    // 关闭session
                    if (session != null) {
                        session.close();
                    }
	            	// 关闭connection
                    if (connection != null) {
                        connection.close();
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
    /**
     * main
     * @param args
     */
    public static void main(String[] args) {
        Thread thread1 = new Thread(new HelloActiveMQProducer());
        Thread thread2 = new Thread(new HelloActiveMQConsumer());
		
        // 生产消息
        thread1.start();
        // 消费消息
        thread2.start();
    }
}

 

四)springboot项目集成ActiveMQ案例

在pom.xml引入ActiveMQ相关jar

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.oysept.springboot</groupId>
    <artifactId>oysept-springboot-activemq</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>oysept-springboot-activemq</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
		
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		
        <!-- springboot activemq -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>

        <!-- activemq线程池 -->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
        </dependency>
		
        <!-- 在2.X版本,spring.activemq.pool.enabled=true时,需依赖该jar -->
        <dependency>
            <groupId>org.messaginghub</groupId>
            <artifactId>pooled-jms</artifactId>
        </dependency>
	</dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

在application.properties添加ActiveMQ配置

说明:spring.activemq.pool.enabled=true该属性有版本兼容性问题,需注意

server.port=8080

spring.activemq.broker-url=tcp://localhost:61616
#spring.activemq.broker-url=failover:(tcp://localhost:61616,tcp://localhost:61617)

spring.activemq.user=admin
spring.activemq.password=admin

spring.activemq.pool.enabled=true
spring.activemq.pool.max-connections=100

 

添加ActiveMQ点对点Queue

说明:点对点发送的任意一条信息,只能由一个人接收,也就是说该发送的消息只能被消费一次。

           ActiveMQ支持多种消息格式,该章只列举了TextMessage

package com.oysept.springboot.controller;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * activemq queue案例
 * @author ouyangjun
 */
@RestController
@RequestMapping(value="/activemq")
public class QueueController {
	
    private final static String ACTIVEMQ_QUEUE_NAME = "activemq.queue";
	
    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 消息生产者(点对点)
     * 说明: 点对点发送的任意一条信息,只能由一个人接收,也就是说该发送的消息只能被消费一次
     * 测试地址: http://localhost:8080/activemq/sendQueueMsg?queueMsg=Hello%20ActiveMQ%20Queue
     * @param activemqMsg
     */
    @RequestMapping(value="/sendQueueMsg")
    @ResponseBody
    public String sendQueueMsg(@RequestParam("queueMsg") String queueMsg) {
        jmsTemplate.send(ACTIVEMQ_QUEUE_NAME, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage();
                textMessage.setText(queueMsg);
                return textMessage;
            }
        });
        return queueMsg;
    }
	
    /**
     * 消息消费者(点对点)
     * @param text
     */
    @JmsListener(destination = ACTIVEMQ_QUEUE_NAME)
    public void receiveQueue(String queueMsg){
        System.out.println("==>queue点对点消费者:receive: "+queueMsg);
    }
}

 

添加ActiveMQ广播、订阅Topic

说明:Topic如果不指定独立的containerFactory的话,就只能消费queue消息。

先添加一个Topic配置文件,配置单独的Factory

package com.oysept.springboot.config;

import javax.jms.ConnectionFactory;
import javax.jms.Topic;

import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

@Configuration
public class TopicConfig {
	
    public final static String ACTIVEMQ_TOPIC_NAME = "activemq.topic";
	
    /**
     * 
     * @param activeMQConnectionFactory
     * @return
     */
    @Bean(name="activemqJmsListenerContainerTopic")
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(activeMQConnectionFactory);
        return bean;
    }
	
    @Bean(name="activemqTopic")
    public Topic topic(){
        return new ActiveMQTopic(ACTIVEMQ_TOPIC_NAME);
    }
}

添加Topic测试Controller

package com.oysept.springboot.controller;

import javax.jms.Topic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.oysept.springboot.config.TopicConfig;

/**
 * activemq topic案例
 * @author ouyangjun
 */
@RestController
@RequestMapping(value="/activemq")
public class TopicController {
	
    @Autowired
    private JmsTemplate jmsTemplate;
	
    @Autowired @Qualifier(value="activemqTopic")
    private Topic topic;
	
    /**
     * topic消息生产者
     * 测试地址: http://localhost:8080/activemq/sendTopicMsg?topicMsg=Hello%20ActiveMQ%20Topic
     * @param topicMsg
     */
    @RequestMapping(value="/sendTopicMsg")
    @ResponseBody
    public String sendTopicMsg(@RequestParam("topicMsg") String topicMsg) {
        // topic
        this.jmsTemplate.convertAndSend(this.topic, topicMsg);
        return topicMsg;
    }
	
    // @JmsListener如果不指定独立的containerFactory的话,就只能消费queue消息
    // 消费者1
    @JmsListener(destination=TopicConfig.ACTIVEMQ_TOPIC_NAME, containerFactory="activemqJmsListenerContainerTopic")
    public void receive1(String topicMsg){
        System.out.println("==>topic消费者:receive1: "+topicMsg);
    }
	
    // 消费者2
    @JmsListener(destination=TopicConfig.ACTIVEMQ_TOPIC_NAME, containerFactory="activemqJmsListenerContainerTopic")
    public void receive2(String topicMsg){
        System.out.println("==>topic消费者:receive2: "+topicMsg);
    }
}

最后启动ActiveMQApplication

package com.oysept.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * springboot启动类
 * @author ouyangjun
 */
@SpringBootApplication
public class ActiveMQApplication {

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

 

在浏览器中输入以下地址即可测试,并到ActiveMQ界面查询

http://localhost:8080/activemq/sendQueueMsg?queueMsg=Hello%20ActiveMQ%20Queue

http://localhost:8080/activemq/sendTopicMsg?topicMsg=Hello%20ActiveMQ%20Topic

 

五)项目结构图

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值