ActiveMQ windows安装和linux安装和代码示例

windows安装

JMS(Java Messaging Service)是Java平台上有关面向消息中间件的技术规范,它便于消息系统中的Java应用程序进行消息交换,并且通过提供标准的产生、发送、接收消息的接口简化企业应用的开发,ActiveMQ而是这个规范的一个具体实现。

JMS的队列消息传递过程如下图:

JMS的主题消息传递过程如下图:

ActiveMQ下载与部署。

1、  下载

到官网下载最新版本,有windows版本和linux版本的。

http://activemq.apache.org/download.html


windows版本:apache-activemq-5.11.1-bin.zip

linux版本:apache-activemq-5.11.1-bin.tar.gz

 

2、  部署

A、 windows下部署

ActiveMQ部署其实很简单,和所有Java一样,要跑java程序就必须先安装JDK并配置好环境变量,这个很简单。

然后解压下载的apache-activemq-5.11.1-bin.zip压缩包到一个目录,得到解压后的目录结构如下图:

进入bin目录,发现有win32和win64两个文件夹,这2个文件夹分别对应windows32位和windows64位操作系统的启动脚本。

我的实验环境是windowsXP,就进入win32目录,会看到如下目录结构。

其中activemq.bat便是启动脚本,双击启动。

ActiveMQ默认启动到8161端口,启动完了后在浏览器地址栏输入:http://localhost:8161/admin要求输入用户名密码,默认用户名密码为admin、admin,这个用户名密码是在conf/users.properties中配置的。

输入用户名密码后便可看到如下图的ActiveMQ控制台界面了。


测试
ActiveMQ默认使用的TCP连接端口是61616, 通过查看该端口的信息可以测试ActiveMQ是否成功启动 netstat -an|find "61616"
C:\Documents and Settings\Administrator>netstat -an|find "61616" 
    TCP        0.0.0.0:61616                    0.0.0.0:0                            LISTENING
 

Linux和Aix系统下的安装:

解压:tar zxvf activemq-x.x.x.tar.gz,进入bin文件夹,运行:./activemq start &,也可以只运行:./activemq console。

验证方式和安全性配置和windows下的配置一样。

linux安装和代码示例

IP:192.168.4.101

环境:CentOS 6.6、JDK7

1 安装 JDK 并配置环境变量(略)

JAVA_HOME=/usr/local/Java/jdk1.7.0_72

2 下载 Linux 版的 ActiveMQ(当前最新版 apache-activemq-5.11.1-bin.tar.gz

wget http://apache.fayea.com/activemq/5.11.1/apache-activemq-5.11.1-bin.tar.gz

3 解压安装

tar -zxvf apache-activemq-5.11.1-bin.tar.gz

mv apache-activemq-5.11.1 activemq-01

如果启动脚本 activemq 没有可执行权限,此时则需要授权(此步可选)

cd /home/wusc/activemq-01/bin/

chmod 755 ./activemq

4 防火墙中打开对应的端口

ActiveMQ 需要用到两个端口

一个是消息通讯的端口(默认为 61616)

一个是管理控制台端口(默认为 8161)可在 conf/jetty.xml 中修改,如下:

<bean id="jettyPort" class="org.apache.activemq.web.WebConsolePort" init-method="start"> <!-- the default port number for the web console -->

<property name="host" value="0.0.0.0"/> <property name="port" value="8161"/>

</bean>

vi /etc/sysconfig/iptables

添加:

-A INPUT -m state --state NEW -m tcp -p tcp --dport 61616 -j ACCEPT 

-A INPUT -m state --state NEW -m tcp -p tcp --dport 8161 -j ACCEPT

重启防火墙:

service iptables restart

5 启动

cd /home/wusc/activemq-01/bin $ ./activemq start

6 打开管理界面:http://192.168.4.101:8161

默认用户名和密码为:admin/admin


7 安全配置(消息安全)

ActiveMQ 如果不加入安全机制的话,任何人只要知道消息服务的具体地址(包括 ip,端口,消息地址[ 队列或者主题地址 ] , ) ,都可以肆无忌惮的发送、接收消息。关于  ActiveMQ  安装配置http://activemq.apache.org/security.html

ActiveMQ 的消息安全配置策略有多种,我们以简单授权配置为例:

 conf/activemq.xml 文件中在 broker 标签最后加入以下内容即可:

vi /home/wusc/activemq-01/conf/activemq.xml

<plugins>

<simpleAuthenticationPlugin>

<users>

 <authenticationUser username="wusc" password="wusc.123" groups="users,admins"/>

</users>

</simpleAuthenticationPlugin>

</plugins>

定义了一个 wusc 用户,密码为 wusc.123,角色为 users,admins

设置 admin 的用户名和密码: $ vi /home/wusc/activemq-01/conf/jetty.xml

<bean id="securityConstraint" class="org.eclipse.jetty.util.security.Constraint"> <property name="name" value="BASIC" />

<property name="roles" value="admin" /> <property name="authenticate" value="true" />

</bean>

确保 authenticate 的值为 true(默认)

控制台的登录用户名密码保存在 conf/jetty-realm.properties 文件中,内容如下:

 $ vi /home/wusc/activemq-01/conf/jetty-realm.properties

# Defines users that can access the web (console, demo, etc.)

# username: password [,rolename ...]

admin: wusc.123, admin

注意:用户名和密码的格式是用户名 : 密码 ,角色名

重启:

/home/wusc/activemq-01/bin/activemq restart

设置开机启动:

vi /etc/rc.d/rc.local

加入以下内容

## ActiveMQ

su - wusc -c '/home/wusc/activemq-01/bin/activemq start'


spring整合异步发送邮件


消息生产者(发邮件的请求)


mq.properties

[plain]  view plain  copy
  1. ## MQ  
  2. mq.brokerURL=tcp\://192.168.4.101\:61616  
  3. mq.userName=wusc  
  4. mq.password=wusc.123  
  5. mq.pool.maxConnections=10  
  6. #queueName  
  7. queueName=wusc.edu.mqtest.v1  

spring-mq.xml被spring-context引用

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd    
  8.            http://www.springframework.org/schema/aop     
  9.            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd    
  10.            http://www.springframework.org/schema/tx    
  11.            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd    
  12.            http://www.springframework.org/schema/context    
  13.            http://www.springframework.org/schema/context/spring-context-3.2.xsd"  
  14.     default-autowire="byName" default-lazy-init="false">  
  15.       
  16.     <!-- 基于Dubbo的分布式系统架构视频教程,吴水成,wu-sc@foxmail.com,学习交流QQ群:367211134 -->  
  17.   
  18.     <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->  
  19.     <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
  20.         <!-- ActiveMQ服务地址 -->  
  21.         <property name="brokerURL" value="${mq.brokerURL}" />  
  22.         <property name="userName" value="${mq.userName}"></property>  
  23.         <property name="password" value="${mq.password}"></property>   
  24.     </bean>  
  25.   
  26.     <!--   
  27.         ActiveMQ为我们提供了一个PooledConnectionFactory,通过往里面注入一个ActiveMQConnectionFactory  
  28.         可以用来将Connection、Session和MessageProducer池化,这样可以大大的减少我们的资源消耗。  
  29.         要依赖于 activemq-pool包  
  30.      -->  
  31.     <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">  
  32.         <property name="connectionFactory" ref="targetConnectionFactory" />  
  33.         <property name="maxConnections" value="${mq.pool.maxConnections}" />  
  34.     </bean>  
  35.   
  36.     <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
  37.     <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
  38.         <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->  
  39.         <property name="targetConnectionFactory" ref="pooledConnectionFactory" />  
  40.     </bean>  
  41.       
  42.     <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->  
  43.       
  44.     <!-- 队列模板 -->  
  45.     <bean id="activeMqJmsTemplate" class="org.springframework.jms.core.JmsTemplate">    
  46.         <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->    
  47.         <property name="connectionFactory" ref="connectionFactory"/>    
  48.         <property name="defaultDestinationName" value="${queueName}"></property>  
  49.     </bean>   
  50.   
  51. </beans>  

MQProducer

[java]  view plain  copy
  1. @Service("mqProducer")  
  2. public class MQProducer {  
  3.       
  4.     @Autowired  
  5.     private JmsTemplate activeMqJmsTemplate;  
  6.   
  7.     /** 
  8.      * 发送消息. 
  9.      * @param mail  
  10.      */  
  11.     public void sendMessage(final MailParam mail) {  
  12.         activeMqJmsTemplate.send(new MessageCreator() {  
  13.             public Message createMessage(Session session) throws JMSException {  
  14.                 return session.createTextMessage(JSONObject.toJSONString(mail));  
  15.             }  
  16.         });  
  17.           
  18.     }  
  19.   
  20. }  

测试类

[html]  view plain  copy
  1. public class MQProducerTest {  
  2.     private static final Log log = LogFactory.getLog(MQProducerTest.class);  
  3.   
  4.     public static void main(String[] args) {  
  5.         try {  
  6.             ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");  
  7.             context.start();  
  8.   
  9.             MQProducer mqProducer = (MQProducer) context.getBean("mqProducer");  
  10.             // 邮件发送  
  11.             MailParam mail = new MailParam();  
  12.             mail.setTo("wu-sc@foxmail.com");  
  13.             mail.setSubject("ActiveMQ测试");  
  14.             mail.setContent("通过ActiveMQ异步发送邮件!");  
  15.   
  16.             mqProducer.sendMessage(mail);  
  17.   
  18.             context.stop();  
  19.         } catch (Exception e) {  
  20.             log.error("==>MQ context start error:", e);  
  21.             System.exit(0);  
  22.         } finally {  
  23.             log.info("===>System.exit");  
  24.             System.exit(0);  
  25.         }  
  26.     }  
  27. }  


 消息消费者(真正发邮件)



mail.properties
[plain]  view plain  copy
  1. #SMTP服务配置  
  2. mail.host=smtp.qq.com  
  3. mail.port=25  
  4. mail.username=XXX@qq.com  
  5. mail.password=XXXX  
  6. mail.smtp.auth=true  
  7. mail.smtp.timeout=30000  
  8. mail.default.from=XXXXX@qq.com  

spring-mq.xml
[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd    
  8.            http://www.springframework.org/schema/aop     
  9.            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd    
  10.            http://www.springframework.org/schema/tx    
  11.            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd    
  12.            http://www.springframework.org/schema/context    
  13.            http://www.springframework.org/schema/context/spring-context-3.2.xsd"  
  14.     default-autowire="byName" default-lazy-init="false">  
  15.   
  16.     <!-- 基于Dubbo的分布式系统架构视频教程,吴水成,wu-sc@foxmail.com,学习交流QQ群:367211134 -->  
  17.   
  18.     <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供 -->  
  19.     <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">  
  20.         <!-- ActiveMQ服务地址 -->  
  21.         <property name="brokerURL" value="${mq.brokerURL}" />  
  22.         <property name="userName" value="${mq.userName}"></property>  
  23.         <property name="password" value="${mq.password}"></property>   
  24.     </bean>  
  25.   
  26.     <!--   
  27.         ActiveMQ为我们提供了一个PooledConnectionFactory,通过往里面注入一个ActiveMQConnectionFactory  
  28.         可以用来将Connection、Session和MessageProducer池化,这样可以大大的减少我们的资源消耗。  
  29.         要依赖于 activemq-pool包  
  30.      -->  
  31.     <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">  
  32.         <property name="connectionFactory" ref="targetConnectionFactory" />  
  33.         <property name="maxConnections" value="${mq.pool.maxConnections}" />  
  34.     </bean>  
  35.   
  36.     <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->  
  37.     <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">  
  38.         <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->  
  39.         <property name="targetConnectionFactory" ref="pooledConnectionFactory" />  
  40.     </bean>  
  41.       
  42.     <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->  
  43.       
  44.     <!-- 队列模板 -->  
  45.     <bean id="activeMqJmsTemplate" class="org.springframework.jms.core.JmsTemplate">    
  46.         <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->    
  47.         <property name="connectionFactory" ref="connectionFactory"/>    
  48.         <property name="defaultDestinationName" value="${queueName}"></property>  
  49.     </bean>   
  50.       
  51.     <!--这个是sessionAwareQueue目的地 -->  
  52.     <bean id="sessionAwareQueue" class="org.apache.activemq.command.ActiveMQQueue">  
  53.         <constructor-arg>  
  54.             <value>${queueName}</value>  
  55.         </constructor-arg>  
  56.     </bean>  
  57.   
  58.     <!-- 可以获取session的MessageListener -->  
  59.     <bean id="consumerSessionAwareMessageListener" class="wusc.edu.demo.mqtest.listener.ConsumerSessionAwareMessageListener"></bean>  
  60.   
  61.     <bean id="sessionAwareListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">  
  62.         <property name="connectionFactory" ref="connectionFactory" />  
  63.         <property name="destination" ref="sessionAwareQueue" />  
  64.         <property name="messageListener" ref="consumerSessionAwareMessageListener" />  
  65.     </bean>  
  66.   
  67. </beans>  
spring-mail.xml真正发送邮件的
[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xmlns:cache="http://www.springframework.org/schema/cache"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  6.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  7.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
  8.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  9.        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">  
  10.          
  11.     <!-- 基于Dubbo的分布式系统架构视频教程,吴水成,wu-sc@foxmail.com,学习交流QQ群:367211134 -->  
  12.       
  13.     <!-- Spring提供的发送电子邮件的高级抽象类 -->  
  14.     <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  15.         <property name="host" value="${mail.host}" />  
  16.         <property name="username" value="${mail.username}" />  
  17.         <property name="password" value="${mail.password}" />  
  18.         <property name="defaultEncoding" value="UTF-8"></property>  
  19.         <property name="javaMailProperties">  
  20.             <props>  
  21.                 <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>  
  22.                 <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>  
  23.             </props>  
  24.         </property>  
  25.     </bean>  
  26.   
  27.     <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">  
  28.         <property name="from">  
  29.             <value>${mail.default.from}</value>  
  30.         </property>  
  31.     </bean>  
  32.       
  33.     <!-- 配置线程池 -->  
  34.     <bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">  
  35.         <!-- 线程池维护线程的最少数量 -->  
  36.         <property name="corePoolSize" value="5" />  
  37.         <!-- 线程池维护线程所允许的空闲时间 -->  
  38.         <property name="keepAliveSeconds" value="30000" />  
  39.         <!-- 线程池维护线程的最大数量 -->  
  40.         <property name="maxPoolSize" value="50" />  
  41.         <!-- 线程池所使用的缓冲队列 -->  
  42.         <property name="queueCapacity" value="100" />  
  43.     </bean>  
  44.   
  45. </beans>  

队列监听器
[java]  view plain  copy
  1. /** 
  2.  *  
  3.  * @描述: 队列监听器 . 
  4.  * @作者: WuShuicheng . 
  5.  * @创建时间: 2015-3-17,下午11:21:23 . 
  6.  * @版本号: V1.0 . 
  7.  */  
  8. @Component  
  9. public class ConsumerSessionAwareMessageListener implements SessionAwareMessageListener<Message> {  
  10.   
  11.     private static final Log log = LogFactory.getLog(ConsumerSessionAwareMessageListener.class);  
  12.   
  13.     @Autowired  
  14.     private JmsTemplate activeMqJmsTemplate;  
  15.     @Autowired  
  16.     private Destination sessionAwareQueue;  
  17.     @Autowired  
  18.     private MailBiz bailBiz;  
  19.   
  20.     public synchronized void onMessage(Message message, Session session) {  
  21.         try {  
  22.             ActiveMQTextMessage msg = (ActiveMQTextMessage) message;  
  23.             final String ms = msg.getText();  
  24.             log.info("==>receive message:" + ms);  
  25.             MailParam mailParam = JSONObject.parseObject(ms, MailParam.class);// 转换成相应的对象  
  26.             if (mailParam == null) {  
  27.                 return;  
  28.             }  
  29.   
  30.             try {  
  31.                 bailBiz.mailSend(mailParam);  
  32.             } catch (Exception e) {  
  33.                 // 发送异常,重新放回队列  
  34. //              activeMqJmsTemplate.send(sessionAwareQueue, new MessageCreator() {  
  35. //                  public Message createMessage(Session session) throws JMSException {  
  36. //                      return session.createTextMessage(ms);  
  37. //                  }  
  38. //              });  
  39.                 log.error("==>MailException:", e);  
  40.             }  
  41.         } catch (Exception e) {  
  42.             log.error("==>", e);  
  43.         }  
  44.     }  
  45. }  

发送邮件的业务逻辑
[java]  view plain  copy
  1. @Component("mailBiz")  
  2. public class MailBiz {  
  3.   
  4.     @Autowired  
  5.     private JavaMailSender mailSender;// spring配置中定义  
  6.     @Autowired  
  7.     private SimpleMailMessage simpleMailMessage;// spring配置中定义  
  8.     @Autowired  
  9.     private ThreadPoolTaskExecutor threadPool;  
  10.   
  11.     /** 
  12.      * 发送模板邮件 
  13.      *  
  14.      * @param mailParamTemp需要设置四个参数 
  15.      *            templateName,toMail,subject,mapModel 
  16.      * @throws Exception 
  17.      *  
  18.      */  
  19.     public void mailSend(final MailParam mailParam) {  
  20.         threadPool.execute(new Runnable() {  
  21.             public void run() {  
  22.                 try {  
  23.                     simpleMailMessage.setFrom(simpleMailMessage.getFrom()); // 发送人,从配置文件中取得  
  24.                     simpleMailMessage.setTo(mailParam.getTo()); // 接收人  
  25.                     simpleMailMessage.setSubject(mailParam.getSubject());  
  26.                     simpleMailMessage.setText(mailParam.getContent());  
  27.                     mailSender.send(simpleMailMessage);  
  28.                 } catch (MailException e) {  
  29.                     throw e;  
  30.                 }  
  31.             }  
  32.         });  
  33.     }  

spring启动类
[java]  view plain  copy
  1. /** 
  2.  *  
  3.  * @描述: ActiveMQ测试启动类  . 
  4.  * @作者: WuShuicheng . 
  5.  * @创建时间: 2015-3-17,上午2:25:20 . 
  6.  * @版本号: V1.0 . 
  7.  */  
  8. public class MQConsumer {  
  9.     private static final Log log = LogFactory.getLog(MQConsumer.class);  
  10.   
  11.     public static void main(String[] args) {  
  12.         try {  
  13.             ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/spring-context.xml");  
  14.             context.start();  
  15.         } catch (Exception e) {  
  16.             log.error("==>MQ context start error:", e);  
  17.             System.exit(0);  
  18.         }  
  19.     }  
  20. }  
公共的邮件参数Bean
[java]  view plain  copy
  1. /** 
  2.  *  
  3.  * @描述: 邮件参数封装类 . 
  4.  * @作者: WuShuicheng . 
  5.  * @创建时间: 2015-3-18,上午1:08:42 . 
  6.  * @版本号: V1.0 . 
  7.  */  
  8. public class MailParam {  
  9.   
  10.     /** 发件人 **/  
  11.     private String from;  
  12.     /** 收件人 **/  
  13.     private String to;  
  14.     /** 主题 **/  
  15.     private String subject;  
  16.     /** 邮件内容 **/  
  17.     private String content;  
  18.   
  19.     public MailParam() {  
  20.     }  
  21.   
  22.     public MailParam(String to, String subject, String content) {  
  23.         this.to = to;  
  24.         this.subject = subject;  
  25.         this.content = content;  
  26.     }.....省略getter/setter  


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值