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

转载于:https://www.cnblogs.com/cq-jiang/p/7662477.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值