带有ActiveMQ的JMS

带有ActiveMQ的JMS

JMS是Java Message Service的缩写,它提供了一种以松散耦合,灵活的方式集成应用程序的机制。 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

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

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

相关文章

矩阵分解 java_使用矩阵分解为推荐系统

矩阵分解假设“潜在因素”,例如对用户的意大利食物的偏好和项目食物的意外性与矩阵中的评级有关 .因此,整个问题类型转变为矩阵重构问题,存在许多不同的解决方案 . 一个简单的,可能很慢的解决方案是(除了ALS和其他一些矩阵重建的可…

用户故事排球教练助手

计划:估计这个任务需要一周时间 需求分析:作为一名排球教练助手,我需要了解每场每位队员的技术动作,每场比赛每位队员的得分情况,以便教练更好的了解到每位队员的发挥情况和特长。 设计文档:用户进入此界面…

TMS320DM642学习----第一篇(硬件连接)

DSP设备型号:SEED-DTK-VPM642(目前实验室用途:视频处理,图像处理方向,预计搭载目标跟踪以及云台防抖等算法) 官网链接:http://www.seeddsp.com/index.php/Home/Product/detail/name/1/id/174.ht…

字符串内存内部

本文基于我对StackOverflow的回答 。 我正在尝试解释String类如何存储文本,内部存储和常量池如何工作。 这里要理解的要点是String Java对象与其内容– private value字段下的char[]之间的区别。 String基本上是char[]数组的包装器,将其封装并使其无法修…

关于inline-block 元素之间为何会产生间隔

关于inline-block 元素之间为何会产生间隔 现象&#xff1a; <body><input type"text"><input type"text"> </body> 在浏览器中的表现&#xff1a; 实时上不仅仅是 inline-block 会导致这种现象。 inline 也会导致。 那问题来了&a…

java 入参 是 枚举_java 枚举 参数传递

展开全部这样做是不行的&#xff0c;原因是&#xff1a;Java中的对象实例化都是在堆中&#xff0c;如果是普通的类实例变量&#xff0c;比如在方法636f707962616964757a686964616f313333376166371中定义的普通类实例变量&#xff0c;传到了方法2中&#xff0c;由于方法1和方法2…

loadView的使用总结

一、loadView 1. loadView什么时候被调用&#xff1f; 每次访问UIViewController的view&#xff08;如 controller.view、self.view&#xff09;并且view为nil&#xff0c;loadView方法就会被调用 2. 有什么作用 loadView 方法是用来负责创建UIViewController的view 3. 默认实…

数据库备份 java jar_Java实现数据库备份并利用ant导入SQL脚本

​数据备份对于经常在运维部署方面的工作者来说&#xff0c;是一件相对简单的事情&#xff0c;都可以通过某一个SQL工具进行备份&#xff0c;但是如果在项目运行当中&#xff0c;我们需要对数据进行实时&#xff0c;或者是每隔一星期&#xff0c;一个月&#xff0c;等等进行数据…

JSF简单Ajax示例

今天&#xff0c;我们将看到一些使用JSF的Ajax简单样本。 如果要查看有关JSF / Web应用程序的其他文章&#xff0c;请单击以下链接&#xff1a; 重定向后的JSF持久化对象和消息 &#xff0c; 使用JAAS和JSF进行用户登录验证 &#xff0c; JSF&#xff1a;Converter and Bean Au…

常用的好用的window工具

1. FastStone Capture截图录屏软件 百度软件中心&#xff1a;http://rj.baidu.com/soft/detail/13504.html?ald 注册企业版&#xff1a; 用户名&#xff1a;c1ikm 注册码&#xff1a;AXMQX-RMMMJ-DBHHF-WIHTV 中文输入乱码解决方法&#xff1a; 2. Notepad文本编辑器&#xff…

表分区

http://www.cnblogs.com/leestar54/p/6225821.html转载于:https://www.cnblogs.com/jouny/p/6262850.html

java飞鸽传书_feige 飞鸽传书源代码java 实现不错的联系网络编程的资料飞鸽传书的GUI(java实现) - 下载 - 搜珍网...

我的飞鸽传书/FileFilter.java我的飞鸽传书/FileNameExtensionFilter.java我的飞鸽传书/飞鸽传书/classes/feige/About.class我的飞鸽传书/飞鸽传书/classes/feige/ConnectOthers$ReadMessageThread.class我的飞鸽传书/飞鸽传书/classes/feige/ConnectOthers.class我的飞鸽传书…

JAXB和根元素

XmlRootElement是人们习惯于与JAXB&#xff08;JSR-222&#xff09;一起使用的注释。 目的是将根元素与类唯一关联。 由于JAXB类映射到复杂类型&#xff0c;因此一个类有可能对应于多个根元素。 在这种情况下&#xff0c;无法使用XmlRootElement &#xff0c;人们开始感到有些困…

python socket模块实现udp通信_Python基于socket模块实现UDP通信功能示例

Python基于socket模块实现UDP通信功能示例本文实例讲述了Python基于socket模块实现UDP通信功能。分享给大家供大家参考&#xff0c;具体如下&#xff1a;一 代码1、接收端import socket#使用IPV4协议&#xff0c;使用UDP协议传输数据ssocket.socket(socket.AF_INET, socket.SOC…

Hibernate缓存基础知识

最近&#xff0c;我尝试了休眠缓存。 在这篇文章中&#xff0c;我想分享我的经验&#xff0c;并指出Hibernate Second Level Cache的一些细节。 在此过程中&#xff0c;我将指导您阅读一些有助于实现缓存的文章。 让我们从地面开始。 在休眠状态下缓存 缓存功能旨在减少必要的…

TP3.2之WHERE组合条件处理

1、条件都是int类型&#xff1a; $User->where(type1 AND status1)->select(); 2、条件包含字符串类型&#xff1a; 使用3.1以上版本的话&#xff0c;使用字符串条件的时候&#xff0c;建议配合预处理机制&#xff0c;确保更加安全&#xff0c; $Model->where("i…

linux-ssh远程后台执行脚本-放置后台执行问题(转)

写了一个监控负载的小脚本&#xff08;死循环&#xff0c;测试结束后再kill对应进程&#xff09;&#xff0c;因需要监控多台服务器&#xff0c;所以在一台服务器上使用ssh统一执行脚本遇到问题&#xff1a;使用ssh root172.16.146.20 /usr/local/luly/loadavg.sh 2 2 &执行…

python2.7输入函数_Python2.7的用户输入函数有问题,无法让这些输入与程序一起工作...

我对python世界还是个新手&#xff0c;虽然我已经用php做了很多工作。。。这是我的案子。。。在我正在用python2.7为我的小程序编写一些代码。在在那个程序中&#xff0c;我需要2个用户输入&#xff0c;它们都是数字。在第一个数字不得大于11&#xff0c;也不得小于0。在第二个…

创建Java动态代理

Java动态代理机制提供了一种有趣的方式来创建代理实例。 不过&#xff0c;创建动态代理的步骤有些繁琐&#xff0c;请考虑将代理用于审核服务实例的方法调用所花费的时间– public interface InventoryService {public Inventory create(Inventory inventory);public List<I…