示例:创建 Callable 和 Runnable 任务
可以创建动态预订主题的任务,并且任何组件都可以按需添加消息侦听器。
以下是动态预订主题的任务的示例:
class SampleTask implements Callable<Object>
{
Set<MessageListener> listeners =
Collections.newSetFromMap(new ConcurrentHashMap<MessageListener, Boolean>);
Topic targetTopic;
TopicConnectionFactory tcf;
public SampleTask(TopicConnectionFactory tcf, Topic targetTopic)
{
this.targetTopic = targetTopic;
this.tcf = tcf;
}
public void addMessageListener(MessageListener listener)
{
listeners.add(listener);
}
public Object call() throws JMSException
{
// Set up JMS.
TopicConnection tc = tcf.createConnection();
try
{
TopicSession sess = tc.createSession(false, Session.AUTOACK);
tc.start();
while( !Thread.currentThread().isInterrupted() )
{
// Block for up to 5 seconds.
Message msg = sess.receiveMessage(5000);
if(msg != null)
{
for (MessageListener listener : listeners)
// Fire an event when we get a message.
listener.onMessage(msg);
}
}
tc.close();
}
finally
{
if (tc != null) tc.close();
}
return null;
}
}
结果,任何组件都可按需添加消息侦听器,这使组件能够通过比仅为每个客户机订户给予其自己的线程更灵活的方法来预订主题。