7.1 Java应用程序中 嵌入ActiveMQ
7.1 Embedding ActiveMQ using JavaAlthough most developers today use some kind of framework for composing theirapplications, it’s always good to start with plain old Java. In this section we’ll initializeand configure ActiveMQ using its Java APIs. You’ll see how to use the BrokerServiceclass to configure a broker using nothing but pure Java code. |
7.1 Java应用程序中 嵌入ActiveMQ目前,尽管大多数的开发者使用一些框架来组织他们的应用程序,但是使用原始的Java编码是一个好的开始.本节中我们将使用Java API来初始化和配置ActiveMQ,你将看到如何通过纯Java代码使用BrokerService类来配置代理. |
Next, we’ll describe how you can configure your broker using custom configurationXML files. We’ll use the BrokerFactory class to achieve this and you’ll learn howyou can use regular configuration files to embed the broker in your Java applications.After this section you’ll be able to embed ActiveMQ with any configuration in yourJava applications. |
接下来,我们将讨论如何使用自定义的XML文件配置代理,我们还会通过BrokerFactory类使用常规的配置文件将代理嵌入到你自己的Java应用程序中.通过本小节的学习,你将能够使用任何配置将ActiveMQ嵌入到你自己的Java应用程序中. |
7.1.1 Embedding ActiveMQ using the BrokerServiceWhen using plain old Java to set up your broker, the org.apache.activemq.broker.BrokerService class is one starting point. This class is used to configure the brokerand manage its entire lifecycle. The best way to demonstrate the usage of the Broker-Service class is with an appropriate example. Let’s start with a broker configurationwe used in chapter 6 to configure a simple authentication plug-in and see how we canachieve the same functionality with plain old Java code. For starters, let’s take a look atthe well-known XML configuration example shown here. Listing 7.1 Configure ActiveMQ with security plug-ins using XML |
7.1.1 使用BrokerService嵌入ActiveMQ使用原始的Java代码类设置代理的起点是使用org.apache.activemq.broker.BrokerService类.该类用于配置代理并管理其整个生命周期.使用一个合适的例子来说明是学习BrokerService类用法的最好的方式.现在,让我们从第6章中使用简单认证插件的配置例子开始,看看如何使用原始的Java代码来实现这个配置文件中配置的功能.下面,让我们看看之前使用的XML配置文件例子: 代码清单7.1 使用XML文件配置ActiveMQ安全插件 |
<broker xmlns="http://activemq.apache.org/schema/core" brokerName="myBroker" dataDirectory="${activemq.base}/data"> <transportConnectors> <transportConnector name="openwire" uri="tcp://localhost:61616" /> </transportConnectors> <plugins> <simpleAuthenticationPlugin> <users> <authenticationUser username="admin" password="password" groups="admins,publishers,consumers"/> <authenticationUser username="publisher" password="password" groups="publishers,consumers"/> <authenticationUser username="consumer" password="password" groups="consumers"/> <authenticationUser username="guest" password="password" groups="guests"/> </users> </simpleAuthenticationPlugin> </plugins> </broker> |
|
Listing 7.1 uses the standard ActiveMQ XML to define a broker instance with a nameand data directory, as well as one transport connector and one plug-in. Now look at thesame configuration using plain old Java and the BrokerService as shown next. |
代码清单7.1中使用了标准的ActiveMQ XML配置文件配置了一个包含name和data目录属性代理实例以及一个传输连接器和一个插件.下面看看使用原始的Java代码以及BrokerService类来完成同样配置的代码. |
public static void main(String[] args) throws Exception { BrokerService broker = new BrokerService(); broker.setBrokerName("myBroker"); broker.setDataDirectory("data/"); SimpleAuthenticationPlugin authentication = new SimpleAuthenticationPlugin(); List<AuthenticationUser> users = new ArrayList<AuthenticationUser>(); users.add(new AuthenticationUser("admin","password","admins,publishers,consumers")); users.add(new AuthenticationUser("publisher","password","publishers,consumers")); users.add(new AuthenticationUser("consumer","password","consumers")); users.add(new AuthenticationUser("guest","password","guests")); authentication.setUsers(users); broker.setPlugins(new BrokerPlugin[]{authentication}); broker.addConnector("tcp://localhost:61616"); broker.start(); System.out.println(); System.out.println("Press any key to stop the broker"); System.out.println(); System.in.read(); } |
|
As you can see, listing 7.2 instantiates the BrokerService and configures the broker-Name and dataDirectory properties. Next the SimpleAuthenticationPlugin is addedto the BrokerService via the setPlugins() method. Then a transport connector isadded to the BrokerService via the addConnector() method. Finally the start()method is used to start the BrokerService instance. Now your broker is fully initializedusing just plain old Java code; no XML configuration files were used. To see thisclass in action, execute it as shown in this listing. |
正如你看到的,代码清单7.2给出了使用BrokerService的例子并设置了brokerName和dataDirectory属性值.接着,通过setPlugins()方法为BrokerService添加了SimpleAuthenticationPlugin插件,然后通过addConnector()方法为BrokerService添加了一个传输连接器.最后使用start()方法启动BrokerService实例.至此,你已经利用原始的Java代码完整的初始了代理,并且没有使用任何XML配置文件.运行下面的命令看看这个类是如何工作的: |
$ mvn exec:java -Dexec.mainClass=org.apache.activemq.book.ch6.broker.Broker -Dlog4j.configuration=file:src/main/java/log4j.properties (译注: 貌似 org.apache.activemq.book.ch7.broker.Broker 这个应该是第6章的类:org.apache.activemq.book.ch6.broker.Broker) ... [INFO] [exec:java {execution: default-cli}] INFO | Using Persistence Adapter: AMQPersistenceAdapter(data/localhost) INFO | AMQStore starting using directory: data/localhost INFO | Kaha Store using data directory data/localhost/kr-store/state INFO | AMQPersistenceAdapter - Active data files: [] INFO | ActiveMQ 5.4.1 JMS Message Broker (localhost) is starting INFO | For help or more information please see: http://activemq.apache.org/ INFO | Kaha Store using data directory data/localhost/kr-store/data INFO | Listening for connections at: tcp://localhost:61616 INFO | Connector tcp://localhost:61616 Started INFO | JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi INFO | ActiveMQ JMS Message Broker (localhost, ID:dejanb-63935-1269536159457-0:0) started Press any key to stop the broker ... |
|
One important thing to note in listing 7.3 is that you should always add your plug-insbefore connectors; otherwise they won’t be initialized. Also, any connectors addedafter the broker has been started won’t be properly started either. The BrokerService class is useful when you want to use plain old Java for the brokerconfiguration. This method is useful for many situations where you don’t need anexternally customizable configuration. In many applications, you’ll want to be able toinitialize the broker using the same configuration files used to configure standaloneinstances of the ActiveMQ broker. For that purpose ActiveMQ provides the utilityorg.apache.activemq.broker.BrokerFactory class. |
代码清单7.3中需要重点注意的是你应该在添加连接器之前添加安全插件,否则插件不能被初始化.同样,在代理启动之后添加的连接器也不会被启动. 当你采用原始的Java代码来配置代理时,BrokerService类就显得非常用.这种使用Java原始代码操作BrokerService的方法适用于那些你不需要使用外部自定义配置来配置代理的应用场景.在很多应用中,你可能希望能用配置独立ActiveMQ代理实例的配置文件来初始化代理.为此,ActiveMQ提供工具类org.apache.activemq.broker.BrokerFactory. |
7.1.2 Embedding ActiveMQ using the BrokerFactoryThe BrokerFactory class is a utility that makes it easy to create a broker instance simplyusing an ActiveMQ URI. Depending on the broker URI scheme, the BrokerFactorylocates the appropriate factory and uses it to create an instance of the BrokerServiceclass. The most widely used factory is the XBeanBrokerFactory class and is configuredby simply passing the XBean-style of URI. An example of an XBean broker URI isshown next:xbean:/path/to/activemq.xml |
7.1.2 使用BrokerFactory嵌入ActiveMQ使用BrokerFactory工具类可以很方便的通过ActiveMQ URI来创建一个代理实例.BrokerFactory根据代理URI的主题使用适当的工厂类创建BrokerService实例.最常用的工厂类是XBeanBrokerFactory类,配置时传递一个XBean风格的UEI.下面是一个XBean代理的URI示例:xbean:/path/to/activemq.xml |
This example URI tells the BrokerFactory to use the XBeanBrokerFactory and thepath following the colon to create the broker instance. Now, let’s look at the following listing. The BrokerFactory can instantiate theBrokerService class using the standard ActiveMQ XML configuration file as shown. |
这个示例URI通知BrokerFactory使用XBeanBrokerFactory工厂类以及冒号后面的路径指定的配置文件创建一个代理实例. 现在,让我们看看下面的代码列表– BrokerFactory通过BrokerService类使用标准的ActiveMQXML配置文件初始化BrokerService类: |
public class Factory { public static void main(String[] args) throws Exception { System.setProperty("activemq.base", System.getProperty("user.dir")); String configUri = "xbean:target/classes/org/apache/activemq/book/ch6/activemq-simple.xml" URI brokerUri = new URI(configUri); BrokerService broker = BrokerFactory.createBroker(brokerUri); broker.start(); System.out.println(); System.out.println("Press any key to stop the broker"); System.out.println(); System.in.read(); } } |
|
As you can see in listing 7.4, the BrokerFactory.createBroker() method uses a configurationURI to create the BrokerService instance. Note that the configuration URIused in listing 7.4 is the xbean: URI scheme. This tells the broker factory to search forthe given XML configuration file in the classpath or somewhere on the file system. Toillustrate this example in action, the following listing shows how to execute it. |
正如代码清单7.4所示,BrokerFactory.createBroker()使用一个URI来创建BrokerService实例.注意,该代码中使用了xbean:这个URI主题,通知代理工厂到当前类路径或文件系统其他地方查询给定的XML配置文件.可以使用下面的命令看看上述代码的执行情况: |
$ mvn exec:java -Dexec.mainClass=org.apache.activemq.book.ch6.broker.Factory -Dlog4j.configuration=file:src/main/java/log4j.properties (译注:org.apache.activemq.book.ch7.broker.Factory 貌似应该是org.apache.activemq.book.ch6.broker.Factory,源码里面是这样) ... [INFO] [exec:java {execution: default-cli}] INFO | Using Persistence Adapter: AMQPersistenceAdapter(data/localhost) INFO | AMQStore starting using directory: data/localhost INFO | Kaha Store using data directory data/localhost/kr-store/state INFO | Active data files: [] INFO | ActiveMQ 5.4.1 JMS Message Broker (localhost) is starting INFO | For help or more information please see: http://activemq.apache.org/ INFO | Kaha Store using data directory data/localhost/kr-store/data INFO | Listening for connections at: tcp://localhost:61616 INFO | Connector openwire Started INFO | ActiveMQ JMS Message Broker (localhost, ID:dejanb-65001-1269594442403-0:0) started Press any key to stop the broker ... |
|
You can also use the broker: URI scheme for simple broker configuration performed completely via the configuration URI. See the following example URI: |
你也可以配置broker: 这样主题的URI来配置普通的代理.下面是这种URI的例子: |
broker:(tcp://localhost:61616,network:static:tcp://remotehost:61616)?persistent=false&useJmx=true |
|
This single URI contains enough configuration to start up a broker, including bothnetwork and transport connectors; persistence has been disabled and JMX has beenexplicitly enabled. For more information, see the complete URI reference on theActiveMQ website (http://mng.bz/FNos). |
这个单独的URI已经包含了启动一个代理的足够信息,包含了网络连接信息和传输连接信息,并且禁用了消息持久化,同时明确的启用了JMX.更多相关信息请参阅ActiveMQ站点的URI文档(http://mng.bz/FNos). |
As mentioned earlier, most Java developers use some kind of framework to composetheir applications. Since the Spring Framework (http://www.springframework.org/) is the most popular framework used today, let’s examine how to configure anduse ActiveMQ as a component in a Spring application. |
前文已经提到过,大多数Java开发人员使用框架来架构他们的程序.Spring框架(http://www.springframework.org/)是当今最流行的框架,下面我探讨如何配置ActiveMQ成Spring的一个组件. |
微信赞赏 支付宝赞赏
本文固定链接: https://www.jack-yin.com/coding/translation/activemq-in-action/1545.html | 边城网事