1.使用了连接池工厂的生产者
package com.imooc.jms;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
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.pool.PooledConnectionFactory;
/**
* JMS消息生产者
*/
public class JmsProducerWithThreadPool {
//设置连接的最大连接数(表示PooledConnectionFactory中的LinkedList中的Connection的数目) ---尽可能大
public final static int DEFAULT_MAX_CONNECTIONS = 5;
//设置每个连接中使用的最大活动会话数(表示Connection中SessionPool中Session的数目)---尽可能小
public final static int DEFAULT_MAXIMUM_ACTIVE_SESSION_PER_CONNECTION = 300;
//线程池数量
public final static int DEFAULT_THREAD_POOL_SIZE = 50;
//使用同步返回数据的格式 ,
public final static boolean DEFAULT_USE_ASYNC_SEND_FOR_JMS = true;
//是否持久化消息,默认持久化
public final static boolean DEFAULT_IS_PERSISTENT = true;
private int maxConnections = DEFAULT_MAX_CONNECTIONS;
private int maximumActiveSessionPerConnection = DEFAULT_MAXIMUM_ACTIVE_SESSION_PER_CONNECTION;
private int threadPoolSize = DEFAULT_THREAD_POOL_SIZE;
private boolean useAsyncSendForJMS = DEFAULT_USE_ASYNC_SEND_FOR_JMS;
private boolean isPersistent = DEFAULT_IS_PERSISTENT;
private String brokerUrl;
private String userName;
private String password;
private ExecutorService threadPool;
/**
* 连接池工厂:
* PooledConnectionFactory内部维护了一个Map,键是由用户的username和password决定的;
* 值是由一个LinkedList维护的ActivemqConnection的循环链表,每次从LikedLsit中的头部取出一个connection
* ,然后再添加到尾部,简单的轮询是的负载均衡。每次发送或接受时先从ConnectionPool中取出一个,如果connection
* 都用光了,就会重用在链表头部的Connection的SessionPool,所以一个Connection可能会被多个线程使用。而上面
* 提到的负载均衡也没有考虑到session的使用情况,可能从头部拿出的SessionPool已经被耗光了,尾部的connection
* session pool 却很空闲.
*/
private PooledConnectionFactory connectionFactory;
public JmsProducerWithThreadPool(String brokerUrl,String userName,String password) {
this(DEFAULT_MAX_CONNECTIONS, DEFAULT_MAXIMUM_ACTIVE_SESSION_PER_CONNECTION,
DEFAULT_THREAD_POOL_SIZE, DEFAULT_USE_ASYNC_SEND_FOR_JMS, brokerUrl, userName, password);
}
public JmsProducerWithThreadPool(int maxConnections,
int maximumActiveSessionPerConnection, int threadPoolSize,
boolean useAsyncSendForJMS, String brokerUrl, String userName,
String password) {
super();
this.maxConnections = maxConnections;
this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection;
this.threadPoolSize = threadPoolSize;
this.useAsyncSendForJMS = useAsyncSendForJMS;
this.brokerUrl = brokerUrl;
this.userName = userName;
this.password = password;
init();
}
private void init() {
//设置JAVA线程池
this.threadPool = Executors.newFixedThreadPool(this.threadPoolSize);
//ActiveMQ的连接工厂
ActiveMQConnectionFactory actualConnectionFactory = new ActiveMQConnectionFactory(userName, password, brokerUrl);
actualConnectionFactory.setUseAsyncSend(useAsyncSendForJMS);
//ActiveMQ的连接池工厂
this.connectionFactory = new PooledConnectionFactory(actualConnectionFactory);
this.connectionFactory.setCreateConnectionOnStartup(true);
//连接池的最大连接数应该尽量设置的大些
this.connectionFactory.setMaxConnections(maxConnections);
this.connectionFactory.setMaximumActiveSessionPerConnection(maximumActiveSessionPerConnection);
}
/**
* 发送消息
*/
private void sendMsg(String queue,Map<String,Object> map) {
Connection connection = null;
Session session = null;
try {
connection = this.connectionFactory.createConnection();
/**
* 第一个参数:事务支持
* 1.当会话以非事务的方式开启时,直接session.close就可以将消息提交到服务器队列
* 2.当会话以开启事务的方式时,必须调用session.commit才能将消息提交到服务器队列
* 第二个参数:
*/
session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(queue);
MessageProducer producer = session.createProducer(destination);
//设置消息的持久化模式
producer.setDeliveryMode(this.isPersistent ? DeliveryMode.PERSISTENT
: DeliveryMode.NON_PERSISTENT);
//map convert to javax message
Message message = getMessage(session, map);
producer.send(message);
} catch (JMSException e) {
e.printStackTrace();
} finally {
closeSession(session);
closeConnection(connection);
}
}
private Message getMessage(Session session,Map<String,Object> map) throws JMSException {
MapMessage message = session.createMapMessage();
if(map != null && !map.isEmpty()) {
Set<String> keys = map.keySet();
for(String key : keys) {
message.setObject(key, map.get(key));
}
}
return message;
}
private void closeSession(Session session) {
try {
if(session != null) {
session.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
private void closeConnection(Connection connection) {
try {
if(connection != null) {
connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
package com.imooc.jms;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQPrefetchPolicy;
/**
*
* Session:
* 服务端:producer或者ActiveMQ服务
* 客户端:ActiveMQ服务或者consumer
*
* 客户端成功接收一条消息的标志是这条消息被签收,成功接收一条消息一般包括三个阶段:
* 1.客户端接收消息;2.客户端处理消息;3.消息被签收。
* session = connection.createSession(Boolean.false,Session.CLIENT_ACKNOWLEDGE);
* 第一个参数控制事务,第二个参数控制消息
*
* A.在不带事务的Session中,消息何时和如何被签收取决于Session设置
* 1.Session.AUTO_ACKNOWLEDGE :当客户端从receive或者onMessage成功返回时,Session自动签收客户端的这条消息收条;
* 2.Session.CLENT_ACKNOWLEDGE:客户端通过调用消息的acknowledge方法签收消息。message.acknowledge();
*
* B.在带事务的Session中,签收自动发生在事务提交时,如果事务回滚,所有已接受的消息会被再次传送。
*
* 总结:
* 1.对于生产者:服务端为producer,客户端为ActiveMQ服务。Session设置为AUTO_ACKNOWLEDGE和CLENT_ACKNOWLEDGE,区别不大
* 2.对于消费者:服务端为ActiveMQ服务,客户端为consumer。Session设置为AUTO_ACKNOWLEDGE,接收到消息(receive或
* onMessage成功返回时)即为消费成功,然后从队里移除该数据。不关系该数据有没有正确被处理成我们想要的结果;Session设置为
* CLIENT_ACKNOWLEGE时,必须手动调用acknowledge方法才为消费成功。然后从队列里移除该条数据。
* 3.producer和consumer的Session设置成哪种模式,互不影响。
*
*/
public class JmsConsumerWithThreadPool {
public final static int DEFAULT_QUEUE_PREFETCH = 10;
//队列预取策略
private int queuePrefetch = DEFAULT_QUEUE_PREFETCH;
private String brokerUrl;
private String userName;
private String password;
private MessageListener messageListener;
private Connection connection;
private Session session;
//队列名
private String queue;
public JmsConsumerWithThreadPool() {
super();
}
public JmsConsumerWithThreadPool(int queuePrefetch, String brokerUrl,
String userName, String password, MessageListener messageListener,
String queue) {
super();
this.queuePrefetch = queuePrefetch;
this.brokerUrl = brokerUrl;
this.userName = userName;
this.password = password;
this.messageListener = messageListener;
this.queue = queue;
}
public void start() throws JMSException {
/**
* 消费者不使用连接池的原因:消费者需要与MQ保持长连接;
*/
//ActiveMQ的连接工厂
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password,
brokerUrl);
connection = connectionFactory.createConnection();
//activeMQ预取策略 ,MQ向消费者每次推送的消息数目
ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy();
prefetchPolicy.setQueuePrefetch(queuePrefetch);
((ActiveMQConnection)connection).setPrefetchPolicy(prefetchPolicy);
connection.start();
//会话采用非事务级别,消息到达机制使用自动通知机制
this.session = connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(this.queue);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(messageListener);
}
/**
* 关闭连接
*/
public void shutdown() {
try {
if(session != null) {
session.close();
}
if(connection != null) {
connection.close();
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}