博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于Tomcat + JNDI + ActiveMQ实现JMS的点对点消息传送
阅读量:6549 次
发布时间:2019-06-24

本文共 6132 字,大约阅读时间需要 20 分钟。

前言

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

什么是JNDI

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

使用Tomcat配置JNDI

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

启动ActiveMQ

  CMD到ActiveMQ安装路径下的bin目录,输入“activemq start”指令即可启动,可在浏览器中输入地址,查看队列、话题等信息。

编写一个Web工程

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

消息生产者Servlet:

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 class Send extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public Send() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        PrintWriter out = response.getWriter();        try {            // get the initial context            InitialContext context = new InitialContext();            // 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 void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }}

消息消费者Servlet:

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 class Receive extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public Receive() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        PrintWriter out = response.getWriter();        try {            // get the initial context            InitialContext context = new InitialContext();            // 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 void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub    }}

验证结果

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

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

参考资料

转载地址:http://qeuco.baihongyu.com/

你可能感兴趣的文章
主键自增归0
查看>>
mysql之 [ERROR] InnoDB: Unable to lock ./ibdata1, error: 11
查看>>
如何批量修改文件后缀的方法
查看>>
Effective STL 笔记
查看>>
[LeetCode] 1. Two Sum
查看>>
POJ2538 ZOJ1884 UVA10082 WERTYU【输入输出】
查看>>
HDU5620 KK's Steel(C++语言版)
查看>>
旋转卡壳
查看>>
2016/10/09
查看>>
自定义HorizontalScrollView的scrollBar
查看>>
c++学习笔记和思考
查看>>
27.Docker集群部署
查看>>
DNS保存
查看>>
IOS 多线程02-pthread 、 NSThread 、GCD 、NSOperationQueue、NSRunLoop
查看>>
第一周冲刺第五天博客
查看>>
[LeetCode]Longest Increasing Path in a Matrix
查看>>
集合set-深入学习
查看>>
C#语言学习——面向对象的几大原则
查看>>
zk 常用资料整理(转)
查看>>
JavaScript 字符串操作
查看>>