入门篇,高手绕道。呵呵
ActiveMQ和jms的特性
jms特点:
(1)可以把不影响用户执行结果又比较耗时的任务(比如大批量发邮件,发短信)异步的扔给jms 服务端,
而尽快的把屏幕返还给用户,且服务端能够多线程排队响应高并发的请求。
(2)可以在java世界里达到最高的解耦。客户端与服务端无需直连,甚至无需知晓对方是谁、在哪里、有多
少人,只要对流过的信息作响应就行了,在企业应用环境复杂时作用明显。
ActiveMQ的特点:
(1)不需要实现ejb繁琐复杂的message bean接口和配置。
(2)可以使用spring的各种特性如ioc、aop 。
(3)基于jencks的jca container实现 pool connection,control transactions and manage security。
一个jms场景通常需要三者参与:
一个pojo的的message producer,负责使用spring的jms template发送消息。
一个message converter,负责把java对象转化为消息,使得producer能够直接发送pojo。
一个mdp message consumer,负责接收并处理消息。
本例中给出一个使用activemq实现的有助于加深对jms机制理解的简单例子。
首先下载activemq 下载地址
http://www.apache.org/dyn/closer.cgi/activemq/apache-activemq/5.2.0/apache-activemq-5.2.0-bin.tar.gz
运行 mq目录\bin\activemq.bat ,启动mq服务。
1 生产者代码
package com.travelsky.jms;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
/**
* @author songning
*/
public class JMSProducer {
/**
* @param args
* @throws JMSException
*/
public static void main(String[] args) throws JMSException {
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection conn = factory.createConnection();
conn.start();
Queue queue = new ActiveMQQueue("helloQueue");
final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
for(int i=0;i<10;i++)
{
producer.send(session.createTextMessage("hello world"+i));
}
System.out.println("send over");
}
}
2消费者代码
package com.travelsky.jms;
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.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
/**
* @author songning
*/
public class Consumer {
/**
* @param args
* @throws JMSException
*/
public static void main(String[] args) throws JMSException {
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection conn = factory.createConnection();
conn.start();
Queue queue = new ActiveMQQueue("helloQueue");
final Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener(){
@Override
public void onMessage(Message msg1){
System.out.println(msg1.toString());
}
});
}
}