一、通过JNDI来使用ActiveMQ

1、jndi配置JMS对象

java.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

2、客户端代码使用

// create a new intial context, which loads from jndi.properties file
javax.naming.Context ctx = new javax.naming.InitialContext();
// lookup the connection factory
javax.jms.TopicConnectionFactory factory = (javax.jms.TopicConnectionFactory)ctx.lookup("ConnectionFactory");
// create a new TopicConnection for pub/sub messaging
javax.jms.TopicConnection conn = factory.getTopicConnection();
// lookup an existing topic
javax.jms.Topic mytopic = (javax.jms.Topic)ctx.lookup("MyTopic");
// create a new TopicSession for the client
javax.jms.TopicSession session = conn.createTopicSession(false,TopicSession.AUTO_ACKNOWLEDGE);
// create a new subscriber to receive messages
javax.jms.TopicSubscriber subscriber = session.createSubscriber(mytopic);

Notice the name of the topic in the sample is "MyTopic". ActiveMQ will read the jndi.properties files and creates the topics and queues in a lazy fashion. The prefix topic and queue is stripped, so the jndi name begins after the prefix.

Once you have the jndi.properties edited and ready, it needs to be accessible to your application. The easiest way is to add jndi.properties to a jar file. When "new InitialContext()" is called, it will scan the resources and find the file. If you get "javax.naming.NamingException", it usually means the jndi.properties file is not accessible.

3、通过Porperties来设置

Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL,"tcp://hostname:61616");
javax.naming.Context ctx = new InitialContext(props);

4、Example Java Code

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* A simple polymorphic JMS producer which can work with Queues or Topics which
* uses JNDI to lookup the JMS connection factory and destination
*
*
*/
public final 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; 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 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 {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}

二、使用spring来使用ActiveMQ

1、使用spring配置ConnectionFactory

<bean id="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>

或者使用Zeroconf来查询可用的brokers

<bean id="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>zeroconf://_activemq.broker.development.</value>
</property>
</bean>

如果是使用的是spring2.0以上版本,则不需要显式配置factory bean

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd"> <amq:broker useJmx="false" persistent="false">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://localhost:0" />
</amq:transportConnectors>
</amq:broker> <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost"/>
</beans>

2、配置使用JmsTemplate,此处使用了ActiveMQ自带的连接池

!-- a pooling based JMS provider -->
<bean id="jmsFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
<property name="connectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>
</property>
</bean> <!-- Spring JMS Template -->
<bean id="myJmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref local="jmsFactory"/>
</property>
</bean>

ActiveMQ客户端配置使用的更多相关文章

  1. ActiveMQ安装配置及使用 转发 https://www.cnblogs.com/hushaojun/p/6016709.html

    ActiveMQ安装配置及使用 ActiveMQ介绍 ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JM ...

  2. NFS服务器+客户端配置

    NFS:Network File System 使用NFS需要启用RPC(remoteprocedure call),RPC可以指定每个NFS功能所对应的端口号,重启RPC后,RPC所管理的所有NFS ...

  3. CentOS下OpenVPN客户端配置

    CentOS下OpenVPN客户端配置 http://liumissyou.blog.51cto.com/4828343/1762683 1,安装 yum install openvpn -y mkd ...

  4. 如何利用tomcat和cas实现单点登录(2):配置cas数据库验证和cas客户端配置

    接(1),上一篇主要讲述了tomcat和cas server端的部署. 接下来主要还有两个步骤. 注意:为了开启两个tomcat,要把直接配置的tomcat的环境变量取消!!!!!!!!!! 客户端配 ...

  5. 在 ServiceModel 客户端配置部分中,找不到引用协定“WebServiceTest.WebServiceSoap”的默认终结点元素。这可能是因为未找到应用程序的配置文件,或者是因为客户端元素

    原文  http://blog.csdn.net/bugdemo/article/details/9083497 主题 技术 在引用WebService后,程序运行到实例化WebService时报错, ...

  6. Cas服务器设置(java),java、php客户端配置

    由于多个项目需要帐号的互通,所以一开始就是用cas去做的,不得不说cas要配置的东西挺多的,但是项目安全性不需要太高,所以没有做https的请求,也就是没有弄证书,这虽然省了很多时间和精力,但是项目之 ...

  7. 使用Jmeter测试MySQL性能——(2)多客户端配置

    在测试性能过程中,单个测试客户端可能存在性能瓶颈无法达到测试要求的压力.在这种情况下,可以设置jmeter的多客户端模式,然后通过一台控制端,同时控制多台PC上的客户端向服务器发送测试请求.若有4台P ...

  8. shadow服务端、客户端配置流程

    服务端 系统环境 CentOS 7 64位,由于系统自带python,shadowsocks服务端我们选择python版,过程如下 yum install python-setuptools & ...

  9. 在 ServiceModel 客户端配置部分中,找不到引用协定“PmWs.PmWebServiceSoap”的默认终结点元素

    System.Exception: ConfigManager.LoadConfigurationFromDb ServiceFactory.GetPmWebService 在 ServiceMode ...

随机推荐

  1. Unity5.X 创建基本的3D游戏场景

    点New(新建懒得写了,反正不是智障应该都会) 创建好的项目会自带一个场景,场景会自带Main Camera (主摄像机),Directional Light (方向光)   系统自带几个可以创建的3 ...

  2. How Many Partitions Does An RDD Have

    From https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/performance_optimization ...

  3. 你应该更新的 Java 知识

    作者:dreamhead 出处:<你应该更新的Java知识>系列 你应该更新的 Java 知识 Tag:你应该更新的Java知识 Java Guava 集合 版权声明:转载时请以超链接形式 ...

  4. HDU 2842 Chinese Rings( 递推关系式 + 矩阵快速幂 )

    链接:传送门 题意:解 N 连环最少步数 % 200907 思路:对于 N 连环来说,解 N 连环首先得先解 N-2 连环然后接着解第 N 个环,然后再将前面 N-2 个环放到棍子上,然后 N 连环问 ...

  5. BZOJ 3675 [Apio2014]序列分割 (斜率优化DP)

    洛谷传送门 题目大意:让你把序列切割k次,每次切割你能获得 这一整块两侧数字和的乘积 的分数,求最大的分数并输出切割方案 神题= = 搞了半天也没有想到切割顺序竟然和答案无关...我太弱了 证明很简单 ...

  6. 笔记本安装Archlinux笔记

    同步更新于wendster大佬的个人博客 搬运自我的洛谷博客 可能会不定期更新! 因为前几天给我的小炸鸡加了一根内存条:而且先前装的Xubuntu是32位的,使用极其不方便:再加上wendster大佬 ...

  7. python的装饰器,迭代器用法

    装饰器. 装饰器实际就是一个函数 定义:在不改变内部代码和调用方式的基础上增加新的功能 了解装饰器需要了解3个内容: 1.函数即变量 2.高阶函数 1).把一个函数名当作实参传给另一个函数 2).返回 ...

  8. (56) 解决字段设为readonly无法保存

    问题描述:当一个字段设为readonly =True 后,在form表单,即使你用onchange方法改变了值但也不能保存到数据库当时.平时在这样的要求,form表单有些字段要展示给用户,但又要达到不 ...

  9. 《一个民企CEO的职场阳谋》–读书总结(上)

    职场是一个战场,很多人几十年在这里战斗. 职场是一个熔炉,很多人大半生在这里修炼. 如果在办公室里得不到快乐,生活就不会快乐. 如果公司里头感觉不到幸福,人生就不会幸福.(以上四句来自老刘的博客) & ...

  10. [terry笔记]python FTP

    如下是作业,用python做一个ftp,主要利用socket. server端在linux下运行,在client端可以执行shell命令(静态的) 在client端输入get xxx,即可下载. 在c ...