ActiveMQ是一款基於Java的開源消息服務器產品,所以,咱們能夠將其集成到經過Java實現的業務系統中。下面將對集成方法作一個簡單的總結。java
首先,咱們看一下ActiveMQ中的部分核心類:apache
org.apache.activemq.Service是ActiveMQ中的一個接口,定義了start和stop方法。org.apache.activemq.broker.BrokerService是ActiveMQ中的核心類,其實現自Service接口,用於對外提供消息服務。org.apache.activemq.broker.XBeanBrokerService是BrokerService的一個子類,XBeanBrokerService實例能夠經過xbean xml配置文件生成。ActiveMQ做爲單獨服務啓動時,其配置文件activemq.xml就是xbean xml格式的,啓動後生成的就是一個XBeanBrokerService實例。服務器
1.經過VM協議實現集成:tcp
客戶端鏈接ActiveMQ消息服務器時,能夠使用多種協議(TCP、VM、STOMP等),其中VM協議是指客戶端會從當前JVM中查找ActiveMQ消息服務器實例,若查找到,則與其創建鏈接,若查找不到,則自動建立ActiveMQ消息服務器實例。若是客戶端和服務器端都在一個JVM中,則能夠經過VM協議實現ActiveMQ消息服務器的自動建立、與業務系統的集成。ide
2.直接建立BrokerService實例:spa
public static void main(String[] args)throws Exception { BrokerService broker = new BrokerService(); broker.setBrokerName("myBroker"); broker.setDataDirectory("data/"); SimpleAuthenticationPlugin authentication = newSimpleAuthenticationPlugin(); List<AuthenticationUser> users = newArrayList<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(); }
3.使用工廠方法建立BrokerService實例:xml
public static void main(String[] args)throws Exception { System.setProperty("activemq.base",System.getProperty("user.dir")); String configUri ="xbean:activemq.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(); }
4.經過Spring配置直接建立BrokerService實例blog
<bean id="simpleAuthPlugin「class="org.apache.activemq.security.SimpleAuthenticationPlugin"> <property name="users"> <util:list> <ref bean="admins" /> <ref bean="publishers" /> <ref bean="consumers" /> <ref bean="guests" /> </util:list> </property> </bean> <bean id="broker"class="org.apache.activemq.broker.BrokerService" init-method="start"destroy-method="stop"> <property name="brokerName"value="myBroker" /> <property name="persistent"value="false" /> <propertyname="transportConnectorURIs"> <list><value>tcp://localhost:61616</value></list> </property> <property name="plugins"> <list><refbean="simpleAuthPlugin"/></list> </property> </bean>
5.經過Spring配置使用BrokerFactoryBean建立BrokerService實例:接口
<bean id="broker「class="org.apache.activemq.xbean.BrokerFactoryBean"> <property name="config" value="classpath:activemq.xml"/> <property name="start"value="true" /> </bean>