背景:ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。
选择ActiveMQ作为JMS的入门学习中间件,是因为其拥有以下优点
1.多种语言和协议编写客户端。语言: Java, C, C++, C#, Ruby, Perl, Python, PHP。应用协议: OpenWire,Stomp REST,WS Notification,XMPP,AMQP
2.完全支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务)
3.对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性
4.完全支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务)
5.通过了常见J2EE服务器(如 Geronimo,JBoss 4, GlassFish,WebLogic)的测试,其中通过JCA 1.5 resource adaptors的配置,可以让ActiveMQ可以自动的部署到任何兼容J2EE 1.4 商业服务器上
6.支持多种传送协议:in-VM,TCP,SSL,NIO,UDP,JGroups,JXTA
7.从设计上保证了高性能的集群,客户端-服务器,点对点
8.支持Ajax
9.支持与Axis的整合
10.可以很容易得调用内嵌JMS provider,进行测试
学会了ActiveMQ之后,其它供应商的MQ也可以在短时间内快速上手。
安装:
ActiveMQ(本文简称MQ)要求JDK1.5以上,推荐1.6以上版本。还没安装JDK的朋友,请先安装,在此不赘诉了。
安装完JDK后,从 http://activemq.apache.org/download.html下载MQ的最新版本,本教程使用版本为5.5。
解压后,可以看到MQ目录下有以下文件和目录
activemq-all-5.5.0.jar:所有MQ JAR包的集合,用于用户系统调用
bin:其中包含MQ的启动脚本
conf:包含MQ的所有配置文件
data:日志文件及持久性消息数据
example:MQ的示例
lib:MQ运行所需的所有Lib
webapps:MQ的Web控制台及一些相关的DEMO
启动MQ:
双击bin目录下的activemq.bat文件即可启动MQ
第一个示例:
新建一个JAVA工程,引用activemq-all-5.5.0.jar,SLFAPI其及对应版本LOG4J的JAR包(懒的上网找的到附件里下载)
Publisher.java
Java代码
- import java.util.Hashtable;
- import java.util.Map;
-
- import javax.jms.Connection;
- import javax.jms.ConnectionFactory;
- import javax.jms.Destination;
- import javax.jms.JMSException;
- import javax.jms.MapMessage;
- import javax.jms.Message;
- import javax.jms.MessageProducer;
- import javax.jms.Session;
-
- import org.apache.activemq.ActiveMQConnectionFactory;
- import org.apache.activemq.command.ActiveMQMapMessage;
-
- public class Publisher {
-
- protected int MAX_DELTA_PERCENT = 1;
- protected Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
- protected static int count = 10;
- protected static int total;
-
- protected static String brokerURL = "tcp://localhost:61616";
- protected static transient ConnectionFactory factory;
- protected transient Connection connection;
- protected transient Session session;
- protected transient MessageProducer producer;
-
- public Publisher() throws JMSException {
- factory = new ActiveMQConnectionFactory(brokerURL);
- connection = factory.createConnection();
- try {
- connection.start();
- } catch (JMSException jmse) {
- connection.close();
- throw jmse;
- }
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- producer = session.createProducer(null);
- }
-
- public void close() throws JMSException {
- if (connection != null) {
- connection.close();
- }
- }
-
- public static void main(String[] args) throws JMSException {
- Publisher publisher = new Publisher();
- while (total < 1000) {
- for (int i = 0; i < count; i++) {
- publisher.sendMessage(args);
- }
- total += count;
- System.out.println("Published '" + count + "' of '" + total + "' price messages");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException x) {
- }
- }
- publisher.close();
- }
-
- protected void sendMessage(String[] stocks) throws JMSException {
- int idx = 0;
- while (true) {
- idx = (int)Math.round(stocks.length * Math.random());
- if (idx < stocks.length) {
- break;
- }
- }
- String stock = stocks[idx];
- Destination destination = session.createTopic("STOCKS." + stock);
- Message message = createStockMessage(stock, session);
- System.out.println("Sending: " + ((ActiveMQMapMessage)message).getContentMap() + " on destination: " + destination);
- producer.send(destination, message);
- }
-
- protected Message createStockMessage(String stock, Session session) throws JMSException {
- Double value = LAST_PRICES.get(stock);
- if (value == null) {
- value = new Double(Math.random() * 100);
- }
-
- // lets mutate the value by some percentage
- double oldPrice = value.doubleValue();
- value = new Double(mutatePrice(oldPrice));
- LAST_PRICES.put(stock, value);
- double price = value.doubleValue();
-
- double offer = price * 1.001;
-
- boolean up = (price > oldPrice);
-
- MapMessage message = session.createMapMessage();
- message.setString("stock", stock);
- message.setDouble("price", price);
- message.setDouble("offer", offer);
- message.setBoolean("up", up);
- return message;
- }
-
- protected double mutatePrice(double price) {
- double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT) - MAX_DELTA_PERCENT;
-
- return price * (100 + percentChange) / 100;
- }
-
- }
Consumer.java
Java代码
- import javax.jms.Connection;
- import javax.jms.ConnectionFactory;
- import javax.jms.Destination;
- import javax.jms.JMSException;
- import javax.jms.MessageConsumer;
- import javax.jms.Session;
-
- import org.apache.activemq.ActiveMQConnectionFactory;
-
- public class Consumer {
-
- private static String brokerURL = "tcp://localhost:61616";
- private static transient ConnectionFactory factory;
- private transient Connection connection;
- private transient Session session;
-
- public Consumer() throws JMSException {
- factory = new ActiveMQConnectionFactory(brokerURL);
- connection = factory.createConnection();
- connection.start();
- session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- public void close() throws JMSException {
- if (connection != null) {
- connection.close();
- }
- }
-
- public static void main(String[] args) throws JMSException {
- Consumer consumer = new Consumer();
- for (String stock : args) {
- Destination destination = consumer.getSession().createTopic("STOCKS." + stock);
- MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination);
- messageConsumer.setMessageListener(new Listener());
- }
- }
-
- public Session getSession() {
- return session;
- }
-
- }
Listener.java
Java代码
- import java.text.DecimalFormat;
-
- import javax.jms.MapMessage;
- import javax.jms.Message;
- import javax.jms.MessageListener;
-
- public class Listener implements MessageListener {
-
- public void onMessage(Message message) {
- try {
- MapMessage map = (MapMessage)message;
- String stock = map.getString("stock");
- double price = map.getDouble("price");
- double offer = map.getDouble("offer");
- boolean up = map.getBoolean("up");
- DecimalFormat df = new DecimalFormat( "#,###,###,##0.00" );
- System.out.println(stock + "\t" + df.format(price) + "\t" + df.format(offer) + "\t" + (up?"up":"down"));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- }
先运行Consumer.java, 输入参数ORCL,然后运行Publisher.java,输入参数ORCL,
就可以看到Publisher在发送消息,Consumer在接收消息了。
好了,MQ的安装与第一个示例程序的介绍就到此为止了。