热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ActiveMQ学习系列(二)生产者客户端(java)

上文主要简单地将activeMq搭建了起来,并且可以用webconsole去登录查看相关的后台功能。本文将学习如何用java语言实现一个生产者客户端,主

上文主要简单地将activeMq搭建了起来,并且可以用web console去登录查看相关的后台功能。

本文将学习如何用java语言实现一个生产者客户端,主要参考了以下链接:

http://activemq.apache.org/jndi-support.html

代码已上传github,建议先下载下来实际运行一遍:

https://github.com/cctvckl/big-data-learning/tree/master/activemq-learning

 

一、ActiveMq支持的协议

ActiveMq作为消息中间件,支持多种连接协议,如:tcp、amqp、stomp、mqtt等。

如果启动时以./activemq console方式启动,可以看到如下输出:

而下文将要讲解的java客户端程序,就是基于其中的tcp协议。

将tcp://host:port这个地址记录下来,下面需要用到。

二、大体思路

1、本地配置文件,配置要连接的ActiveMq服务器、包括连接协议和端口号,配置要发送消息的目标队列、目标topic等等。

2、程序读取上述配置文件,生成连接会话、生成消息生产者、发送消息、关闭连接。
三、具体步骤

1、配置文件样例:

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory# Use the following property to configure the default connector
java.naming.provider.url = tcp://192.168.2.140:61616# 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

释义:上面的url项要与第一章节里面的那个地址匹配;

topic.MyTopic中的点号分割开的第二部分(此例为MyTopic)会被注册为JNDI名, 至于value(example.MyTopic)为topic名,在Web Console可以看到。

 

queue.MyQueue同理。

 

2、配置文件完毕,下面介绍业务代码:

package com.ckl.activemq;
/*** The SimpleQueueSender class consists only of a main method,* which sends several messages to a queue.** Run this program in conjunction with SimpleQueueReceiver.* Specify a queue name on the command line when you run the* program. By default, the program sends one message. Specify* a number after the queue name to send that number of messages.*/import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;/*** A simple polymorphic JMS producer which can work with Queues or Topics which* uses JNDI to lookup the JMS connection factory and destination.*/
public class SimpleProducer {private static final Logger LOG = LoggerFactory.getLogger(SimpleProducer.class);private SimpleProducer() {}/*** @param args the destination name to send to and optionally, the number of* messages to send*/public static void main(String[] args) {Context jndiContext = null;ConnectionFactory connectionFactory = null;Connection connection = null;Session session = null;Destination destination = null;MessageProducer producer = null;String destinationName = null;final int numMsgs;
    //这边被我手动修改了,比较不喜欢每次运行时还要修改Run configuration,麻烦。args
&#61; new String[2];args[0] &#61; "MyTopic";args[1] &#61; "3";if ((args.length <1) || (args.length > 2)) {LOG.info("Usage: java SimpleProducer []");System.exit(1);}destinationName &#61; args[0];LOG.info("Destination name is " &#43; destinationName);if (args.length &#61;&#61; 2) {numMsgs &#61; (new Integer(args[1])).intValue();}else {numMsgs &#61; 1;}/** Create a JNDI API InitialContext object*/try {jndiContext &#61; new InitialContext();}catch (NamingException e) {LOG.info("Could not create JNDI API context: " &#43; e.toString());System.exit(1);}/** Look up connection factory and destination.*/try {connectionFactory &#61; (ConnectionFactory)jndiContext.lookup("ConnectionFactory");destination &#61; (Destination)jndiContext.lookup(destinationName);}catch (NamingException e) {LOG.info("JNDI API lookup failed: " &#43; e);System.exit(1);}/** Create connection. Create session from connection; false means* session is not transacted. Create sender and text message. Send* messages, varying text slightly. Send end-of-messages message.* Finally, close the connection.*/try {connection &#61; connectionFactory.createConnection();session &#61; connection.createSession(false, Session.AUTO_ACKNOWLEDGE);producer &#61; session.createProducer(destination);TextMessage message &#61; session.createTextMessage();for (int i &#61; 0; i ) {message.setText("This is message " &#43; (i &#43; 1));LOG.info("Sending message: " &#43; message.getText());producer.send(message);}/** Send a non-text control message indicating end of messages.*/producer.send(session.createMessage());}catch (JMSException e) {LOG.info("Exception occurred: " &#43; e);}finally {
       //睡眠是我手动加的&#xff0c;主要为了观察效果
try {Thread.sleep(100000L);} catch (InterruptedException e) {e.printStackTrace();}if (connection !&#61; null) {try {connection.close();}catch (JMSException ignored) {}}}}
}

代码不难理解&#xff1a;jndi读取配置文件&#xff0c;建立连接&#xff0c;发消息&#xff0c;关闭连接。

运行结果&#xff1a;

 

此时查看Web Console&#xff0c;

可以看到来自客户端的连接信息。

 

本例子就先到这里&#xff0c;详细还请参考贴的代码链接和官网文档。

欢迎留言交流。

 

转:https://www.cnblogs.com/grey-wolf/p/6526352.html



推荐阅读
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 深入解析 Android IPC 中的 Messenger 机制
    本文详细介绍了 Android 中基于消息传递的进程间通信(IPC)机制——Messenger。通过实例和源码分析,帮助开发者更好地理解和使用这一高效的通信工具。 ... [详细]
  • [论文笔记] Crowdsourcing Translation: Professional Quality from Non-Professionals (ACL, 2011)
    Time:4hoursTimespan:Apr15–May3,2012OmarZaidan,ChrisCallison-Burch:CrowdsourcingTra ... [详细]
  • 本文介绍如何解决在 IIS 环境下 PHP 页面无法找到的问题。主要步骤包括配置 Internet 信息服务管理器中的 ISAPI 扩展和 Active Server Pages 设置,确保 PHP 脚本能够正常运行。 ... [详细]
  • 优化联通光猫DNS服务器设置
    本文详细介绍了如何为联通光猫配置DNS服务器地址,以提高网络解析效率和访问体验。通过智能线路解析功能,域名解析可以根据访问者的IP来源和类型进行差异化处理,从而实现更优的网络性能。 ... [详细]
  • 本文详细分析了JSP(JavaServer Pages)技术的主要优点和缺点,帮助开发者更好地理解其适用场景及潜在挑战。JSP作为一种服务器端技术,广泛应用于Web开发中。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • 如何配置Unturned服务器及其消息设置
    本文详细介绍了Unturned服务器的配置方法和消息设置技巧,帮助用户了解并优化服务器管理。同时,提供了关于云服务资源操作记录、远程登录设置以及文件传输的相关补充信息。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 网络攻防实战:从HTTP到HTTPS的演变
    本文通过一系列日记记录了从发现漏洞到逐步加强安全措施的过程,探讨了如何应对网络攻击并最终实现全面的安全防护。 ... [详细]
  • 在使用 MUI 框架进行应用开发时,开发者常常会遇到 mui.init() 和 mui.plusReady() 这两个方法。本文将详细解释它们的区别及其在不同开发环境下的应用。 ... [详细]
  • ASP.NET MVC中Area机制的实现与优化
    本文探讨了在ASP.NET MVC框架中,如何通过Area机制有效地组织和管理大规模应用程序的不同功能模块。通过合理的文件夹结构和命名规则,开发人员可以更高效地管理和扩展项目。 ... [详细]
  • docker镜像重启_docker怎么启动镜像dock ... [详细]
author-avatar
手机用户2502920043
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有