activeMQ initial use

Recently the use of activeMQ do something, though I'm not directly bear the module, but since participate in this project, learn a little but still good. Built himself an environment as a whole is not more difficult, but the middle of some of the pit, come up with to say. (Not too deep, to welcome the god of correction)

First, the official website now related packages, http://activemq.apache.org/download.html rest is need your computer has a JAVA environment, (it mentioned directory in the bin directory, the default package directory activeMQ under), according to their own computer environment starts a 64-bit or 32-bit.The main feature is the persistence activeMQ delay delivery of messages and message support, so as to ensure the message is not lost, mainly used in this project even a feature, but you need to configure the delay in activeMQ, the default is not open, a little dimples .Open activemq.xml under conf, find a broker label, plus schedulerSupport within the bank angle bracket = "true", if you are running, you need to restart to take effect, at this time delay function to support other temporary no configuration.

Establish basic spring projects to maven project as an example, in the pom added:

<dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.12.0</version>
        </dependency>

Non-pom engineering package to add the relevant jar, applicationContext.xml configuration file:

<bean id="targetConnectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"/>
        <property name="useAsyncSend" value="true" />
    </bean>
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>
    <!--这个是队列目的地,点对点的-->
    <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>     <-! Spring provides the JMS tools, it can send a message, reception, etc. ->     </ the bean>         </ Arg-constructor>
            <value> MyQueue </ value>



    <bean the above mentioned id = "the JmsTemplate" class = "org.springframework.jms.core.JmsTemplate">
        <-! connectionFactory this ConnectionFactory object that corresponds to the definition of our Spring offer ->
        <Property name = "connectionFactory" ref = "The connectionFactory" />
        <Property name = "defaultDestination" REF = "queueDestination" />
        <Property name = "pubSubDomain is" value = "to false" />
        <Property name = "explicitQosEnabled" value = "to true" /> <! - deliveryMode, priority, timeToLive switch, to be effective, must be configured to true, defaults to false ->
        <Property name = "deliveryMode" value = "2" /> <- transmit mode DeliveryMode.NON_PERSISTENT = 1:! non persistent; DeliveryMode.PERSISTENT = 2: persistence ->
        <Property name = "SessionAcknowledgeMode" value = ". 1" />
        <-! message response manner
        Session.AUTO_ACKNOWLEDGE 1 automatically sign message
        Session.CLIENT_ACKNOWLEDGE 2 client calls a method to manually acknowledge receipt
        Session.DUPS_OK_ACKNOWLEDGE 3 not necessarily have to be signed, the message may be sent repeatedly
        ->
    </ the bean>
    <-! Message Listener ->
    <the bean ID = "consumerMessageListener" class = "com.wei.activemq.MsgListener" />
    <-! message listener container ->
    <the bean ID = "jmsContainer" class = "org.springframework.jms.listener.DefaultMessageListenerContainer">
        <Property name = "The connectionFactory" REF = "The connectionFactory" />
        <Property name = "Where do you want" REF = "queueDestination" />
        <Property name = "messageListener" REF = "consumerMessageListener" />
    </bean>


然后添加相应的支持

定义我们要发送的消息任务:

public class MsgTask implements Serializable {
    private long id;
    private String name;
    private long delayTime;
    //getter setter...
}

定义消息生产者

@Service
public class MsgProducer {
    @Autowired
    public JmsTemplate jmsTemplate;
    /**
     * send message
     */
    public void sendMessage(final MsgTask msgTask) {
        jmsTemplate.send(jmsTemplate.getDefaultDestination(), new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                ObjectMessage objectMessage = session.createObjectMessage(msgTask);
//                objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, msgTask.getDelayTime());打开注解,即可发送延时的消息
                objectMessage.setJMSExpiration(msgTask.getDelayTime());
                objectMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
                objectMessage.setJMSType("延迟发送的消息");
                Constants.map.put(msgTask.hashCode(),msgTask);
               
return objectMessage;
            }
        });
    }
}

定义消息接收者:

public class MsgListener implements MessageListener {


    public void onMessage(Message m) {
        System.out.println("[receive message]");


        ObjectMessage om = (ObjectMessage) m;
        try {
            MsgTask msgTask = (MsgTask) om.getObject();
            Constants.receivemap.put(msgTask.hashCode(), msgTask);
            System.out.println("延迟发送时间:" + msgTask.getDelayTime() / 1000);
            System.out.println("model:" + om.getJMSDeliveryMode());
            System.out.println("destination:" + om.getJMSDestination());
            System.out.println("type:" + om.getJMSType());
            System.out.println("messageId:" + om.getJMSMessageID());
            System.out.println("time:" + om.getJMSTimestamp());
            System.out.println("expiredTime:" + om.getJMSExpiration());
            System.out.println("priority:" + om.getJMSPriority());
            System.out.println("到达率:" + Constants.receivemap.size() * 1.0 / Constants.map.size());
//            System.out.println("long Propertity:" + om.getLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY));
            Random random = new Random();


            if (msgTask.getId() % 2 == 0) {
                om.acknowledge();
                System.out.println("耗时为:" + (System.currentTimeMillis() - Constants.beginTime) + " s");
                msgTask.setId(msgTask.getId() + 1);
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}


添加一些测试参数

public class Constants {
    public static ConcurrentHashMap<Integer, MsgTask> map = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<Integer, MsgTask> receivemap = new ConcurrentHashMap<>();


    public static int size = 1000;
    public static long beginTime = 1000;
}


好了,可以写测试一下

public class MainTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        MsgProducer msgProducer = (MsgProducer) applicationContext.getBean("msgProducer");
        Constants.beginTime = System.currentTimeMillis();
        for (int i = 0; i < 2; i++) {
            MsgTask msgTask = new MsgTask();
            msgTask.setName("test" + i);
            msgTask.setId(i);
            msgTask.setDelayTime((long) Math.random() * 1000);
            msgProducer.sendMessage(msgTask);
        }
    }
}


基本的功能已经可用,可以在大部分场合中使用。


发布了20 篇原创文章 · 获赞 0 · 访问量 1万+

Guess you like

Origin blog.csdn.net/u011248560/article/details/48413933