美文网首页待整理菜鸟要飞
ActiveMQ学习(三)Topic订阅模式

ActiveMQ学习(三)Topic订阅模式

作者: 万总有点菜 | 来源:发表于2017-05-28 17:13 被阅读144次

    说明

    基于ActiveMQ学习(二),学习ActiveMQ的另一种消息模式Topic订阅模式,同时将普通的文本消息改为对象消息。

    代码

    demo代码

    订阅模式

    文件目录
    • 编写被收发的对象 UserModel
    package com.sima.topics;
    import java.io.Serializable;
    /**
     * Created by Maple on 2017-05-28.
     */
    public class UserModel implements Serializable {
    
        private String name;
        private int age;
    
        public UserModel() {
        }
        public UserModel(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "UserModel{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

    注:被收发的对象类需要实现Serializable

    • 编写消息生产者
    package com.sima.topics;
    import org.apache.activemq.ActiveMQConnection;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.activemq.command.ActiveMQObjectMessage;
    import javax.jms.*;
    /**
     * Created by Maple on 2017-05-28.
     */
    public class JMSProducer {
        private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名
        private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码
        private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址
    //  private static final String BROKEURL= "tcp://localhost:8161"; // 默认的连接地址
        private static final int SENDNUM = 3; // 发送的消息数量
        public static void  main(String[] args){
    //        ConnectionFactory connectionFactory; // 连接工厂
            ActiveMQConnectionFactory connectionFactory; // 连接工厂
            Connection connection = null; // 连接
            Session session; // 会话 接受或者发送消息的线程
            Destination destination; // 消息的目的地
            MessageProducer messageProducer; // 消息生产者
            connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME,
                    JMSProducer.PASSWORD, JMSProducer.BROKEURL);
            connectionFactory.setTrustAllPackages(true);
            try {
                connection = connectionFactory.createConnection(); // 通过连接工厂获取连接
                connection.start(); // 启动连接
                session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建Session
    //            destination = session.createQueue("TestQueueFirst"); // 创建消息队列
                destination = session.createTopic("TestTopicFirst"); // 创建消息队列
                messageProducer = session.createProducer(destination); // 创建消息生产者
                //设置不持久化
    //            messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                sendMessage(session, messageProducer); // 发送消息
                session.commit();
            } catch (JMSException e) {
                e.printStackTrace();
            }finally {
                if(connection!=null){
                    try {
                        connection.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        private static void sendMessage(Session session, MessageProducer messageProducer) {
            for(int i=0;i< JMSProducer.SENDNUM;i++){
                TextMessage message= null;
                try {
    //                message = session.createTextMessage("ActiveMQ 发送的消息-"+i);
    //                System.out.println("发送消息:" + "ActiveMQ 发送的消息-" + i);
    //                messageProducer.send(message);
    
                    UserModel userModel = new UserModel("maple", 28);
                    ObjectMessage objectMessage = session.createObjectMessage(userModel);
                    objectMessage.setObject(userModel);
    //                ActiveMQObjectMessage
                    System.out.println("发送消息:" + "ActiveMQ 发送的消息-" + userModel.toString());
                    messageProducer.send(objectMessage);
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    • 消息消费者
    package com.sima.topics;
    import com.sima.queues.MyListener;
    import org.apache.activemq.ActiveMQConnection;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import javax.jms.*;
    /**
     * Created by Maple on 2017-05-28.
     */
    public class JMSConsumerByListener1 {
        private static final String USERNAME = ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名
        private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码
        private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址
    //    private static final String BROKEURL= "tcp://localhost:8161"; // 默认的连接地址
        public static void main(String[] args){
    //        ConnectionFactory connectionFactory; // 连接工厂
            ActiveMQConnectionFactory connectionFactory; // 连接工厂
            Connection connection = null; // 连接
            Session session; // 会话 接受或者发送消息的线程
            Destination destination; // 消息的目的地
            MessageConsumer messageConsumer; // 消息的消费者
            // 实例化连接工厂
            connectionFactory=new ActiveMQConnectionFactory(JMSConsumerByListener1.USERNAME, JMSConsumerByListener1.PASSWORD, JMSConsumerByListener1.BROKEURL);
            connectionFactory.setTrustAllPackages(true);
            try {
                connection=connectionFactory.createConnection();  // 通过连接工厂获取连接
                connection.start(); // 启动连接
                session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); // 创建Session
    //            destination=session.createQueue("TestQueueFirst");  // 创建连接的消息队列
                destination=session.createTopic("TestTopicFirst");  // 创建连接的消息队列
                messageConsumer=session.createConsumer(destination); // 创建消息消费者
    //            messageConsumer.setMessageListener(new MyListener());// 注册消息监听
                messageConsumer.setMessageListener(new MyObjectListener());// 注册消息监听
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 监听类
    package com.sima.topics;
    import javax.jms.*;
    /**
     * Created by Maple on 2017-05-28.
     */
    public class MyObjectListener implements MessageListener {
        public void onMessage(Message message) {
            try {
                UserModel u = (UserModel) ((ObjectMessage) message).getObject();
                System.out.println("通过MyListener收到的ObjectMessage消息:"+ u.toString());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
    
    订阅者 注册成消费者
    • 运行消息生产者,此时消费者会收到通知并进行消费
    消息订阅消费
    • 当有多个订阅者的情况下,每个订阅者都将收到相同数量的消息

    白名单

    ActiveMQ自5.12.2版本之后,强制用户指定一份可信任的packages白名单,以对付ObjectMessage存在的安全漏洞。具体内容可参考:http://activemq.apache.org/objectmessage.html
    会遇到如下问题:

    javax.jms.JMSException: Failed to build body from content. Serializable class not available to broker. Reason: java.lang.ClassNotFoundException: Forbidden class com.sima.topics.UserModel! 
    This class is not trusted to be serialized as ObjectMessage payload. 
    Please take a look at http://activemq.apache.org/objectmessage.html for more information on how to configure trusted classes.
    

    官方提供的白名单配置方法如下:


    白名单配置

    相关文章

      网友评论

        本文标题:ActiveMQ学习(三)Topic订阅模式

        本文链接:https://www.haomeiwen.com/subject/hijhfxtx.html