Using static redis connections in multithreaded env in Java

53 Views Asked by At

I want to improve the performance of my Redis read/writes, by reusing the connection object. So, I am making it static in the class, and my get() and set() functions are using this static connection.

In a multithreaded environment, can this cause data corruption? As in, since the connection is static, can 2 threads access it at the same time and data meant for one, be sent to the other?

I am using Lettuce lib in Java.

class RedisServiceLocator {
  static StatefulRedisConnection<String, String> redisConn = null;

  // constructor
  public RedisServiceLocator() {
    // create client and get connection if null
    if(RedisServiceLocator.redisConn == null) {
      RedisClient redisClient = RedisClient.create(redisURL);
      RedisServiceLocator.redisConn = redisClient.connect()
    }
  }

  // set
  public void set(String key, String val){
    RedisServiceLocator.redisConn.sync().set(key, val);
  }

  // get
  public String get(String key){
    redisConn.sync().get(key);
  }
}
1

There are 1 best solutions below

0
ControlAltDel On

The best way to do this is to use a messaging system. Create a singleton class like

public class RedisMessenger {
  private Queue<Message> messages;
  public long queueMessage(Message m); //return a response ticket number
  public void registerListener(RedisResponseListener l, RedisMessageType t);
}

Then use a thread to send queries and notify appropriate listeners.

You can use the RedisMessageType parameter to allow listening for response for specific messages (via message ticket number) or by message catagories.