Java Gateway - How to store object in memory between calls?
Trying to connect Ensemble to RabbitMQ following this article I'm using Java Gateway and encountered the following problem - in all my calls I need to pass connection object, which is always the same but it takes a long time to create. Here's java code:
package com.myorgname.rabbitmq; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import com.rabbitmq.client.QueueingConsumer; public class Wrapper { public void sendMsg(String hostName, String queueName, byte[] msg) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); channel.basicPublish("", queueName, null, msg); channel.close(); connection.close(); } public int readMsg(String hostName, String queueName, byte[] msg) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); int len = delivery.getBody().length; System.arraycopy(delivery.getBody(),0,msg,0,len); channel.close(); connection.close(); return len; } }
As you see to publish or to get a message a new connection is made each time.
I'm interested in a way to create a connection object only once and use it to send several messages. Is it possible?
Turns out Java Gateway can instantiate objects and call their methods. Here's a rewrite of the above code, but all connecting is done in constructor: