activemq: jms api实现queue和topic生产者、消费者demo及spring api 实现queue生产者、消费者

activemq: jms api实现queue和topic生产者、消费者demo及spring api 实现queue生产者、消费者

一、jms api实现queue和topic生产者、消费者demo

1、queue

1.1、生产者
package com.hcb.mq.jmsapi.queue;

import java.util.Date;

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

import org.apache.activemq.ActiveMQConnectionFactory;

public class QueueProducer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                "tcp://localhost:61616");

        Connection connection = connectionFactory.createConnection();
        connection.start();

        // 参数transacted设置为true, 开启事务
        Session session = connection.createSession(Boolean.TRUE,
                Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("jms-api-queue");

        MessageProducer producer = session.createProducer(destination);
        for (int i = 0; i < 3; i++) {
            MapMessage message = session.createMapMessage();
            message.setLong("count", new Date().getTime());
            Thread.sleep(1000);
            // 通过消息生产者发出消息
            producer.send(message);
        }
        session.commit();
        session.close();
        connection.close();
    }
}
1.2、消费者
package com.hcb.mq.jmsapi.queue;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class QueueCustomer {
    private static Logger LOG = LoggerFactory.getLogger(QueueCustomer.class);

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
                "tcp://localhost:61616");

        Connection connection = connectionFactory.createConnection();
        connection.start();

        final Session session = connection.createSession(Boolean.TRUE,
                Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("jms-api-queue");

        MessageConsumer consumer = session.createConsumer(destination);
        // listener 方式
        consumer.setMessageListener(new MessageListener() {

            public void onMessage(Message msg) {
                MapMessage message = (MapMessage) msg;
                try {
                    LOG.info("收到消息:" + new Date(message.getLong("count")));
                    session.commit();
                } catch (JMSException e) {
                    e.printStackTrace();
                }

            }

        });

        // 消费者线程不结束,监听一分钟
        Thread.sleep(60 * 1000);

        session.close();
        connection.close();
    }
}

2、topic

2.1、生产者
package com.hcb.mq.jmsapi.topic;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TopicMsgProducer {

    private static Logger LOG = LoggerFactory.getLogger(TopicMsgProducer.class);

    public void send() {
        // 创建连接工厂
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
                "tcp://localhost:61616");

        Connection conn = null;
        try {
            // 创建连接
            conn = factory.createConnection();
            conn.start();
            // 创建会话
            // 参数transacted设置为false, 关闭事务
            Session session = conn.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);

            // 创建地点
            Topic topic = session.createTopic("jms-topic");

            // 创建生产者
            MessageProducer producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            producer.setTimeToLive(Message.DEFAULT_TIME_TO_LIVE);
            for (int i = 0; i < 5; i++) {
                TextMessage tmsg = session.createTextMessage();
                tmsg.setText("早上你好   " + i);
                producer.send(tmsg);
                LOG.info("发送的消息:" + tmsg.getText());
            }
            session.close();
            conn.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static void main(String[] args) throws Exception {
        new TopicMsgProducer().send();
    }

}
2.2、订阅者
package com.hcb.mq.jmsapi.topic;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TopicMsgSubscriber {

    private static Logger LOG = LoggerFactory
            .getLogger(TopicMsgSubscriber.class);

    private String name;

    TopicMsgSubscriber(String name) {
        this.name = name;
    }

    public void receive() throws InterruptedException {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
                "tcp://localhost:61616");
        Connection conn = null;
        try {
            conn = factory.createConnection();
            conn.setClientID(this.name);
            conn.start();

            // 参数transacted设置为false, 关闭事务
            final Session session = conn.createSession(false,
                    Session.AUTO_ACKNOWLEDGE);

            // 订阅发布模式的 Topic对象 不是Destination
            Topic topic = session.createTopic("jms-topic");

            TopicSubscriber subsriber = session.createDurableSubscriber(topic,
                    this.name);

            subsriber.setMessageListener(new MessageListener() {
                public void onMessage(Message msg) {
                    TextMessage message = (TextMessage) msg;
                    try {
                        LOG.info(name + " received message: "
                                + message.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

            // 消费者线程不结束,监听一分钟
            Thread.sleep(60 * 1000);

            session.close();
            conn.close();
            LOG.info(this.name + " receive over");
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        // 设置两个订阅者
        // 订阅者1
        new Thread() {
            public void run() {
                try {
                    new TopicMsgSubscriber("subscriber1").receive();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        // 订阅者1
        new Thread() {
            public void run() {
                try {
                    new TopicMsgSubscriber("subscriber2").receive();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}

二、spring api 实现queue生产者、消费者

1、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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/task 
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
    ">

    <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>failover://(tcp://127.0.0.1:61616)?randomize=false&amp;jms.prefetchPolicy.queuePrefetch=1</value>
                </property>
            </bean>
        </property>
        <property name="maxConnections" value="100"></property>
    </bean>

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory">
            <ref local="jmsFactory" />
        </property>
    </bean>

    <bean id="springApiQueue" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="spring-api-queue" />
    </bean>

    <bean id="springApiQueueMessageListener" class="com.hcb.mq.listener.SpringApiQueueMessageListener"></bean>

    <bean id="listenerContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="concurrentConsumers" value="2" />
        <property name="connectionFactory" ref="jmsFactory" />
        <property name="destination" ref="springApiQueue" />
        <property name="messageListener" ref="springApiQueueMessageListener" />
        <property name="pubSubNoLocal" value="false"></property>
    </bean>

</beans> 

2、代码

2.1、生产者
package com.hcb.mq.springapi;

import java.io.IOException;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.hcb.mc.vo.User;
import com.hcb.util.JsonUtil;

public class Producer {

    public static void main(String[] args) throws JsonGenerationException,
            JsonMappingException, IOException, InterruptedException {

        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "mq.xml");

        JmsTemplate template = (JmsTemplate) applicationContext
                .getBean("jmsTemplate");

        Destination subjectDestination = (Destination) applicationContext
                .getBean("springApiQueue");

        for (int i = 0; i < 5; i++) {
            User tmpUser = new User();
            tmpUser.setName("张三" + i);
            final String tmpMessageText = JsonUtil.toJson(tmpUser);
            template.send(subjectDestination, new MessageCreator() {
                public Message createMessage(Session session)
                        throws JMSException {
                    Message message = session.createTextMessage(tmpMessageText);
                    return message;
                }
            });
        }

        // spring容器不立即结束,让容器内的监听器存活10s
        Thread.sleep(10 * 1000);
        applicationContext.close();

        System.out.println("Producer over");
    }
}
2.2、消费者
package com.hcb.mq.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpringApiQueueMessageListener implements MessageListener {

    static Logger LOG = LoggerFactory
            .getLogger(SpringApiQueueMessageListener.class);

    @Override
    public void onMessage(Message message) {
        String textMsg = null;
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            try {
                textMsg = textMessage.getText();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
        LOG.info("SpringApiQueueMessageListener, textMsg: " + textMsg);

        try {
            // 模拟每个消息的处理时间为1s
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值