예제: 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;
}
}
결과적으로 모든 컴포넌트는 필요 시 메시지 리스너를 추가할 수 있으며, 이를 통해 컴포넌트가 각각의 클라이언트 등록자에 고유 스레드를 제공하는 것보다 더욱 확장 가능 방식으로 주제에 등록할 수 있습니다.