java - How to initialize initial context in JMS -
i create message queue in standalone application using jms queue. not using kind of container tomcat , jboss. should arguments passed initial context object.? s standalone application..
note: if wishes give down vote question, please give reason in comment , give down vote. thanks!
initialcontext ctx = new initialcontext(?????); queue queue = (queue) ctx.lookup("queue/queue1"); queueconnectionfactory connfactory = (queueconnectionfactory) ctx.lookup("queue/connectionfactory"); queueconnection queueconn = connfactory.createqueueconnection(); queuesession queuesession = queueconn.createqueuesession(false,session.auto_acknowledge); queuesender queuesender = queuesession.createsender(queue); queuesender.setdeliverymode(deliverymode.non_persistent); textmessage message = queuesession.createtextmessage("hello"); queuesender.send(message); system.out.println("sent: " + message.gettext()); queueconn.close();
you can't resolve connectionfactory via jndi there no container provide it.
you have instantiate connectionfactory providing necessary (transport) parameters.
as don't retrieve java ee container behavior not covered related jsr , provider specific.
below example using hornetq :
// transport parameters final map< string, object > connectionparams = new hashmap< string, object >(); connectionparams.put(transportconstants.port_prop_name, port); connectionparams.put(transportconstants.host_prop_name, host); final transportconfiguration transportconfiguration = new transportconfiguration( nettyconnectorfactory.class.getname(), connectionparams); // should created once , reused whole app lifecycle connectionfactory = (connectionfactory) org.hornetq.api.jms.hornetqjmsclient .createconnectionfactorywithoutha(jmsfactorytype.queue_cf, transportconfiguration); final jmsqueue = hornetqjmsclient.createqueue(queuename) try { // connection thread safe connection connection = null; // session not session session = null; connection = connectionfactory.createconnection(user, password); connection.start(); /* following objects must propper thread (but should reused if possible) */ // create non transacted session (no xa support outside of java ee container) session = connection.createsession(false, session.auto_acknowledge); final messageproducer producer = session.createproducer(jmsqueue); final objectmessage objectmessage = session.createobjectmessage(); objectmessage.setobject(mymessageserializableobject); producer.send(objectmessage); } { // release resources try { if (session != null) { session.close(); } if (connection != null) { connection.close(); } } catch (final jmsexception e) { log.warn("an error occurs while releasing jms resources", e); } }
note connections, sessions , producers should reused (not created , released each use but not shared between threads) , ideally pooled.
see https://developer.jboss.org/wiki/shouldicachejmsconnectionsandjmssessions
Comments
Post a Comment