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);
}
}
The best way to do this is to use a messaging system. Create a singleton class like
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.