⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 topicsubscribeasynchronous.java

📁 基于JMS的消息,用包括界面代码,主要用初学都学习
💻 JAVA
字号:
package com.sjx.jms;

import java.util.*;
import javax.jms.*;
import javax.naming.*;
/**
 * @author sjx
 * openJms 非持久订阅异步接收演示
 * www.javayou.com
 */
public class TopicSubscribeAsynchronous implements MessageListener {
	private Context context = null;
	private TopicConnectionFactory factory = null;
    private TopicConnection topicConnection = null;
    private TopicSession topicSession = null;
    private Topic topic = null;
    private TopicSubscriber topicSubscriber = null;
    window w = null;

    public TopicSubscribeAsynchronous(window w) {
    	this.w = w;
        try {
            //取得JNDI上下文和连接
            context = GetJini.getContext();
            //取得Topic的连接工厂和连接
             factory =GetJini.getTopicConnectionFactory(context);               
            topicConnection = factory.createTopicConnection();
            //创建Topic的会话,用于接收信息
            topicSession = topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
            topic = (Topic) context.lookup("topic1");
            //创建Topic subscriber
            topicSubscriber = topicSession.createSubscriber(topic);
            //设置订阅监听
            topicSubscriber.setMessageListener(this);
            //启动信息接收          
            topicConnection.start();
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    /*public static void main(String[] args) {
       new TopicSubscribeAsynchronous().ReceiveMsg(); 
    }*/

    //收到订阅信息后自动调用此方法
    public void onMessage(Message message) {
        try {
            String messageText = null;
            if (message instanceof TextMessage)
                messageText = ((TextMessage) message).getText();
            w.topoicTextArea.append(messageText);
            System.out.println(messageText);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
    
    public void ReceiveMsg(){
    	System.out.println("非同步定购消息的接收:");
        try {
            TopicSubscribeAsynchronous listener =
                new TopicSubscribeAsynchronous(w);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public void close(){
    	GetJini.closeTopicSubscriber(topicSubscriber);
    	GetJini.closeTopicSession(topicSession);
    	GetJini.closeTopicConnection(topicConnection);
    	GetJini.closeContext(context);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -