Apache TomEE + JMS。 这从未如此简单。

我记得J2EE (1.3和1.4)的过去,使用JMS启动项目非常困难。 您需要安装JMS 代理 ,创建主题队列 ,最后使用服务器配置文件和JNDI开始自己的战斗。

感谢JavaEE 6及其它,使用JMS确实非常简单。 但是使用Apache TomEE则更容易上手。 在本文中,我们将了解如何创建和测试一个简单的应用程序,该应用程序使用Apache TomEEJMS队列发送消息或从JMS队列接收消息。

Apache TomEE使用Apache Active MQ作为JMS提供程序。 在此示例中,您不需要下载或安装任何东西,因为所有元素都将作为Maven依赖项提供,但是如果您计划(并且应该)使用Apache TomEE服务器,则需要下载Apache TomEE plus或Apache TomEE plume。 您可以在http://tomee.apache.org/comparison.html中了解有关Apache TomEE风味的更多信息。

依存关系

首先要做的是将javaee-api添加为提供的依赖项,并将junitopenejb-core添加测试依赖项。 请注意,添加了openejb-core依赖项以使其具有运行时来执行测试,我们将在测试部分中对其进行深入了解。

<dependencies><dependency><groupId>org.apache.openejb</groupId><artifactId>javaee-api</artifactId><version>6.0-6</version><scope>provided</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><dependency><groupId>org.apache.openejb</groupId><artifactId>openejb-core</artifactId><version>4.7.1</version><scope>test</scope></dependency>
</dependencies>

商业代码

下一步是创建负责发送消息和从JMS 队列接收消息的业务代码。 它还包含一种从队列接收消息的方法。 对于此示例,我们将使用无状态 EJB

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;@Stateless
public class Messages {//Standard @Resource annotation is used to inject the ConnectionFactory. //If no name is provided using lookup or name attribute, //the fully qualified name of the class with an slash (/) and the name of the attribute is used. //In this example: java:comp/env/org.superbiz.jms.Messages/connectionFactory.@Resource private ConnectionFactory connectionFactory;//Standard @Resource annotation is used to inject the Queue. //If no name is provided using lookup or name attribute, //the fully qualified name of the class with an slash (/) and the name of the attribute is used. //In this example: java:comp/env/org.superbiz.injection.jms.Messages/chatQueue.@Resource private Queue chatQueue;public void sendMessage(String text) throws JMSException {Connection connection = null;Session session = null;try {connection = connectionFactory.createConnection();//Connection is get from ConnectionFactory instance and it is started.connection.start(); //Creates a session to created connection.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); //Creates a MessageProducer from Session to the Queue.MessageProducer producer = session.createProducer(chatQueue);producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage(text);//Tells the producer to send the messageproducer.send(message); } finally {if (session != null) session.close(); if (connection != null) connection.close();}}public String receiveMessage() throws JMSException {Connection connection = null;Session session = null;MessageConsumer consumer = null;try {connection = connectionFactory.createConnection();connection.start();session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);consumer = session.createConsumer(chatQueue); //Waits for a message with timeout. Note that because a TextMessage is sent, the receive method expects a TextMessage too.TextMessage message = (TextMessage) consumer.receive(1000); return message.getText(); } finally {if (consumer != null) consumer.close();if (session != null) session.close();if (connection != null) connection.close();}}
}

Messages类的最重要部分是注意注入ConnectionFactory
在代码内将实例排队 。 您只需要使用@Resource批注,容器将为您完成其余工作。 最后请注意,由于我们尚未使用namelookup属性来设置名称,因此将字段名称用作资源名称。

测试

最后,我们可以编写一个测试来断言使用JMS队列发送和接收消息。 例如,我们可以使用Arquilian编写测试,但是由于这种情况,由于简单起见,我们将使用嵌入式OpenEJB实例来部署JMS示例并运行测试。

public class MessagesTest {//Messages EJB is injected.@EJBprivate Messages messages;@Beforepublic void setUp() throws Exception {Properties p = new Properties();//Embedded OpenEJB container is started.//And current test added inside created container//So we can use javaee annotations insideEJBContainer.createEJBContainer(p).getContext().bind("inject", this); }@Testpublic void shouldSendAndReceiveMessages() throws Exception {//Three messages are sent.messages.sendMessage("Hello World!"); messages.sendMessage("How are you?");messages.sendMessage("Still spinning?");//Three messages are received.assertThat(messages.receiveMessage(), is("Hello World!")); assertThat(messages.receiveMessage(), is("How are you?"));assertThat(messages.receiveMessage(), is("Still spinning?"));}}

请注意,该测试非常简单明了,您只需要以编程方式启动EJB容器并在其中绑定当前测试,这样我们就可以在测试中使用JavaEE批注。 其余的是一个简单的JUnit测试。

而且,如果您运行测试,您将收到绿色的子弹。 但是,等等,您可能想知道JMS 代理及其配置在哪里? ConnectionFactoryJMS 队列的定义在哪里? 这就是OpenEJB (和Apache TomEE )发挥作用的地方。

在这种情况下, OpenEJB (和Apache TomEE )将以嵌入式模式使用Apache Active MQ ,因此您无需在计算机上安装Apache Active MQ即可运行测试。 此外, Apache TomEE将为您创建所有必需的资源。 例如,它会创建一个连接工厂和一个队列为你使用默认参数和预期的名称(org.superbiz.Messages / connectionFactory的用于连接工厂org.superbiz.Messages / chatQueue队列 ),所以你不必担心到在测试阶段配置JMSApache TomEE足够聪明,可以为您创建和配置它们。

您可以通过阅读下一条日志消息来检查控制台输出,以了解资源是自动创建的: INFO:自动创建资源

Jan 10, 2015 10:32:48 AM org.apache.openejb.config.AutoConfig processResourceRef
INFO: Auto-linking resource-ref 'java:comp/env/org.superbiz.Messages/connectionFactory' in bean Messages to Resource(id=Default JMS Connection Factory)
Jan 10, 2015 10:32:48 AM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=org.superbiz.Messages/chatQueue, type=Resource, provider-id=Default Queue)
Jan 10, 2015 10:32:48 AM org.apache.openejb.config.AutoConfig logAutoCreateResource
INFO: Auto-creating a Resource with id 'org.superbiz.Messages/chatQueue' of type 'javax.jms.Queue for 'Messages'.
Jan 10, 2015 10:32:48 AM org.apache.openejb.assembler.classic.Assembler createRecipe
INFO: Creating Resource(id=org.superbiz.Messages/chatQueue)
Jan 10, 2015 10:32:48 AM org.apache.openejb.config.AutoConfig processResourceEnvRef
INFO: Auto-linking resource-env-ref 'java:comp/env/org.superbiz.Messages/chatQueue' in bean Messages to Resource(id=org.superbiz.Messages/chatQueue)
Jan 10, 2015 10:32:48 AM org.apache.openejb.config.ConfigurationFactory configureService
INFO: Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container)
Jan 10, 2015 10:32:48 AM org.apache.openejb.config.AutoConfig createContainer
INFO: Auto-creating a container for bean javaee.MessagesTest: Container(type=MANAGED, id=Default Managed Container)

如此,借助Java EETomEEJMS真的非常容易上手 。 在下一篇文章中,我们将看到如何使用消息驱动Bean (MDB)进行相同的操作。

翻译自: https://www.javacodegeeks.com/2015/01/apache-tomee-jms-it-has-never-been-so-easy.html

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

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

相关文章

Struts2显示double价格格式0.00

在国际化资源文件中加入&#xff1a; format.money{0,number,0.00} jsp页面用struts标签&#xff1a; <s:text name"format.money">   <s:param name"value" value"priceName" /> </s:text> 输出格式&#xff1a;0.00转载于…

数组方法大全ES5+ES6

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录1. 使用 Array 构造函数2. 使用数组字面量表示法数组原型方法1. join()2.push()和pop()3.shift() 和 unshift()4.sort()5.reverse()6.concat()7.slice()8.splice()9.…

【Linux系统基础】(2)在Linux上部署MySQL、RabbitMQ、ElasticSearch、Zookeeper、Kafka、NoSQL等各类软件

实战章节&#xff1a;在Linux上部署各类软件 前言 为什么学习各类软件在Linux上的部署 在前面&#xff0c;我们学习了许多的Linux命令和高级技巧&#xff0c;这些知识点比较零散&#xff0c;同学们跟随着课程的内容进行练习虽然可以基础掌握这些命令和技巧的使用&#xff0c;…

使用Java 8流进行快速失败的验证

我已经失去了使用类似方法通过失败快速验证代码状态的次数&#xff1a; public class PersonValidator {public boolean validate(Person person) {boolean valid person ! null;if (valid) valid person.givenName ! null;if (valid) valid person.familyName ! null;if (…

找到数组最大值

const maxHight Math.max.apply(null, rowData && rowData.urlImage.map(ele > ele.long) || []);

JDK 7和JDK 8中大行读取速度较慢的原因

我之前发布了博客文章“使用JDK 7和JDK 8读取慢速行”&#xff0c;并且在该问题上有一些有用的评论来描述该问题。 这篇文章提供了更多解释&#xff0c;说明为何该文章中演示的文件读取&#xff08;并由Ant的LineContainsRegExp使用 &#xff09;在Java 7和Java 8中比在Java 6中…

Spring Stateless State Security第3部分:JWT +社会认证

我的Stateless Spring Security系列文章的第三部分也是最后一部分是关于将基于JWT令牌的身份验证与spring-social-security混合在一起的。 这篇文章直接建立在此基础上&#xff0c;并且主要集中在已更改的部分上。 想法是使用基于OAuth 2的“使用Facebook登录”功能来替换基于用…

css React 单行省略和多行省略

单行省略 white-space: nowrap; text-overflow: ellipsis; overflow: hidden; word-break: break-all;多行省略 overflow : hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;我们需要在需要超出加省略号的标签…

nyoj239 月老的难题 二分图 匈牙利算法

月老的难题 时间限制&#xff1a;1000 ms | 内存限制&#xff1a;65535 KB难度&#xff1a;4描述月老准备给n个女孩与n个男孩牵红线&#xff0c;成就一对对美好的姻缘。 现在&#xff0c;由于一些原因&#xff0c;部分男孩与女孩可能结成幸福的一家&#xff0c;部分可能不会结…

使用系统规则测试System.in和System.out

编写单元测试是软件开发的组成部分。 当您的被测类与操作系统交互时&#xff0c;您必须解决的一个问题是模拟其行为。 这可以通过使用模拟代替Java Runtime Environment&#xff08;JRE&#xff09;提供的实际对象来完成。 支持Java的模拟的库是例如嘲笑或jMock 。 当您完全控…

循环对象

params为对象&#xff0c;key为对象的k值 Object.keys(params).forEach(key > {formData.append(key, params[key]); });

[转]C#操作XML方法详解

本文转自&#xff1a;http://www.cnblogs.com/minotmin/archive/2012/10/14/2723482.html using System.Xml;//初始化一个xml实例XmlDocument xmlnew XmlDocument(); //导入指定xml文件xml.Load(path);xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml…

Web应用程序体系结构– Spring MVC – AngularJs堆栈

Spring MVC和AngularJs共同为构建表单密集型Web应用程序提供了一个真正高效且吸引人的前端开发堆栈。在这篇博客文章中&#xff0c;我们将看到如何使用这些技术构建表单密集型Web应用程序&#xff0c;并将这种方法与其他方法进行比较可用选项。 可以在此github 存储库中找到功能…

HTML5基础一:常用布局标签

1、DTD声明&#xff1a; <!doctype html> 2、布局标签 <html> <head></head> <body> //头部标签 <header> <nav>导航栏标签</nav> </header>  <div> //自定义主区间 <section> <ruby>夼<rp>(&…

Antd Table树形展示,分页后有时候数据渲染不出的问题

项目场景&#xff1a; Antd V4版 网页端 问题描述&#xff1a; 使用Table树形使用Card onTabChange 切换tab&#xff0c;有时候数据渲染不出的问题 const paginationProps {Current: currentNumber,size: small,pageSize,total,onChange: (PageNumber) > this.getList(Pa…

Java 8函数式编程:延迟实例化

单例通常会延迟实例化自己&#xff0c;有时&#xff0c;如果对象足够重&#xff0c;则可以延迟实例化类字段。 通常&#xff0c;在走惰性路线时&#xff0c;getter方法&#xff08;或accessor &#xff09;必须具有一段代码&#xff0c;该代码块在返回对象之前检查对象是否已实…

ant-design官网打不开 , 需要用镜像地址打开

如果网络不好的时候ant-design 的官网很难打开的 &#xff0c;用下面的镜像地址就可以打开啦 ant-design 官网镜像地址: http://ant-design.gitee.io/index-cn ant-design-pro镜像地址&#xff1a; http://ant-design-pro.gitee.io/index-cn antd-mobile镜像地址&#xff1a; …

全排列函数、组合函数

1 1、求一个全排列函数&#xff1a;如p([1,2,3])输出&#xff1a; [123],[132],[213],[231],[321],[312]. 2、求一个组合函数如p([1,2,3])输出&#xff1a; [1],[2],[3],[1,2],[2,3],[1,3],[1,2,3] 这两问可以用伪代码。 void swap(int *a, int *b) //交换函数 {int tmp;tmp *a…

Java中的XSL转换:一种简单的方法

XSL转换 &#xff08;XSLT&#xff09;是将一个XML文档转换为另一个XML文档的强大机制。 但是&#xff0c;在Java中&#xff0c;XML操作相当冗长和复杂。 即使是简单的XSL转换&#xff0c;也必须编写几十行代码—如果需要适当的异常处理和日志记录&#xff0c;甚至可能还要写更…

修改html页面的title,可以自定义

方式一&#xff1a; document.getElementsByTagName(“title”)[0].innerText ‘需要设置的值’; document.title方式 经过测试&#xff0c;还可通过document.title 设置title的值。方式二 console.log(document.title); # 可以获取title的值。 document.title ‘需要设置的值…