zoukankan      html  css  js  c++  java
  • activeMq 使用方法

    一:activeMq介绍

        ActiveMQ是一种开源的,实现了JMS1.1规范的,面向消息(MOM)的中间件,为应用程序提供高效的、可扩展的、稳定的和安全的企业级消息通信,下载地址是:http://activemq.apache.org/download.html,下载后启动activemq.bat就可以,activemq默认端口号是8161,可以在confg/jetty.xml处修改。

    <bean id="jettyPort" class="org.apache.activemq.web.WebConsolePort" init-method="start">
                 <!-- the default port number for the web console -->
            <property name="host" value="0.0.0.0"/>
            <property name="port" value="8161"/>
        </bean>

    二:activeMq使用方法

    activeMq 使用java多线程经典的生产者和消费者来处理。

    1:首先创建生产者

    // 连接工厂 jms 用它创建连接
    connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,
                    ActiveMQConnection.DEFAULT_BROKER_URL);
    // jms 连接
    Connection connection = connectionFactory.createConnection();
    // 一个发送或接收消息的线程
    Session session= connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
    // 消息目的地,消息发送给谁
    Destination  destination = session.createQueue("threadMsg");
    // 得到生产者对像
    MessageProducer messageProducer=session.createProducer(destination);
    //设置消息对像
    TextMessage message = session.createTextMessage("ActiveMq 发送的消息" + index);
    //发送
    producer.send(message);

    消费发送后,可以在activeMq后台查询

     点击threadMsg可以查看未读消息列表,并且可以看未读消息的详细内容

    2:创建消息消费者

    // 连接工厂 jms 用它创建连接
    ConnectionFactory connectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
                    ActiveMQConnection.DEFAULT_PASSWORD,
                    ActiveMQConnection.DEFAULT_BROKER_URL);
    // jms 连接
     Connection connection=connectionFactory.createConnection();
    //创建操作连接
    Session session=connection.createSession(Boolean.TRUE,
                        Session.AUTO_ACKNOWLEDGE);
    // 获取操作连接 threadMsg 需要和生产者发送消息时的值对应
    Destination destination=session.createQueue("threadMsg");
    // 消息接收
    MessageConsumer =messageConsumersession.createConsumer(destination);
    while (true) {//1秒去读取一次消息
      // 设置接收者接收消息的时间,为了便于测试,这里谁定为100s
       TextMessage message = (TextMessage) messageConsumer.receive(100000);
       if (null != message) {
           log.info(threadName+"  收到消息  " + message.getText());
       } else {
    //                    break;
      }
       Thread.sleep(1000);
    }

        

       注意:由于这个项目没有使用maven,可能出现环境不一样,导致logg4j等包无法找到的情况。

        代码下载地址:github

  • 相关阅读:
    windows 核心编程 第2章 U n i c o d e
    在一个类内不可以定义自身类的对象,为什么定义自身类的静态对象又是正确的
    将JPG图片绘制在对话框背景上:(这段代码绝对可以执行)
    小技巧给CEdit设置字体
    惠普 升级两年保修
    DoModal返回1,对话框不能显示,今天碰到项目在用unicode编码,和多字符编码时候出现的
    MFC 绘图
    CString类所有成员函数详解
    mysql 一些问题
    错误:不能实例化抽象类
  • 原文地址:https://www.cnblogs.com/cq-jiang/p/7662477.html
Copyright © 2011-2022 走看看