java tomcat jms_JavaWeb之使用Tomcat、JNDI与ActiveMQ实现JMS消息通信服务

前言

之所以使用JNDI 是出于通用性考虑,该例子使用JMS规范提供的通用接口,没有使用具体JMS提供者的接口,这样可以保证我们编写的程序适用于任何一种JMS实现(ActiveMQ、HornetQ等)。

什么是JNDI:JNDI(Java Naming and Directory Interface)是一个标准规范,类似于JDBC,JMS等规范,为开发人员提供了查找和访问各种命名和目录服务的通用、统一的接口。J2EE 规范要求所有 J2EE 容器都要提供 JNDI 规范的实现,因此Tomcat就实现了JNDI 规范。

PTP(Point to point)消息模式(JMS的点对点消息传送)

1、使用Tomcat配置JNDI

找到Tomcat安装路径下的conf文件夹,打开context.xml,添加如下配置:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

View Code

2、启动ActiveMQ

bb6064f11044c3354c7a02f1ff789ada.png

3、编写一个Web工程

Eclipse上新建web工程,添加ActiveMQ依赖的jar包,然后开始编写两个Servlet,一个用于生产消息,另一个用于消费消息,如下代码:

消息生产者Servlet:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

import java.io.IOException;

import java.io.PrintWriter;

import javax.jms.DeliveryMode;

import javax.jms.Queue;

import javax.jms.QueueConnection;

import javax.jms.QueueConnectionFactory;

import javax.jms.QueueSender;

import javax.jms.QueueSession;

import javax.jms.Session;

import javax.jms.TextMessage;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;/**

* Servlet implementation class JMSTest*/@WebServlet("/Send")public classSend extends HttpServlet {private static final long serialVersionUID = 1L;/**

* @see HttpServlet#HttpServlet()*/

publicSend() {

super();//TODO Auto-generated constructor stub

}/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

PrintWriterout =response.getWriter();try{//get the initial context

InitialContext context = newInitialContext();//lookup the queue object

Queue queue = (Queue) context.lookup("java:comp/env/queue/queue0");//lookup the queue connection factory

QueueConnectionFactory conFactory =(QueueConnectionFactory) context

.lookup("java:comp/env/queue/connectionFactory");//create a queue connection

QueueConnection queConn =conFactory.createQueueConnection();//create a queue session

QueueSession queSession = queConn.createQueueSession(false,

Session.DUPS_OK_ACKNOWLEDGE);//create a queue sender

QueueSender queSender =queSession.createSender(queue);

queSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);//create a simple message to say "Hello World"

TextMessage message = queSession.createTextMessage("Hello World");//send the message

queSender.send(message);//print what we did

out.write("Message Sent:" +message.getText());//close the queue connection

queConn.close();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {//TODO Auto-generated method stub

}

}

View Code

消息消费者Servlet:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

import java.io.IOException;

import java.io.PrintWriter;

import javax.jms.Queue;

import javax.jms.QueueConnection;

import javax.jms.QueueConnectionFactory;

import javax.jms.QueueReceiver;

import javax.jms.QueueSession;

import javax.jms.Session;

import javax.jms.TextMessage;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;/**

* Servlet implementation class Receive*/@WebServlet("/Receive")public classReceive extends HttpServlet {private static final long serialVersionUID = 1L;/**

* @see HttpServlet#HttpServlet()*/

publicReceive() {

super();//TODO Auto-generated constructor stub

}/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

PrintWriterout =response.getWriter();try{//get the initial context

InitialContext context = newInitialContext();//lookup the queue object

Queue queue = (Queue) context.lookup("java:comp/env/queue/queue0");//lookup the queue connection factory

QueueConnectionFactory conFactory =(QueueConnectionFactory) context

.lookup("java:comp/env/queue/connectionFactory");//create a queue connection

QueueConnection queConn =conFactory.createQueueConnection();//create a queue session

QueueSession queSession = queConn.createQueueSession(false,

Session.AUTO_ACKNOWLEDGE);//create a queue receiver

QueueReceiver queReceiver =queSession.createReceiver(queue);//start the connection

queConn.start();//receive a message

TextMessage message =(TextMessage) queReceiver.receive();//print the message

out.write("Message Received:" +message.getText());//close the queue connection

queConn.close();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {//TODO Auto-generated method stub

}

}

View Code

4、验证结果

在Tomcat里运行该Web工程,执行消息生产者Servlet,返回消息发送成功标志,同时我们可以在http://localhost:8161/admin/queues.jsp查看到该消息,如下图所示

61859a798b71e69891bb7f0aa05c7093.png

5bea33200d2e7eebd73c6583dc58f4ba.png

继续执行消息消费者Servlet,返回消息接收成功标志,同时我们可以打开http://localhost:8161/admin/queues.jsp页面,发现刚才的消息已经不见了,如下图所示

3fe4efd286b27005e60c23884e426aa1.png

0c6ed79f7dc65cbc928e8bbc872d0476.png

Pub/Sub消息模式(JMS发布/订阅消息传送)

1、在Tomcat中配置JNDI

配置连接工厂和话题:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

View Code

2、启动ActiveMQ

bb6064f11044c3354c7a02f1ff789ada.png

3、在Web工厂中编写代码

新建一个发布者Servlet:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

package pubSub;

import java.io.IOException;

import java.io.PrintWriter;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.jms.Topic;

import javax.jms.Session;

import javax.jms.TextMessage;

import javax.jms.TopicPublisher;

import javax.jms.DeliveryMode;

import javax.jms.TopicSession;

import javax.jms.TopicConnection;

import javax.jms.TopicConnectionFactory;/**

* Servlet implementation class JMSTest*/@WebServlet("/Publish")public classPublisher extends HttpServlet {private static final long serialVersionUID = 1L;/**

* @see HttpServlet#HttpServlet()*/

publicPublisher() {

super();//TODO Auto-generated constructor stub

}/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

PrintWriterout =response.getWriter();try{//get the initial context

InitialContext ctx = newInitialContext();//lookup the topic object

Topic topic = (Topic) ctx.lookup("java:comp/env/topic/topic0");//lookup the topic connection factory

TopicConnectionFactory connFactory =(TopicConnectionFactory) ctx

.lookup("java:comp/env/topic/connectionFactory");//create a topic connection

TopicConnection topicConn =connFactory.createTopicConnection();//create a topic session

TopicSession topicSession = topicConn.createTopicSession(false,

Session.AUTO_ACKNOWLEDGE);//create a topic publisher

TopicPublisher topicPublisher =topicSession.createPublisher(topic);

topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);//create the "Hello World" message

TextMessage message =topicSession.createTextMessage();

message.setText("Hello World");//publish the messages

topicPublisher.publish(message);//print what we did

out.write("Message published:" +message.getText());//close the topic connection

topicConn.close();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {//TODO Auto-generated method stub

}

}

View Code

新建一个订阅者Servlet:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

package pubSub;

import java.io.IOException;

import java.io.PrintWriter;

import javax.jms.Session;

import javax.jms.TextMessage;

import javax.jms.Topic;

import javax.jms.TopicConnection;

import javax.jms.TopicConnectionFactory;

import javax.jms.TopicSession;

import javax.jms.TopicSubscriber;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;/**

* Servlet implementation class Receive*/@WebServlet("/Subscribe")public classSubscriber extends HttpServlet {private static final long serialVersionUID = 1L;/**

* @see HttpServlet#HttpServlet()*/

publicSubscriber() {

super();//TODO Auto-generated constructor stub

}/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

PrintWriterout =response.getWriter();try{//get the initial context

InitialContext ctx = newInitialContext();//lookup the topic object

Topic topic = (Topic) ctx.lookup("java:comp/env/topic/topic0");//lookup the topic connection factory

TopicConnectionFactory connFactory =(TopicConnectionFactory) ctx

.lookup("java:comp/env/topic/connectionFactory");//create a topic connection

TopicConnection topicConn =connFactory.createTopicConnection();//create a topic session

TopicSession topicSession = topicConn.createTopicSession(false,

Session.AUTO_ACKNOWLEDGE);//create a topic subscriber

TopicSubscriber topicSubscriber =topicSession

.createSubscriber(topic);//start the connection

topicConn.start();//receive the message

TextMessage message =(TextMessage) topicSubscriber.receive();//print the message

out.write("Message received:" +message.getText());//close the topic connection

topicConn.close();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

* response)*/

protected voiddoPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {//TODO Auto-generated method stub

}

}

View Code

4、验证结果

运行Web工程,分别打开多个标签访问订阅servlet,然后访问发布servlet,结果如下:

ea9fac9ba5719fa6d87e0335453e1f67.png

2885c6823bbf90346657611f6e3b9da6.png

22d7e0f9897efc474dd79f2d7a40a818.png

在订阅者订阅消息的时候,一开始没接收到消息,一旦发布者发布消息后,订阅者马上收到消息。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/411050.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

你是第几名:Excel 中 Large 和 Small 的用法

类似于 SQL 语言中的 TOP X, Large 和Small 有2个参数 Large(Array,k) Array 可以为一个单元格区域,k 为第k各最大值,Small 与之对应返回第k个最小值。 注意:单元格区域中的非数字会被忽略掉。 例子如下: 可以类比Rank的用法&…

mac系统下android studio创建手机模拟器

打开android studio,点击右上角的模拟器图标,打开“Android Virtual Device Manager” 窗口,如下图 点击“Create Virtual Device”,在打开的设备定义列表中,选择“Phone -> Nexus 5X”,右边列出了改机型…

如何设置Hyper-V的虚拟机快捷方式

在Windows Server 2008中,提供的Hyper-V功能,可以很方便地在企业环境中部署多个虚拟机,以适应不同的开发需要。一般我们都是通过下面的方式 1. 打开服务器管理器 2.打开Hyper-V管理器,找到有关的虚拟机,然后右键点击“…

java跨函数跳转_VS code 函数无法跨文件跳转到定义

现状:本文件函数通过this打点调用的函数,引入绝对路径的文件,调用的函数都可以通过Ctrl 点击 实现跳转到定义处。而如果在 webpack 通过alias 设置了别名,无法跳转成功。解决方案: 新建文件 jsconfig.json,配置如下。…

python enumerate()

描述 enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。 语法 以下是 enumerate() 方法的语法: enumerate(sequence, [start0]) 参数 sequence -- 一个序列、迭代器…

java 怎么页面授权访问_Java调用Linkedin接口API之:获取授权

配置领英应用配置地址:https://www.linkedin.com/secure/developer?newapp强烈建议您使用 HTTPS网址必须是绝对网址 (例如: “https://example.com/auth/callbac”,而不是“/auth/callback”)网址参数会被忽略 (即 https://example.com/?id1 与 https:…

win7 'IIS APPPOOL\Classic .NET AppPool' 登录失败

进入iis管理器 本地应用程序池 选中classic. net appPool 选择右侧的 高级设置 进程模型 标识 将内置账户改为LOCAL SYSTEM 转载于:https://www.cnblogs.com/3rocks/archive/2010/06/02/1750091.html

MariaDB数据库5-password、galera

转载于:https://www.cnblogs.com/WIU1905/p/11100917.html

创建使用 Active Directory 模式隔离用户的新 FTP 站点

“使用 Active Directory 隔离用户”模式根据相应的 Active Directory 容器验证用户凭据,而不是搜索整个 Active Directory,因为这样做需要大量的处理时间。 备 注 此模式需要在 Windows Server 2003 家族的操作系统上运行 Active Directory 服务器。也…

小米推送之服务端简单开发

1.获取SDK,并写入常量表 2.引入MiPush_SDK_Sever.jar文件和json-simple-1.1.1.jar 3.开发服务端代码(这里是用别名进行推送) /*小米推送*//** * 指定alias推送(单个或多个) * * param messagePayload 消息 * param title 消息标题 *…

java源码导入eclipse_spring framework源码下载并导入eclipse

一. 准备工作1.下载安装sts(springsource推荐使用), 毕竟人家的框架用他自家的ide是最好的,当然sts也是基本eclipse的, 下载地址: http://www.springsource.org/downloads/sts-ggts2.下载安装gradle, spring 源码构建加入了gradle支持. gradle下载: http://www.gradle.org/down…