JMS和消息驱动Bean(MDB)
一、说明
本示例使用的ActiveMQ作为消息中间件,服务器为Glassfish,使用JMS发送消息,在MDB接收到消息之后做打印输出。
二、ActiveMQ安装配置1、安装console
war包安装到服务器不需要特殊配置,默认监听端口为61616,可通过修改activemq.xml修改默认端口,测试使用的console版本为activemq-web-console-5.5.1,当然console可以是与客户端不同的服务器,而且我们也一般都这样使用。
2、安装ActiveMq应用端
安装rar包,如果你下载的rar包中缺少slf4j-log4j12的jar包请手工加入,与安装普通的app一样,不需要特殊配置,我采用的为activemq-rar-5.5.0.rar,不同版本对服务器可能会存在兼容性问题。
3、配置服务器
依次配置如下内容:
public void sendMsg(String msg) throws NamingException {String cfJNDI = "jms/ConnectionFactory";// 配置的jndiString QUEUE_PHYSICAL_NAME = "jmsQueue";// 配置的PhysicalNameInitialContext ic = new InitialContext();//获取到连接池ConnectionFactory connectionFactory = (ConnectionFactory) ic.lookup(cfJNDI);Connection connection = null;MessageProducer producer = null;try {//通过连接创建会话connection = connectionFactory.createConnection();Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);//创建消息TextMessage message = session.createTextMessage();message.setText(msg);//创建消息队列Queue queue = session.createQueue(QUEUE_PHYSICAL_NAME);//发送消息producer = session.createProducer(queue);producer.send(message);} catch (JMSException e) {e.printStackTrace();return;} finally {// 关闭资源if (producer != null) {try {producer.close();} catch (JMSException e) {e.printStackTrace();return;}}if (connection != null) {try {connection.close();} catch (JMSException e) {e.printStackTrace();return;}}}}