【java开发安装篇】之安装ActiveMQ

468 阅读6分钟

Linux下ActiveMQ的安装

前言:ActiveMQ基于java的,所以得先安装jdk;重点重点重点:ActiveMQ的版本一定要和jdk的版本匹配。

废话不多说,直接上图,简单粗暴...

1、下载activemq

下载地址:http://activemq.apache.org/download-archives.html
我下载的是Activemq 5.12.0 Relaese 版本
jdk我安装的是1.7版本

https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u80-oth-JPR

如果没有安装jdk的,请按一进行安装。我已经安装了,直接进入activemq的步骤
进入activemq下载地址

我们下载linux版本的,将下载下来的包,存到我们的目录下
解压:tar -zxvf apache-activemq-5.12.0-bin.tar.gz

2、启动

两种方式:
第一种:

关闭命令: bin/activemq stop

第二种:

mv apache-activemq-5.12.1 /usr/local/activemq

直接改造activemq原生启动脚本来做服务引导脚本

ln -s /usr/local/activemq/bin/activemq /etc/init.d/
vi /etc/init.d/activemq

第二行插入

chkconfig: 345 63 37
description: Auto start ActiveMQ

可以设置开机启动了

chkconfig activemq on  
chkconfig --list activemq

启动服务看看service activemq start
设置防火墙service iptables status

iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 61616 -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 8161 -j ACCEPT
service iptables save
service iptables restart

3、JAVA API

代码见activemq代码压缩文件 路径:/usr/allToolAndCode目录下的activemqcode.zip
前提:
本人根据上述,jdk1.7,activemq5.12.0集成的
本人项目集成的是spring2.0,由于公司项目老,替换升级会导致很多问题。非必,请勿优化或重构项目(因为脑壳痛,掉了几根头发)。
言归正传,action 需要下载相关jar包(spring基础相关Jar包,见那个少下那个,由于web项目,难整理)
Spring-jms-2.0jar
Activemq-all-5.5.0jar
下载地址:

https://mvnrepository.com/artifact/org.springframework/spring-jms  
https://mvnrepository.com/artifact/org.apache.activemq/activemq-all 

由于本人的web项目,直接放在lib下,如果你是maven项目,只需要导入依赖,版本根据上述即可。
首先创建activemq.xml文件
具体配置已添加注释

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:amq="http://activemq.apache.org/schema/core"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!--1.ActiveMQ 真正产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 也可以用amq:内置标签来定义-->
    <!--<amq:connectionFactory id="amqConnectionFactory"-->
    <!--brokerURL="tcp://192.168.1.1:61616"-->
    <!--userName="admin" password="admin"></amq:connectionFactory>-->

    <bean id="activeMqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://192.168.1.18:61616"/>
        <property name="userName" value="admin"></property>
        <property name="password" value="admin"></property>
    </bean>
    <!--userName,password是activemq的默认密码,如果需要修改密码,自行百 度,程序猿何苦为难程序猿,见下述标题5:修改activemq默认密码-->

    <!--2.配置spring 管理 connectionFactory类-->
    <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
        <constructor-arg ref="activeMqConnectionFactory" />
        <property name="sessionCacheSize" value="100" />
    </bean>

    <!--3.配置消息队列生产者与消费者以及监听者-->
    <!-- 定义消息队列(Queue) -->
    <bean id="LTQueueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <!-- 设置消息队列的名字 -->
        <constructor-arg>
            <value>LTQueue01</value>
        </constructor-arg>
    </bean>

    <!-- 配置JMS模板(Queue),Spring提供的JMS工具类,它发送、接收消息。 -->
    <bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="LTQueueDestination" />
        <property name="receiveTimeout" value="10000" />
        <!-- true是topic,false是queue,默认是false,此处显示写出false -->
        <property name="pubSubDomain" value="false" />
    </bean>


    <!-- 配置消息队列监听者(Queue) -->
    <bean id="queueMessageListener" class="com.hlt.mqs.QueueMessageListener" />

    <!-- 显示注入消息监听容器(Queue),配置连接工厂,监听的目标是demoQueueDestination,监听器是上面定义的监听器 -->
    <bean id="queueListenerContainer"
          class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="LTQueueDestination" />
        <property name="messageListener" ref="queueMessageListener" />
        <!--客户端手动确认 -->
        <property name="sessionAcknowledgeMode" value="4"/>
<!--有人会想,不是2吗?字太多,详情请查看链接:https://segmentfault.com/a/1190000008707181-->
    </bean>


    <!--4.配置主题消息生产者以及监听者-->
    <!--这个是主题(topic)目的地,一对多的 -->
    <bean id="LTTopicDestination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg value="LTTopic01" />
    </bean>

    <!-- 配置JMS模板(Topic),Spring提供的JMS工具类,它发送、接收消息。 -->
    <bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultDestination" ref="LTTopicDestination" />
        <property name="receiveTimeout" value="10000" />
        <!-- true是topic,false是queue,默认是false,此处显示写出true -->
        <property name="pubSubDomain" value="true" />
        <!-- 消息不持久化 -->
        <property name="explicitQosEnabled" value="false"></property>
    </bean>


    <!-- 消息监听类 -->
    <bean id="topicMessageListener1" class="com.hlt.mqs.TopicMessageListener1"/>

    <!-- 消息监听器 -->
    <bean id="topicListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"></property>
        <property name="destination" ref="LTTopicDestination"></property>
        <property name="messageListener" ref="topicMessageListener1"></property>
    </bean>

</beans>

然后在spring文件中

<!-- 引入activeMQ  配置   -->
<import resource="/applicationmq.xml"/>

新建Action/controller接口测试代码:
请不要在意我的随意命名法

// activemq
//队列消费者
@Resource
QueueConsumerService queueConsumerService;

//队列生产者
@Resource
QueueProducerService queueProducerService;

@Resource(name = "LTQueueDestination")
private Destination destination;


public String sendQueueMessage(){
    queueProducerService.sendMessage(destination, "我向activeMQ服务器发送一条Queue消息");
    return ajax(Status.success,"发送队列 success");
}


public String receiveQueueMessage() throws Exception{
    TextMessage receive = queueConsumerService.receive(destination);
    return receive.getText();
}



// 主题
@Resource
TopicProducerService topicProducerService;
@Resource(name = "LTTopicDestination")
private Destination destinationTopic;

public String sendTopicMessage(){
    topicProducerService.sendMessage(destinationTopic, "我向activeMQ服务器发送一条Topic消息");
    return "发送主题信息 success";
}


新建QueueProducerService
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

/**
 * Created by Gaci on 2020/1/10.
 */
@Service
public class QueueProducerService {

    @Resource(name="jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    public void sendMessage(Destination destination, final String msg){
        System.out.println(Thread.currentThread().getName()+" 向队列"+destination.toString()+"发送消息---------------------->"+msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }
}

新建QueueConsumerService 
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;

/**
 * Created by Gaci on 2020/1/10.
 */
@Service
public class QueueConsumerService {
    @Resource(name="jmsQueueTemplate")
    private JmsTemplate jmsTemplate;

    public TextMessage receive(Destination destination){
        TextMessage textMessage = (TextMessage) jmsTemplate.receive(destination);
        try{
            System.out.println("从队列" + destination.toString() + "收到了消息:\t"
                    + textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return textMessage;
    }


}

新建QueueMessageListener 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * Created by Gaci on 2020/1/10.
 */
public class QueueMessageListener implements MessageListener {
    @Override
    public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
            System.out.println("QueueMessageListener监听到了文本消息:\t"
                    + tm.getText());
            tm.acknowledge();  //告诉中间件 已经消费了
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

新建TopicProducerService 
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

/**
 * Created by Gaci on 2020/1/10.
 */
@Service
public class TopicProducerService {
    @Resource(name="jmsTopicTemplate")
    private JmsTemplate jmsTemplate;

    public void sendMessage(Destination destination, final String msg){
        System.out.println(Thread.currentThread().getName()+" 向主题"+destination.toString()+"发送消息---------------------->"+msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }

}

新建TopicMessageListener1 
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * Created by Gaci on 2020/1/10.
 */
public class TopicMessageListener1 implements MessageListener {
    @Override
    public void onMessage(Message message) {
        TextMessage tm = (TextMessage) message;
        try {
            System.out.println("TopicMessageListener1监听到了文本消息:\t"
                    + tm.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

利用postman测试下我的几根头发

说明我的几根头发还是值得
具体各种业务,请根据业务需求去设计。
咦,差点忘记了

4、修改activemq默认密码

首先修改网页登录密码 ,进入activemq的conf目录下

使用vi jetty-realm.properties

上面的注释:用户名,密码,角色
admin是用户名,activemq123456是密码,admin是角色
按i进入编辑模式,修改完之后按esc键退出编辑模式,输入命令:wq ,搞定了。

修改使用账号密码:
进入conf目录,vi activemq.xml

找到</broker>的位置

尽量手动输入:我由于为了方便,cv大法,可能有特殊空格字符,导致启动报
xxxxxxxxx lineNumber: 125; columnNumber: 14; cvc-complex-type.2.3: 元素 'broker' 必须不含字符 [子级], 因为该类型的内容类型为“仅元素”。

<plugins>
      <simpleAuthenticationPlugin>
            <users>
               <authenticationUser username="admin" password="activemq123456" groups="users,admins"/>
            </users>
       </simpleAuthenticationPlugin>
</plugins>

启动activemq,就可以了。


结语:以往都是看别人的博客进行学习技术,其中不乏有精华博客也有吊儿郎当的CV大法文章,所以决定将自己所学所用所整理的知识分享给大家,主要还是想为了后浪们少走些弯路,多些正能量的博客,如有错漏,欢迎指正,仅希望大家能在我的博客中学到知识,解决到问题,那么就足够了。谢谢大家!(转载请注明原文出处)