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

  • 相关阅读:
    Mono项目将继续推动基于Linux的开发
    VS.PHP 在Visual Studio 下的 PHP 开发 IDE 工具
    SQL Server 2008 的代码提示功能
    想做的时候没有机会了
    我的最爱
    双缓冲
    做个好男人!
    再见了,曾经喜欢过的歌手
    看看他是喜欢你还是爱你的~~~
    独家:未来五年程序员应当具备的十项技能
  • 原文地址:https://www.cnblogs.com/cq-jiang/p/7662477.html
Copyright © 2011-2022 走看看