On 12 Sep 2009, at 23:53, czy11421 wrote:
I am running ActiveMQ 5, in the admin web page, I could see
"STOCKS.SUNW" in Topics, and this topic is sending out message, then
how could I subscribe this topic and get the published message ?
I have tried this coding, but I get the error as bottom. Where is
the bug ?
Thanks.
//////////////////////// code /////////////////
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.setProperty(Context.PROVIDER_URL, "tcp://localhost:
61616");
javax.naming.Context ctx = new InitialContext(props);
// lookup the connection factory
javax.jms.TopicConnectionFactory factory =
(javax.jms.TopicConnectionFactory) ctx.lookup("ConnectionFactory");
// create a new TopicConnection for pub/sub messaging
javax.jms.TopicConnection conn =
factory.createTopicConnection(); //getTopicConnection();
System.out.println(conn); // output this :
ActiveMQConnection {id=ID:xxxx-
PC
-51013
-1252720683131-0:0,clientId=null,started=false} //
lookup an existing topic
javax.jms.Topic mytopic = (javax.jms.Topic)
ctx.lookup("STOCKS.SUNW"); //error is from here
// create a new TopicSession for the client
javax.jms.TopicSession session = conn.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
// create a new subscriber to receive messages
javax.jms.TopicSubscriber subscriber =
session.createSubscriber(mytopic);
System.out.println(subscriber.receive());
////////////////////////// Exception ///////////////////
Exception in thread "main" javax.naming.NameNotFoundException:
STOCKS.SUNW
at
org.apache.activemq.jndi.ReadOnlyContext.lookup(ReadOnlyContext.java:
225)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.Test.main(Test.java:31)
The ActiveMQ JNDI Context is local - in VM only. It doesn't
communicate with the ActiveMQ Broker - but it does follow some
conventions to allow easy "standard" ways of finding ActiveMQ
administered objects (Connections, Topics, Queues etc). For example -
it will create a ConnectionFactory because you've looked up in the
Context for a "ConnectionFactory". It will also create a Queue or a
Topic for you - if the Object you are looking up has a Queue or a
Topic if the name you are looking up starts with "queue." or "topic.".
Which isn't going to be of any use to you - as you want to subscribe
to a Topic "STOCKS.SUNW".
However, all destinations by default are dynamic - so you just have to
change:
javax.jms.Topic mytopic = (javax.jms.Topic)
ctx.lookup("STOCKS.SUNW"); //error is from here
for
javax.jms.Topic mytopic = session.createTopic("STOCKS.SUNW");
Something else you need to do - is call connection.start() - to start
receiving messages.
cheers,
Rob
Rob Davies
I work here: http://fusesource.com
My Blog: http://rajdavies.blogspot.com/
I'm writing this: http://www.manning.com/snyder/