zoukankan      html  css  js  c++  java
  • 消息消费者(监听)示例

    import javax.jms.Connection;
    import javax.jms.ConnectionFactory;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.MessageConsumer;
    import javax.jms.Session;

    import org.apache.activemq.ActiveMQConnection;
    import org.apache.activemq.ActiveMQConnectionFactory;

    /**
     * 消息消费者
     * @author Administrator
     *
     */
    public class JMSConsumer2 {

        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; // 默认的连接地址
        
        public static void main(String[] args) {
            ConnectionFactory connectionFactory; // 连接工厂
            Connection connection = null; // 连接
            Session session; // 会话 接受或者发送消息的线程
            Destination destination; // 消息的目的地
            MessageConsumer messageConsumer; // 消息的消费者
            
            // 实例化连接工厂
            connectionFactory=new ActiveMQConnectionFactory(JMSConsumer2.USERNAME, JMSConsumer2.PASSWORD, JMSConsumer2.BROKEURL);
                    
            try {
                connection=connectionFactory.createConnection();  // 通过连接工厂获取连接
                connection.start(); // 启动连接
                session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE); // 创建Session
                //订阅时destination=session.createTopic("FirstTopic1");
                destination=session.createQueue("FirstQueue1");  // 创建连接的消息队列
                messageConsumer=session.createConsumer(destination); // 创建消息消费者
                messageConsumer.setMessageListener(new Listener()); // 注册消息监听
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



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

    /**
     * 消息监听
     * @author Administrator
     *
     */
    public class Listener implements MessageListener{

        @Override
        public void onMessage(Message message) {
            // TODO Auto-generated method stub
            try {
                System.out.println("收到的消息:"+((TextMessage)message).getText());
            } catch (JMSException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

  • 相关阅读:
    mybatis配置
    mybatis 多表查询 与配置
    Maven中资源导出问题解决方案--pom.xml配置
    【macOS】Mac App Store 无法 更新/下载
    【macOS】删除 Mac 上的 Office 许可证文件
    【前端】JavaScript学习笔记(一)——快速入门
    【前端】CSS3学习笔记(五)——定位
    【前端】CSS3学习笔记(四)——浮动
    【前端】CSS3学习笔记(三)——盒子模型
    【macOS】清除Finder 「前往」(⌘
  • 原文地址:https://www.cnblogs.com/cyf18/p/14290403.html
Copyright © 2011-2022 走看看