JMS&MQ系统之Spring中嵌入ActiveMQ

2019-03-14 13:23|来源: geloin

1. 纯Spring配置文件

所谓纯Spring配置文件,就是直接在Spring的配置文件中配置ActiveMQ,代码如下所示:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    
    <!-- 其他Spring配置 -->
    
    <bean id="admins" class="org.apache.activemq.security.AuthenticationUser">
        <constructor-arg index="0" value="admin" />
        <constructor-arg index="1" value="password" />
        <constructor-arg index="2" value="admins,publishers,consumers" />
    </bean>
    <bean id="publishers" class="org.apache.activemq.security.AuthenticationUser">
        <constructor-arg index="0" value="publisher" />
        <constructor-arg index="1" value="password" />
        <constructor-arg index="2" value="publishers,consumers" />
    </bean>
    <bean id="consumers" class="org.apache.activemq.security.AuthenticationUser">
        <constructor-arg index="0" value="consumer" />
        <constructor-arg index="1" value="password" />
        <constructor-arg index="2" value="consumers" />
    </bean>
    <bean id="guests" class="org.apache.activemq.security.AuthenticationUser">
        <constructor-arg index="0" value="guest" />
        <constructor-arg index="1" value="password" />
        <constructor-arg index="2" value="guests" />
    </bean>
    <bean id="simpleAuthPlugin" class="org.apache.activemq.security.SimpleAuthenticationPlugin">
        <property name="users">
            <list>
                <ref bean="admins" />
                <ref bean="publishers" />
                <ref bean="consumers" />
                <ref bean="guests" />
            </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" />
        <property name="transportConnectorURIs">
            <list>
                <value>tcp://localhost:61616</value>
            </list>
        </property>
        <property name="plugins">
            <list>
                <ref bean="simpleAuthPlugin" />
            </list>
        </property>
    </bean>
</beans> 
如果你看过JMS&MQ系列之普通Java程序中加载配置,你肯定可以马上将这一段代码与ActiveMQ的配置文件对应起来。

2. 使用Spring的配置文件并引入ActiveMQ的配置文件

ActiveMQ的配置文件不再赘述,Spring的配置文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    
    <!-- 其他Spring配置 -->
    
    <bean id="broker" class="org.apache.activemq.xbean.BrokerFactoryBean">
        <property name="config" value="activemq.xml" />
        <property name="start" value="true"></property>
    </bean>
</beans> 
3. 使用硬代码及ActiveMQ配置文件。使用这种方式时,若ActiveMQ已被创建,则不能再次被创建。activemq.xml文件的内容不再赘述,硬代码如下所示:

/**
 *
 * @author geloin
 * @date 2012-9-12 下午3:42:55
 */
package com.geloin.activemq.test2;

import java.util.Hashtable;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.xbean.spring.context.FileSystemXmlApplicationContext;

/**
 *
 * @author geloin
 * @date 2012-9-12 下午3:42:55
 */
public class MyConfiguration3 {

    private int MAX_DELTA_PERCENT = 1;
    private Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();

    private static String brokerURL = "tcp://localhost:61616";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient Session session;
    private transient MessageProducer producer;

    private String username = "publisher";
    private String password = "password";

    /**
     * 发送消息
     *
     * @author geloin
     * @date 2012-9-12 下午3:56:11
     * @param stocks
     * @throws JMSException
     */
    private void sendMessage(String[] stocks) throws JMSException {
        // 随机选择某一项作为消息主题
        int idx = 0;
        while (true) {
            idx = (int) Math.round(stocks.length * Math.random());
            if (idx < stocks.length) {
                break;
            }
        }
        String stock = stocks[idx];

        // 目的
        Destination destination = session.createTopic("STOCKS." + stock);

        // 消息内容
        Message message = createStockMessage(stock, session);

        // 发送消息
        producer.send(destination, message);

    }

    /**
     * 创建消息内容
     *
     * @author geloin
     * @date 2012-9-12 下午3:58:09
     * @param stock
     * @param session
     * @return
     * @throws JMSException
     */
    private Message createStockMessage(String stock, Session session)
            throws JMSException {
        Double value = LAST_PRICES.get(stock);
        if (value == null) {
            value = new Double(Math.random() * 100);
        }

        // lets mutate the value by some percentage
        double oldPrice = value.doubleValue();
        value = new Double(mutatePrice(oldPrice));
        LAST_PRICES.put(stock, value);
        double price = value.doubleValue();

        double offer = price * 1.001;

        boolean up = (price > oldPrice);
        MapMessage message = session.createMapMessage();
        message.setString("stock", stock);
        message.setDouble("price", price);
        message.setDouble("offer", offer);
        message.setBoolean("up", up);
        return message;
    }

    private double mutatePrice(double price) {
        double percentChange = (2 * Math.random() * MAX_DELTA_PERCENT)
                - MAX_DELTA_PERCENT;

        return price * (100 + percentChange) / 100;
    }

    /**
     * 构造子
     *
     * @author geloin
     * @date 2012-9-12 下午3:55:36
     * @throws Exception
     */
    public MyConfiguration3() throws Exception {
        factory = new ActiveMQConnectionFactory(brokerURL);
        connection = factory.createConnection(username, password);
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(null);
    }

    /**
     *
     * @author geloin
     * @date 2012-9-12 下午3:42:55
     * @param args
     */
    public static void main(String[] args) throws Exception {
        String configUri = MyConfiguration3.class.getResource("/")
                + "activemq.xml";
        System.setProperty("activemq.base", System.getProperty("user.dir"));
        new FileSystemXmlApplicationContext(configUri);
        MyConfiguration3 cfg = new MyConfiguration3();
        for (int i = 0; i < 10; i++) {
            cfg.sendMessage(new String[] { "JAVA", "IONA" });
        }
    }
}

 请关注主方法main,你会发现第一、二行代码已在JMS&MQ系列之普通Java程序中加载配置中阐述,直接跳过,看new FileSystemXmlApplicationContext(configUri),这段代码的作用是设置当前程序运行过程中的上下文,此上下文直接作用下以后的代码。

        4. 在Spring配置文件中使用特定的Schema

        这一种方式与使用纯Spring配置文件类似,与其不同的是在Schema列表中加入了ActiveMQ的Schema,允许以非bean的形式配置ActiveMQ,代码如下所示:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    <span style="color:#ff0000;">xmlns:amq="http://activemq.apache.org/schema/core"</span>
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    <span style="color:#ff0000;">http://activemq.apache.org/schema/core
    http://activemq.apache.org/schema/core/activemq-core.xsd</span>
    ">  
    
    <!-- 其他Spring配置 -->
    
    <amq:broker brokerName="myBroker" dataDirectory="${activemq.base}/data">
        <amq:transportConnectors>
            <amq:transportConnector name="openwire" uri="tcp://localhost:61616" />
        </amq:transportConnectors>
        <amq:plugins>
            <amq:simpleAuthenticationPlugin>
                <amq:users>
                    <amq:authenticationUser username="admin" password="password" groups="admins,publishers,consumers" />
                    <amq:authenticationUser username="publisher" password="password" groups="publishers,consumers" />
                    <amq:authenticationUser username="consumer" password="password" groups="consumers" />
                    <amq:authenticationUser username="guest" password="password" groups="guests" />
                </amq:users>
            </amq:simpleAuthenticationPlugin>
        </amq:plugins>
    </amq:broker>
</beans>  


 该配置文件的大部分并无特别,注意红色字体部分,即Schema部分即可。

相关问答

更多