上文主要简单地将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 = new String[2];
args[0] = "MyTopic";
args[1] = "3"; if ((args.length < 1) || (args.length > 2)) {
LOG.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]");
System.exit(1);
} destinationName = args[0];
LOG.info("Destination name is " + destinationName); if (args.length == 2) {
numMsgs = (new Integer(args[1])).intValue();
}
else {
numMsgs = 1;
} /*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
}
catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
} /*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("ConnectionFactory");
destination = (Destination)jndiContext.lookup(destinationName);
}
catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + 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 = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage(); for (int i = 0; i < numMsgs; i++) {
message.setText("This is message " + (i + 1));
LOG.info("Sending message: " + 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: " + e);
}
finally {
       //睡眠是我手动加的,主要为了观察效果
try {
Thread.sleep(100000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (connection != null) {
try {
connection.close();
}
catch (JMSException ignored) {}
}
}
}
}

代码不难理解:jndi读取配置文件,建立连接,发消息,关闭连接。

运行结果:

此时查看Web Console,

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

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

欢迎留言交流。

ActiveMQ学习系列(二)----生产者客户端(java)的更多相关文章

  1. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

  2. RabbitMQ学习系列二-C#代码发送消息

    RabbitMQ学习系列二:.net 环境下 C#代码使用 RabbitMQ 消息队列 http://www.80iter.com/blog/1437455520862503 上一篇已经讲了Rabbi ...

  3. .net reactor 学习系列(二)---.net reactor界面各功能说明

    原文:.net reactor 学习系列(二)---.net reactor界面各功能说明         安装了.net reactor之后,可以在安装目录下找到帮助文档REACTOR_HELP.c ...

  4. Maven学习系列二(1-5)

    Maven学习系列二(1-5) 本文转自 QuantSeven 博客,讲解精炼易懂,适合入门,链接及截图如下 http://www.cnblogs.com/quanyongan/category/47 ...

  5. scrapy爬虫学习系列二:scrapy简单爬虫样例学习

    系列文章列表: scrapy爬虫学习系列一:scrapy爬虫环境的准备:      http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_python_00 ...

  6. DocX开源WORD操作组件的学习系列二

    DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...

  7. [转]ASP.NET MVC学习系列(二)-WebAPI请求 传参

    [转]ASP.NET MVC学习系列(二)-WebAPI请求 传参 本文转自:http://www.cnblogs.com/babycool/p/3922738.html ASP.NET MVC学习系 ...

  8. 图机器学习(GML)&图神经网络(GNN)原理和代码实现(前置学习系列二)

    项目链接:https://aistudio.baidu.com/aistudio/projectdetail/4990947?contributionType=1 欢迎fork欢迎三连!文章篇幅有限, ...

  9. Java I/O系统学习系列二:输入和输出

    编程语言的I/O类库中常使用流这个抽象概念,它代表任何有能力产出数据的数据源对象或者是有能力接收数据的接收端对象.“流”屏蔽了实际的I/O设备中处理数据的细节. 在这个系列的第一篇文章:<< ...

随机推荐

  1. PHP面试和PHP开发者都应掌握的10个问题

    PHP面试和PHP开发者都应掌握的10个问题 问题 :1 MySQL里的存储引擎有什么不同,哪一个是默认的? 答案: 1 我们可以一下存储引擎: 1. MyISAM(MySQL的默认引擎. 每个MyI ...

  2. POJ1331 Multiply(strtol函数练习)

    题目链接:http://poj.org/problem?id=1331 主要介绍strtol函数: long int strtol(const char *nptr,char **endptr,int ...

  3. Android_Jar mismatch! Fix your dependencies

    在用adt开发安卓时,添加依赖的library后,经常会出现错误,Jar mismatch! Fix your dependencies 这个错误的原因是.出现了不同版本的jar包(例如:V4包版本不 ...

  4. 【Python】 sys和os模块

    sys sys模块能使程序访问于python解释器联系紧密的变量和函数 ● sys中的一些函数和变量 argv 命令行参数构成的列表 path 查找所有可用模块所在的目录名的列表 platform 查 ...

  5. grep -vFf 比较2个文件差异

    grep -vFf 1.txt 2.txt   打印出2.txt中与1.txt有差异的数据. #cat .txt 192.168.0.1 192.168.0.2 192.168.0.3 #cat .t ...

  6. 韩天峰博客 php基础知识学习记录

    http://rango.swoole.com 写好PHP代码真的不容易,给大家几个建议: 慎用全局变量,全局变量不好管理的,会导致你的代码依赖于全局变量,而耦合度太高. 一定不要复制粘贴代码,可重用 ...

  7. Comparable接口和Comparator接口

    1.一个类在设计之初就要实现对该类对象的排序功能,那么这个类要实现Comparable接口,实现public int compareTo(T t)方法.如代码中的Student类.对于实现Compar ...

  8. 关于Netty的入门使用

    Netty介绍: Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能.高可靠性的网络服务器和客户端程序. 换句话说,Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比 ...

  9. 云计算--网络原理与应用--20171120--VLAN与三层交换机配置

    什么是VLAN及其配置 Trunk的原理与配置 三层交换机的基本配置 实验:配置一个三层交换机 一 VLAN 的概念及优势 VLAN(virtual local area network)就是虚拟局域 ...

  10. C语言程序设计(基础)- 第14、15周作业

    从本周开始,将作业标记为学校自然周,而不是开课的周数. 要求一(25经验值) 完成14.15周的所有PTA中题目集. 注意1:一周两次pta作业,包括四次. 要求二(50经验值) 博客的具体书写内容和 ...