首页>代码>spring整合apache activemq实现消息发送的三种方式代码配置实例>/zuidaima_activemq/src/com/zuidamai/jms/JmsMessageReceiver.java
package com.zuidamai.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

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

/**
 * JMS消息接收者
 * @author kaka
 *
 */
public class JmsMessageReceiver {
	//tcp地址
    public static final String BROKER_URL = "tcp://localhost:61616";
    public static final String DESTINATION = "com.zuidaima.jms";
    
    public static void run() throws Exception {
        
        Connection connection = null;
        Session session = null;
        try {
            // 创建链接工厂
            ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
            // 通过工厂创建一个连接
            connection = factory.createConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Destination destination = session.createQueue(DESTINATION);
            // 创建消息制作者
            MessageConsumer consumer = session.createConsumer(destination);
            
            while (true) {
                // 接收数据的时间(等待)1s
                Message message = consumer.receive(1000 * 1000);
                
                TextMessage text = (TextMessage) message;
                if (text != null) {
                    System.out.println("kaka接收:" + text.getText());
                } else {
                    break;
                }
            }
            
            // 提交会话
            session.commit();
            
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        JmsMessageReceiver.run();
    }
}
最近下载更多
1358849392  LV21 4月12日
wei331  LV1 2020年12月15日
tiansitong  LV14 2020年8月19日
simple丶余心  LV21 2020年7月27日
weixiaoderen123  LV2 2020年3月8日
javaPrimary  LV11 2020年1月13日
smalltarget  LV6 2019年11月13日
垃圾平台已注销  LV7 2019年9月3日
luo110012  LV9 2019年8月25日
HCh1018  LV3 2019年8月21日
最近浏览更多
1358849392  LV21 4月12日
renyuan  LV9 2023年4月27日
npc也有忧伤  LV3 2022年3月20日
gaohd123456789  LV8 2022年1月21日
sizeking  LV8 2021年4月12日
xb1406112453  LV5 2021年3月12日
xsxtxbb  LV8 2021年3月9日
hs123456  LV1 2021年1月7日
wei331  LV1 2020年12月14日
wangdengzhe  LV7 2020年11月30日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友