jms activemq_带有ActiveMQ的JMS

jms activemq

带有ActiveMQ的JMS

JMS是Java消息服务的缩写,它提供了一种以松散耦合,灵活的方式集成应用程序的机制。 JMS以存储和转发的方式跨应用程序异步传递数据。 应用程序通过充当中介的MOM(面向消息的中间件)进行通信,而无需直接通信。

JMS体系结构

JMS的主要组件是:

  • JMS Provider:一种消息传递系统,它实现JMS接口并提供管理和控制功能
  • 客户端:发送或接收JMS消息的Java应用程序。 消息发送者称为生产者,而接收者称为消费者
  • 消息:在JMS客户端之间传递信息的对象
  • 受管对象:管理员为使用客户端而创建的预配置JMS对象。

有几种可用的JMS提供程序,例如Apache ActiveMQ和OpenMQ。 在这里,我使用了Apache ActiveMQ。

在Windows上安装和启动Apache ActiveMQ

  1. 下载ActiveMQ Windows二进制分发版
  2. 将其提取到所需位置
  3. 使用命令提示符将目录更改为ActiveMQ安装文件夹中的bin文件夹,然后运行以下命令以启动ActiveMQ
  4. activemq

启动ActiveMQ之后,您可以使用http:// localhost:8161 / admin /访问管理控制台并执行管理任务

JMS消息传递模型

JMS有两种消息传递模型,即点对点消息传递模型和发布者订户消息传递模型。

点对点消息传递模型

生产者将消息发送到JMS提供程序中的指定队列,并且只有一个监听该队列的使用者才能接收该消息。

示例1和示例2几乎相似,唯一的区别是示例1在程序内创建队列,示例2使用jndi.properties文件命名查找和创建队列。

例子1

package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Producer {public Producer() throws JMSException, NamingException {// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryConnectionFactory conFactory = (ConnectionFactory) jndi.lookup('connectionFactory');Connection connection;// Getting JMS connection from the server and starting itconnection = conFactory.createConnection();try {connection.start();// JMS messages are sent and received using a Session. We will// create here a non-transactional session object. If you want// to use transactions you should set the first parameter to 'true'Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);Destination destination = (Destination) jndi.lookup('MyQueue');// MessageProducer is used for sending messages (as opposed// to MessageConsumer which is used for receiving them)MessageProducer producer = session.createProducer(destination);// We will send a small text message saying 'Hello World!'TextMessage message = session.createTextMessage('Hello World!');// Here we are sending the message!producer.send(message);System.out.println('Sent message '' + message.getText() + ''');} finally {connection.close();}}public static void main(String[] args) throws JMSException {try {BasicConfigurator.configure();new Producer();} catch (NamingException e) {e.printStackTrace();}}
}
package com.eviac.blog.jms;import javax.jms.*;import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.BasicConfigurator;public class Consumer {// URL of the JMS serverprivate static String url = ActiveMQConnection.DEFAULT_BROKER_URL;// Name of the queue we will receive messages fromprivate static String subject = 'MYQUEUE';public static void main(String[] args) throws JMSException {BasicConfigurator.configure();// Getting JMS connection from the serverConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);Connection connection = connectionFactory.createConnection();connection.start();// Creating session for seding messagesSession session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);// Getting the queueDestination destination = session.createQueue(subject);// MessageConsumer is used for receiving (consuming) messagesMessageConsumer consumer = session.createConsumer(destination);// Here we receive the message.// By default this call is blocking, which means it will wait// for a message to arrive on the queue.Message message = consumer.receive();// There are many types of Message and TextMessage// is just one of them. Producer sent us a TextMessage// so we must cast to it to get access to its .getText()// method.if (message instanceof TextMessage) {TextMessage textMessage = (TextMessage) message;System.out.println('Received message '' + textMessage.getText()+ ''');}connection.close();}
}

jndi.properties

# START SNIPPET: jndijava.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory# use the following property to configure the default connector
java.naming.provider.url = vm://localhost# use the following property to specify the JNDI name the connection factory
# should appear as. 
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic# END SNIPPET: jndi
package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Producer {public Producer() throws JMSException, NamingException {// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryConnectionFactory conFactory = (ConnectionFactory) jndi.lookup('connectionFactory');Connection connection;// Getting JMS connection from the server and starting itconnection = conFactory.createConnection();try {connection.start();// JMS messages are sent and received using a Session. We will// create here a non-transactional session object. If you want// to use transactions you should set the first parameter to 'true'Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);Destination destination = (Destination) jndi.lookup('MyQueue');// MessageProducer is used for sending messages (as opposed// to MessageConsumer which is used for receiving them)MessageProducer producer = session.createProducer(destination);// We will send a small text message saying 'Hello World!'TextMessage message = session.createTextMessage('Hello World!');// Here we are sending the message!producer.send(message);System.out.println('Sent message '' + message.getText() + ''');} finally {connection.close();}}public static void main(String[] args) throws JMSException {try {BasicConfigurator.configure();new Producer();} catch (NamingException e) {e.printStackTrace();}}
}
package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Consumer {public Consumer() throws NamingException, JMSException {Connection connection;// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryConnectionFactory conFactory = (ConnectionFactory) jndi.lookup('connectionFactory');// Getting JMS connection from the server and starting it// ConnectionFactory connectionFactory = new// ActiveMQConnectionFactory(url);connection = conFactory.createConnection();// // Getting JMS connection from the server// ConnectionFactory connectionFactory = new// ActiveMQConnectionFactory(url);// Connection connection = connectionFactory.createConnection();try {connection.start();// Creating session for seding messagesSession session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);// Getting the queueDestination destination = (Destination) jndi.lookup('MyQueue');// MessageConsumer is used for receiving (consuming) messagesMessageConsumer consumer = session.createConsumer(destination);// Here we receive the message.// By default this call is blocking, which means it will wait// for a message to arrive on the queue.Message message = consumer.receive();// There are many types of Message and TextMessage// is just one of them. Producer sent us a TextMessage// so we must cast to it to get access to its .getText()// method.if (message instanceof TextMessage) {TextMessage textMessage = (TextMessage) message;System.out.println('Received message '' + textMessage.getText()+ ''');}} finally {connection.close();}}public static void main(String[] args) throws JMSException {BasicConfigurator.configure();try {new Consumer();} catch (NamingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

发布者订阅者模型

发布者将消息发布到JMS提供程序中的指定主题,并且订阅该主题的所有订阅者都将收到该消息。 请注意,只有活动的订户才能收到该消息。

点对点模型示例

package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.*;import org.apache.log4j.BasicConfigurator;import java.io.BufferedReader;
import java.io.InputStreamReader;public class DemoPublisherSubscriberModel implements javax.jms.MessageListener {private TopicSession pubSession;private TopicPublisher publisher;private TopicConnection connection;/* Establish JMS publisher and subscriber */public DemoPublisherSubscriberModel(String topicName, String username,String password) throws Exception {// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryTopicConnectionFactory conFactory = (TopicConnectionFactory) jndi.lookup('topicConnectionFactry');// Create a JMS connectionconnection = conFactory.createTopicConnection(username, password);// Create JMS session objects for publisher and subscriberpubSession = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);TopicSession subSession = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);// Look up a JMS topicTopic chatTopic = (Topic) jndi.lookup(topicName);// Create a JMS publisher and subscriberpublisher = pubSession.createPublisher(chatTopic);TopicSubscriber subscriber = subSession.createSubscriber(chatTopic);// Set a JMS message listenersubscriber.setMessageListener(this);// Start the JMS connection; allows messages to be deliveredconnection.start();// Create and send message using topic publisherTextMessage message = pubSession.createTextMessage();message.setText(username + ': Howdy Friends!');publisher.publish(message);}/** A client can register a message listener with a consumer. A message* listener is similar to an event listener. Whenever a message arrives at* the destination, the JMS provider delivers the message by calling the* listener's onMessage method, which acts on the contents of the message.*/public void onMessage(Message message) {try {TextMessage textMessage = (TextMessage) message;String text = textMessage.getText();System.out.println(text);} catch (JMSException jmse) {jmse.printStackTrace();}}public static void main(String[] args) {BasicConfigurator.configure();try {if (args.length != 3)System.out.println('Please Provide the topic name,username,password!');DemoPublisherSubscriberModel demo = new DemoPublisherSubscriberModel(args[0], args[1], args[2]);BufferedReader commandLine = new java.io.BufferedReader(new InputStreamReader(System.in));// closes the connection and exit the system when 'exit' enters in// the command linewhile (true) {String s = commandLine.readLine();if (s.equalsIgnoreCase('exit')) {demo.connection.close();System.exit(0);}}} catch (Exception e) {e.printStackTrace();}}
}

参考: 和ActiveMQ JMS从我们JCG伙伴 Pavithra Siriwardena在EVIAC博客。


翻译自: https://www.javacodegeeks.com/2012/07/jms-with-activemq.html

jms activemq

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

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

相关文章

【EMV L2】SDA静态数据认证处理流程

【静态数据认证】 静态数据认证处理过程中,卡片没有执行任何处理,终端执行的处理流程:1、认证中心公钥的获取终端使用卡片上的认证中心公钥索引(PKI)【TAG:8F,Certification Authority Public K…

java取邮箱前缀_java抓取网页或文件中的邮箱号码

java抓取网页或文件中的邮箱号码发布时间:2020-10-18 08:58:32来源:脚本之家阅读:69作者:java大渣渣本文实例为大家分享了java抓取邮箱号码的具体代码,供大家参考,具体内容如下java抓取文件中邮箱号码的具体…

为Twitter4j创建自定义SpringBoot Starter

SpringBoot提供了许多启动器模块来快速启动和运行。 SpringBoot的自动配置机制负责根据各种标准代表我们配置SpringBean。 除了Core Spring Team提供的现成的springboot启动器之外,我们还可以创建自己的启动器模块。 在本文中,我们将研究如何创建自定义…

mac php gd库,mac下安装GD库FreeType

MacBook Pro安装的新系统10.10.3,PHP环境也是默认就有的,GD库在默认情况下也安装过了,但在使用验证码的时候,提示GD库不支持FreeType,这里我们手动安装一下。法一:安装 FreeType前往苹果官方开源支持&#…

php异步查询数据库,php中mysql数据库异步查询实现

问题通常一个web应用的性能瓶颈在数据库。因为,通常情况下php中mysql查询是串行的。也就是说,如果指定两条sql语句时,第二条sql语句会等到第一条sql语句执行完毕再去执行。这个时候,如果执行2条sql语句,每条执行时间为…

java btrace_BTrace:Java开发人员工具箱中的隐藏宝石

java btrace这篇文章是关于BTrace的 ,我正在考虑将其作为Java开发人员的隐藏宝藏。 BTrace是用于Java平台的安全,动态跟踪工具。 BTrace可用于动态跟踪正在运行的Java程序(类似于DTrace,适用于OpenSolaris应用程序和OS&#xff09…

共享文件夹不能访问的问题解决

打开控制面板--管理工具--服务--webclinet,设为自动,启动。重启电脑,搞定!转载于:https://www.cnblogs.com/atlj/p/8481257.html

xampp浏览php出现乱码,dvwa+xampp搭建显示乱码的问题及解决方案

如图,dvwa显示乱码,解决办法有两个:1、方法一是,临时解决办法,也就是每次都得手动修改:利用浏览器的编码修改2、方法二是:永久方案,那就是修改dvwa的配置文件,修改默认编…

HotSpot的-XshowSettings标志的简单性和价值

一个方便的HotSpot JVM标志 ( 选项为Java启动 java )是-XshowSettings选项。 Oracle Java启动器描述页面中对此选项进行了如下描述 : -XshowSettings : category显示设置并继续。 该选项的可能类别参数包括: all显示所…

Python验证码简单实现(数字和大写字母组成的4位验证码)

#数字和英文大写字母的4位随机数 def checkcode(): #def 定义方法 checkcode() 方法名()import random # 导入包checkcode ""string range(0,4)for i in string:current random.randrange(0,3) #randrange随机数 参数1<随机数<参数2if current ! i:temp …

php haystack,haystack(示例代码)

1、haystack简介Haystack是django的开源全文搜索框架(全文检索不同于特定字段的模糊查询&#xff0c;使用全文检索的效率更高 )&#xff0c;该框架支持Solr,Elasticsearch,Whoosh, Xapian&#xff0c;搜索引擎它是一个可插拔的后端(很像Django的数据库层)&#xff0c;所以几乎你…

猫眼电影面试经历

面试是昨天上午进行的&#xff0c;因为昨天家里断网了&#xff0c;所以未能及时记录。 昨天的面试进行到了第三面&#xff0c;由于第三面的面试官当天未上班&#xff0c;所以成了回家等通知了。 感觉总体面试过程回答了百分之七十的样子吧&#xff01;一面、二面面试官都不错&a…

fopen php 乱码,如何解决php fgets读取文件乱码的问题

如何解决php fgets读取文件乱码的问题,文件,乱码,简体中文,记事本,页面如何解决php fgets读取文件乱码的问题易采站长站&#xff0c;站长之家为您整理了如何解决php fgets读取文件乱码的问题的相关内容。php fgets乱码的解决办法&#xff1a;首先依次点击“菜单修改->页面属…

一致性哈希算法原理分析及实现

一致性哈希算法常用于负载均衡中要求资源被均匀的分布到所有节点上&#xff0c;并且对资源的请求能快速路由到对应的节点上。具体的举两个场景的例子&#xff1a; 1、MemCache集群&#xff0c;要求存储各种数据均匀的存到集群中的各个节点上&#xff0c;访问这些数据时能快速的…

jsf集成spring_JSF – PrimeFaces和Hibernate集成项目

jsf集成spring本文介绍了如何使用JSF&#xff0c;PrimeFaces和Hibernate开发项目。 下面是一个示例应用程序&#xff1a; 二手技术&#xff1a; JDK 1.6.0_21 Maven的3.0.2 JSF 2.0.3 PrimeFaces 2.2.1 Hibernate3.6.7 MySQL Java连接器5.1.17 MySQL 5.5.8 Apache Tomcat 7.…

帝国 loginjs.php,帝国cms 6.6 后台拿shell

时间:2013-02-27来源:源码库 作者:源码库 文章热度:℃漏洞作者&#xff1a; 付弘雪提交时间&#xff1a; 2013-01-21公开时间&#xff1a; 2013-01-21漏洞类型&#xff1a; 文件上传导致任意代码执行简要描述&#xff1a;帝国cms 6.6版本后台拿shell 比网上流行的方法简单很多由…

合并两个排序的链表递归和非递归C++实现

题目描述&#xff1a; 输入两个单调递增的链表&#xff0c;输出两个链表合成后的链表&#xff0c;要求合成后的链表满足单调不减规则。 1、分析 已知输入的两个链表递增有序&#xff0c;要使输出的链表依然递增有序&#xff0c;可以依次从输入的两个链表中挑选最小的元素插入到…

带有JSF,Servlet和CDI的DynamicReports和JasperReports

在此示例中&#xff0c;我将展示如何将DynamicReport和JasperReports与Servlet和CDI集成。 工具&#xff1a; TIBCO Jaspersoft Studio-6.0.4。最终版 Eclipse Luna服务版本2&#xff08;4.4.2&#xff09;。 WildFly 8.x应用程序服务器。 这是Eclipse上项目层次结构的屏幕…

《Android进阶之光》--View体系与自定义View

No1&#xff1a; View的滑动 1&#xff09;layout()方法的 public class CustomView extends View{private int lastX;private int lastY;public CustomView(Context context,AttributeSet attrs,int defStyleAttr){super(context,attrs,defStyleAttr);}public CustomView(Cont…

js 数组 ajax php,js里面的对象ajax post到php端直接变成数组了?

本帖最后由 zhoumengkang 于 2013-09-12 10:03:14 编辑 事先引入了jqueryvar str "{a:b,aa:bb}";var str2 eval((str));var type typeof(str2);console.log(str);console.log(type);//objectconsole.log(str2);$.post(./bb.php,{data:str2});bb.php的代码$data $_…