Skip to content

Instantly share code, notes, and snippets.

@linusfoldemo
Created December 17, 2015 11:57
Show Gist options
  • Save linusfoldemo/b3c6c346c42733521811 to your computer and use it in GitHub Desktop.
Save linusfoldemo/b3c6c346c42733521811 to your computer and use it in GitHub Desktop.
class EmbeddedMQBroker {
public static final String ACTIVEMQ_URL = "vm://localhost";
private static Logger logger = LoggerFactory.getLogger(EmbeddedMQBroker.class);
Connection connection;
BrokerService broker;
private EmbeddedMQBroker(final String url) {
//Keep alive mq connection to stop ActiveMq from shutting down automatically.
broker = new BrokerService();
try {
broker.addConnector(url);
broker.setPersistent(false);
broker.start();
broker.waitUntilStarted();
connection = new ActiveMQConnectionFactory(ACTIVEMQ_URL).createConnection();
} catch (Exception e) {
throw new RuntimeException("Unable to setup broker", e);
}
}
public static EmbeddedMQBroker start() {
return start(ACTIVEMQ_URL);
}
public static EmbeddedMQBroker start(final String url) {
logger.info(">>>>>>>>>> EmbeddedMQBroker starting <<<<<<<<<<");
return new EmbeddedMQBroker(url);
}
public void stop() {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
throw new RuntimeException("Unable to close connection", e);
}
}
try {
broker.stop();
} catch (Exception e) {
throw new RuntimeException("Unable to stop broker", e);
}
broker.waitUntilStopped();
broker = null;
logger.info(">>>>>>>>>> EmbeddedMQBroker stopped <<<<<<<<<<");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment