Last active
May 20, 2021 13:27
-
-
Save kimathie/ffc344c6d59de2b5782f570a22f74d10 to your computer and use it in GitHub Desktop.
A simple ActiveMQ Artemis Core API Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| try (ServerLocator locator = ActiveMQClient.createServerLocator("tcp://localhost:61617"); | |
| ClientSessionFactory factory = locator.createSessionFactory(); | |
| ClientSession session = factory.createSession(true, true, 0)) { | |
| String queueName = "router::hornetq"; | |
| /** | |
| * In reference to the question | |
| * https://stackoverflow.com/questions/67606298/how-to-configure-an-activemq-artemis-queue-not-be-created-again | |
| * Just catch the Exception and handle it quietly and proceed executing the rest of the code. | |
| * Hopefully this wont be necessary in future versions. | |
| */ | |
| try { | |
| session.createQueue(new QueueConfiguration(queueName) | |
| .setAutoCreateAddress(Boolean.TRUE) | |
| .setDurable(Boolean.TRUE) | |
| .setRoutingType(RoutingType.ANYCAST)); | |
| } catch (ActiveMQQueueExistsException e) { | |
| System.out.println("Queue '" + queueName + "' exists."); | |
| } catch (Exception e) { | |
| throw new RuntimeException(e); | |
| } | |
| try (ClientProducer producer = session.createProducer(queueName); | |
| ClientConsumer consumer = session.createConsumer(queueName)) { | |
| session.start(); | |
| Thread sender = new Thread(new Sender(session, producer), "Sender"); | |
| Thread receiver = new Thread(new Receiver(consumer), "Receiver"); | |
| sender.setDaemon(true); | |
| receiver.setDaemon(true); | |
| sender.start(); | |
| receiver.start(); | |
| receiver.join(); | |
| } | |
| } catch (Error | Exception e) { | |
| throw new RuntimeException(e); | |
| } |
Author
Thanks Justin, this is really good feedback,
- I was actually intending to check the code to see if it uses autoclosable but this answers it all.
- As for the closing of resources, I forgot to add the join methods. I have corrected that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For what it's worth, all the resources you're using (i.e.
ServerLocator,ClientSessionFactory,ClientProducer, andClientConsumer) implementjava.lang.AutoCloseableso you can use try-with-resources instead of using afinallyblock with anullcheck. This would make your code simpler and more readable, e.g.:Also, I think that you will find your
senderandreceiverthreads won't work since as soon as you callstarton them you close their resources (i.e.session,producer, &consumer).