ActiveMQ笔记

ActiveMQ为java消息服务(JMS)框架,它分为两种模式一种为点对点Queue,另一种为发布/订阅Topic模式。

一条JMS消息分为消息头、消息属性、消息类型。

ActiveMQ下载官网(Linux版本apache-activemq-5.9.0):http://activemq.apache.org/activemq-590-release.html

安装方法:

下载后可直接运行,运行命令:bin\activemq start

停止命令:bin\activemq stop

运行后,可查看运行端口:netstat -an|grep 61616

如果bin\activemq stop没有停止服务,可采用kill进行终止服务:

ps -ef|grep activemq
kill [PID]

官方文档:http://activemq.apache.org/version-5-getting-started.html#Version5GettingStarted-TestingtheInstallation

启动后的ActiveMQ如下图:


ActiveMQ启动后,下面分别以Queue点对点和Topic发布/订阅两种模式写实例代码:

建一个maven的java工程,需要用到的包在pom.xml中配置(如不是maven工程,下载的ActiveMQ中有相应的包,拷到工程即可):

<!-- ActiveMQ -->
    <dependency>
		 <groupId>org.apache.activemq</groupId>
		 <artifactId>activemq-all</artifactId>
		 <version>5.9.0</version>
	</dependency>
	<dependency>
		<groupId>org.apache.geronimo.specs</groupId>
		<artifactId>geronimo-j2ee-management_1.1_spec</artifactId>
		<version>1.0.1</version>
	</dependency>
	<dependency>
		<groupId>org.apache.geronimo.specs</groupId>
		<artifactId>geronimo-jms_1.1_spec</artifactId>
		<version>1.1.1</version>
	</dependency>


点对点:

接收者

package com.activemq.one;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.activemq.util.Constants;

/**
 * 接收者
 * 
 * @author Dwen
 * @version v 0.1 2014-1-22 下午03:02:48
 */
public class Receiver {

	/**
	 * 程序入口
	 * @param args
	 */
	public static void main(String[] args) {
		// 连接工厂
		ConnectionFactory connectionFactory;
		//连接
		Connection connection = null;
		//会话
		Session session;
		// Destination :消息的目的地;消息发送给谁.
		Destination destination;
		// 消费者
		MessageConsumer consumer;
		connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, Constants.BROKER_URL);
		try {
			// 构造从工厂得到连接对象
			connection = connectionFactory.createConnection();
			// 启动
			connection.start();
			// 获取操作连接
			session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
			//获取session中的queue,该queue在http://localhost:8161/admin/queues.jsp中进行配置
			destination = session.createQueue("FirstQueue");
			consumer = session.createConsumer(destination);
			while (true) {
//				reveiveTextMessage(consumer);
				reveiveObjectMessage(consumer);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != connection)
					connection.close();
			} catch (Throwable ignore) {
			}
		}
	}
	
	/**
	 * 接收文本消息
	 * @param consumer
	 * @throws JMSException
	 */
	private static void reveiveTextMessage(MessageConsumer consumer) throws JMSException{
		// 设置接收者接收消息的时间,测试定为100s
		TextMessage message = (TextMessage) consumer.receive(100000);
		if (null != message) {
			System.out.println("收到消息" + message.getText());
		} else {
			System.out.println("无消息!");
		}
	}
	
	/**
	 * 接收对象消息
	 * @param consumer
	 * @throws JMSException
	 */
	private static void reveiveObjectMessage(MessageConsumer consumer) throws JMSException{
		ObjectMessage message = (ObjectMessage) consumer.receive();
		Users users = (Users) message.getObject();
		if (null != users) {
			System.out.println("收到消息" + users.getId()+" , "+users.getUserName()+" , "+users.getPassword());
		} else {
			System.out.println("无消息!");
		}
	}

}
发送者

package com.activemq.one;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.activemq.util.Constants;

/**
 * 发送者
 * 
 * @author Dwen
 * @version v 0.1 2014-1-22 下午03:01:27
 */
public class Sender {
	/** 定义发送数量 */
	private static final int SEND_NUMBER = 5;

	/**
	 * 程序入口
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		// 连接工厂
		ConnectionFactory connectionFactory;
		// 连接
		Connection connection = null;
		// 会话
		Session session;
		// 消息的目的地;消息发送给谁.
		Destination destination;
		// 消息发送者
		MessageProducer producer;
		// 构造ConnectionFactory实例对象
		connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, Constants.BROKER_URL);
		try {
			// 构造从工厂得到连接对象
			connection = connectionFactory.createConnection();
			// 启动
			connection.start();
			// 获取操作连接
			session = connection.createSession(Boolean.TRUE,
					Session.AUTO_ACKNOWLEDGE);
			// 获取session中的queue,该queue在http://localhost:8161/admin/queues.jsp中进行配置
			destination = session.createQueue("FirstQueue");
			// 得到消息生成者
			producer = session.createProducer(destination);
			// 设置不持久化,此处学习,实际根据项目决定
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			//消息类型:
			// Message,TextMessage,ObjectMessage,BytesMessage,StreamMessage,MapMessage
			// 发送消息
//			sendMessage(session, producer);
			sendObjectMessage(session, producer);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != connection)
					connection.close();
			} catch (Throwable ignore) {
			}
		}
	}

	/**
	 * 发送文本消息
	 * @param session
	 * @param producer
	 * @throws Exception
	 */
	public static void sendMessage(Session session, MessageProducer producer)
			throws Exception {
		for (int i = 1; i <= SEND_NUMBER; i++) {
			TextMessage message = session.createTextMessage("ActiveMq 发送的消息+"
					+ i);
			// 发送消息到目的地方
			System.out.println("发送消息:" + "ActiveMq 发送的消息" + i);
			producer.send(message);
		}
	}

	/**
	 * 发送对象消息
	 * @param session
	 * @param producer
	 * @throws Exception
	 */
	public static void sendObjectMessage(Session session,
			MessageProducer producer) throws Exception {
		Users users = new Users();
		users.setId(1000L);
		users.setUserName("test");
		users.setPassword("111111");
		ObjectMessage message = session.createObjectMessage(users);
		System.out.println("已发送对象消息!");
		producer.send(message);
	}
}
package com.activemq.util;
/**
 * 常量类
 * @author Dwen
 * @version v 0.1 2014-1-22 下午05:32:13
 */
public class Constants {

	/** activemq url */
	public static final String BROKER_URL = "tcp://localhost:61616";
}


发布/订阅:

package com.activemq.many;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.activemq.util.Constants;

/**
 * 发布者
 * @author Dwen
 * @version v 0.1 2014-1-22 下午05:11:09
 */
public class Publisher {
	
	public static void main(String[] args) {
		// 连接工厂
		ConnectionFactory connectionFactory;
		//连接
		Connection connection = null;
		//会话
		Session session;
		// 消息发送者
		MessageProducer producer;
		connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, Constants.BROKER_URL);
		try {
			// 构造从工厂得到连接对象
			connection = connectionFactory.createConnection();
			// 启动
			connection.start();
			// 获取操作连接
			session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
			//创建Topic
			Topic topic = session.createTopic("FirstTopic");
			producer = session.createProducer(topic);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			while (true) {
				sendMessage(session, producer);
				Thread.sleep(2000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != connection){
					connection.close();
				}
			} catch (Throwable ignore) {
			}
		}
	}
	
	/**
	 * 发送文本消息
	 * @param session
	 * @param producer
	 * @throws Exception
	 */
	public static void sendMessage(Session session, MessageProducer producer)
			throws Exception {
			TextMessage message = session.createTextMessage("ActiveMq 发送的消息_"+System.currentTimeMillis());
			// 发送消息到目的地方
			producer.send(message);
			System.out.println("发送消息:" + message.getText());
	}
}

package com.activemq.many;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.activemq.util.Constants;

/**
 * 订阅者
 * 
 * @author Dwen
 * @version v 0.1 2014-1-22 下午05:10:57
 */
public class Subscribers {

	public static void main(String[] args) {
		// 连接工厂
		ConnectionFactory connectionFactory;
		// 连接
		Connection connection = null;
		// 会话
		Session session;
		// 消费者
		MessageConsumer consumer;
		connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, Constants.BROKER_URL);
		try {
			// 构造从工厂得到连接对象
			connection = connectionFactory.createConnection();
			// 启动
			connection.start();
			// 获取操作连接
			session = connection.createSession(Boolean.FALSE,
					Session.AUTO_ACKNOWLEDGE);
			// 创建Topic
			Topic topic = session.createTopic("FirstTopic");
			consumer = session.createConsumer(topic);
			consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message message) {
					TextMessage message2 = (TextMessage) message;
					try {
						System.out.println("收到消息:" + message2.getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		} 
//		finally {
//			try {
//				if (null != connection) {
//					connection.close();
//				}
//			} catch (Throwable ignore) {
//			}
//		}
	}
}

ActiveMQ访问安全问题,如果不进行安全访问,任何人只有知道activeqm的地址就可以访问。限制如下:

修改ActiveMQ管理页面密码在jetty-realm.properties文件中修改,里面有相应格式为:用户名:密码,角色

客户端访问安全设置:

1、在credentials.properties文件中设置用户名和密码。通过credentials-enc.properties可以用户名密码进行加密,官方

文档地址:http://activemq.apache.org/encrypted-passwords.html

activemq.username=system
activemq.password=manager
user.username=user
user.password=password
guest.username=guest
guest.password=password

2、在activemq.xml文件systemUsage标签之前加上

<plugins>
	<simpleAuthenticationPlugin>
    	<users>
	<authenticationUser username="${activemq.username}" password="${activemq.password}"
            groups="users,admins"/>
        <authenticationUser username="${user.username}" password="${user.password}"
            groups="users"/>
        <authenticationUser username="${guest.username}" password="${guest.password}" groups="guests"/>
        <!--<authenticationUser username="system" password="manager"
            groups="users,admins"/>
        <authenticationUser username="user" password="password"
            groups="users"/>
        <authenticationUser username="guest" password="password" groups="guests"/> -->
    	</users>
	</simpleAuthenticationPlugin>

      <!--  use JAAS to authenticate using the login.config file on the classpath to configure JAAS -->
      <jaasAuthenticationPlugin configuration="activemq" />
 
      <!--  lets configure a destination based authorization mechanism -->
      <authorizationPlugin>
        <map>
          <authorizationMap>
            <authorizationEntries>
              <authorizationEntry queue=">" read="admins" write="admins" admin="admins" />
              <authorizationEntry queue="USERS.>" read="users" write="users" admin="users" />
              <authorizationEntry queue="GUEST.>" read="guests" write="guests,users" admin="guests,users" />
               
              <authorizationEntry topic=">" read="admins" write="admins" admin="admins" />
              <authorizationEntry topic="USERS.>" read="users" write="users" admin="users" />
              <authorizationEntry topic="GUEST.>" read="guests" write="guests,users" admin="guests,users" />
               
              <authorizationEntry topic="ActiveMQ.Advisory.>" read="guests,users" write="guests,users" admin="guests,users"/>
            </authorizationEntries>
             
            <!-- let's assign roles to temporary destinations. comment this entry if we don't want any roles assigned to temp destinations  -->
            <tempDestinationAuthorizationEntry>  
              <tempDestinationAuthorizationEntry read="tempDestinationAdmins" write="tempDestinationAdmins" admin="tempDestinationAdmins"/>
           </tempDestinationAuthorizationEntry>               
          </authorizationMap>
        </map>
      </authorizationPlugin>
    </plugins>
3、在users.properties文件中设置用户名和密码

system=manager
user=password
guest=password
在groups.properties文件中设置组,设置允许的权限组才会有相应的访问权限

admins=system,user,guest
login.config文件配置中指定了users.properties和groups.properties

设置了用户名和密码就可以进行安全限制访问了。



配置过程中问题:

出现:activemq javax.security.auth.login.LoginException: 没有为 activemq-domain 配置LoginModules。是因为activemq.xml文件中<jaasAuthenticationPlugin configuration="activemq" />configuration指定的名字与conf/login.config文件中的名称不一致。


接下来要讨论以下两个问题:持久化问题和集群问题。

讨论下ActiveMQ持久化问题,由于保证信息在异常情况下没有发送出去,导致信息丢失的情况。消息服务器发送消息前先进行持久化,如果消息成功发送出去了,根据返回的消息来是否删除持久化消息,返回成功消息则删除持久化信息,反之,则异常恢复正常后继续发送,直到成功为止。


待续。。。。。。

研究完如何使用后,最后要研究下源码的实现。





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值