Standalone java program reading from ActiveMQ queue won't auto reconnect after broker is down -
the activemq setting, server, properties in jndi.properties file.
example:
java.naming.provider.url=failover:(tcp://localhost:61616?keepalive=true) java.naming.factory.initial = org.apache.activemq.jndi.activemqinitialcontextfactory queue.myqueue = testupdate
while program this:
public class mqreader{ public final string jndi_factory = "connectionfactory"; public final string queue = "myqueue"; private queueconnectionfactory queueconnectionfactory; private queueconnection queueconnection; private queuesession queuesession; private queuereceiver queuereceiver; private queue queue; public static void main(string[] args) throws exception { // create new intial context, loads jndi.properties file javax.naming.context ctx = new javax.naming.initialcontext(); mqreader reader = new mqreader(); reader.init(ctx); try { reader.wait(); } catch (interruptedexception ie) { ie.printstacktrace(); } reader.close(); } public void init(context context) throws namingexception, jmsexception { queueconnectionfactory = (queueconnectionfactory) context.lookup(jndi_factory); queueconnection = queueconnectionfactory.createqueueconnection(); queuesession = queueconnection.createqueuesession(false, session.auto_acknowledge); queue = (queue) context.lookup(queue); queuereceiver = queuesession.createreceiver(queue); queuereceiver.setmessagelistener( message ->{ try { if(message != null) { //do stuff print message testing. } } catch (jmsexception jmse) { system.err.println("an exception occurred: " + jmse.getmessage()); } } ); queueconnection.start(); } public void close() throws jmsexception { queuereceiver.close(); queuesession.close(); queueconnection.close(); } }
i thought failover item in jndi should take care of reconnecting not. ran broker , ran program , worked once stopped broker, consumer program exit exit code of 1. "process finished exit code 1"
i not sure did wrong here. have added print out statement lot of places , found out exited @ reader.wait() without triggering exception.
i figure out. since main thread exited after started listener thread , listener thread running(non-daemon thread) perfectly, keeps jvm running. once listener loses connection, program exits because there no non-daemon thread running left. failover protocol code running daemon thread therefore jvm exit program without letting failover protocol code reconnect.
so did add piece of code, not best way works trying do.
scanner in = new scanner(system.in); while(true){ system.out.println("please enter \"stop\" stop program."); string command = in.nextline(); if("stop".equalsignorecase(command)){ reader.close(); system.exit(0); } }
instead of
try { reader.wait(); } catch (interruptedexception ie) { ie.printstacktrace(); } reader.close();
the wait method crashing , not keeping main thread alive. way keep program running without sending messages queue stop it.