先把代码贴上来,可以在此处下载到源码http://download.csdn.net/detail/licheng989/9586328
简要说明:
package activemqDemo01;
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;
/**
* 消息生产者(produceer):用于把消息发送到一个目的地
*
* @author licheng
*
*/
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;
/**
* brokerURL为连接配置参数,是ActiveMQ服务地址和端口号,支持openwire协议的默认连接为tcp://localhost:61616,
* 支持stomp协议的默认连接为tcp://localhost:61613
*/
protected static String brokerURL = "tcp://127.0.0.1:61616";
/**
* 连接工程(ConnectionFactory)
* 连接工厂是客户用来创建连接的对象
* 例如:ActiveMQ提供的ActiveMQConnectionFactory.注意(要初始化JMS,则需要使用连接工厂.
* 客户端通过创建ConnectionFactory建立到ActiveMQ的连接,一个连接工厂封装了一组连接配置参数,这组参数在配置ActiveMQ时已定义,
* 例如brokerURL参数,此参数传入的是ActiveMQ服务地址和端口,支持openwire协议的默认连接为tcp://localhost:61616,
* 支持stomp协议的默认连接为tcp://localhost:61613)
*/
protected static transient ConnectionFactory factory;
/**
* 连接(Connection)
* Connection封装了客户与JMS提供者之间的一个虚拟的连接
* 注意:当一个Connection被创建时,它的传输默认是关闭的,必须使用start方法开启.
* 一个Connection可以建立一个或多个Session.当一个程序执行完成后,必须关闭之前创建的Connection,否则ActiveMQ不能释放资源,
* 关闭一个Connection同样也关闭了Session,MessageProducer和MessageConsumer.
*/
protected transient Connection connection;
/**
* 会话(Session)
* Session是生产和消费消息的一个单线程上下文.
* 会话用于创建消息生产者(producer),消息消费者(consumer)和消息(message)等.
* 会话提供了一个事务性的上下文,在这个上下文中,一组发送和接受被组合到了一个原子操作中
*/
protected transient Session session;
protected transient MessageProducer producer;
public Publisher() throws JMSException {
// 通过JNDI查找ConnectionFactory
factory = new ActiveMQConnectionFactory(brokerURL);
// 用ConnectionFactory创建一个Connection
connection = factory.createConnection();
// 启动Connection
connection.start();
// 用Connection创建一个或多个Session
/**
* 消息发送出去之后的确认模式,应用程序创建的会话一般有5种确认模式(非实物)
* AUTO_ACKNOWLEDGE:自动确认模式.一旦接收方应用程序的方法调用从处理消息处返回,会话对象就会确认消息的接受
* false参数表示为非事务型消息
*/
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// 用session创建所需的MessageProducer
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];
/**
* 目的地
* 目的地是客户用来指定它的消息的目标和它消费的消息的来源的对象
* 在发布/订阅(PUB/SUB)消息,目的地被称为主题(topic)
*/
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;
}
}
package activemqDemo01;
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;
/**
* 消息消费者(consumer):它用于接收发送到目的地的消息
* @author licheng
*
*/
public class Consumer {
private static String brokerURL = "tcp://127.0.0.1:61616";
private static transient ConnectionFactory factory;
private transient Connection connection;
private transient Session session;
public Consumer() throws JMSException {
// 通过JNDI查找ConnectionFactory
factory = new ActiveMQConnectionFactory(brokerURL);
// 用ConnectionFactory创建一个Connection
connection = factory.createConnection();
// 启动Connection
connection.start();
// 用Connection创建一个或者多个session
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) {
// 用Session创建一个Destination
Destination destination = consumer.getSession().createTopic("STOCKS." + stock);
// 用Destination创建所需的MessageConsumer
MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination);
/**
* 异步消费:客户可以为消费者注册一个消息监听器(Listener),已定义在消息到达时所采取的动作.
* 另一种消费方式是同步消费:通过调用消费者的receive方法从目的地中显示提取消息,receive方法可以一直阻塞到消息到达
* 接收消息方式1:消息的异步接收
*/
messageConsumer.setMessageListener(new Listener());
}
}
public Session getSession() {
return session;
}
}
package activemqDemo01;
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();
}
}
}