I'm new using Jedis and I'm not sure if the configuration i used is correct.
I'm trying to use Jedis in a API server application as a cache used by my handlers. For this reason the environment is a multi-threaded one and i'm looking for the correct configuration for this scenario.
I found lot of example mentioning the "JedisPool" such as the following:
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(jedisPoolConfig, shards);
try (ShardedJedis jedis = pool.getResource()) {
jedis.set("a", "foo");
}
pool.close();
But in my case i need to use a UnifiedJadis object in order to have access to jsonSet and jsonGet methods, which "normal" Jedis does not provide.
This is what i've done.
This is the class i use to manage a UnifiedJedis object as singleton.
public class MyDB{
//singleton
public static UnifiedJedis jedisPooled;
//called at startup
public void init() throws DBConnectionException {
ConnectionPoolConfig poolConfig = RedisConfig.getRediConfiguration();
jedisPooled = new JedisPooled(poolConfig, dbUrl, dbPort);
}
}
At application startup i initialize the connection and inject the singleton everywhere is needed (e.g. in my handlers).
public class App{
public static void main(String[] args) throws Exception {
MyDB db = new MyDB();
db.init();
//...inject db where needed
}
}
Finally in my handlers I use the variable injected to use the jedisPooled methods jsonGet and jsonSet.
public class MyHandler{
// in the MyHandler constructor i receive the db variable
@Override
public void handle() throws Exception {
//...
db.jedisPooled.jsonSet(redisKey, Path.of("."), myPojo);
}
}
My question is: since there is no method "getResource" in the UnifiedJedis object, i can i get a connection from the pool and then release it after i send a command? Is it automatically done by the UnifiedJedis methods?
Is my solution correct?
Thank you
UnifiedJedis
could act differently depending on parameters.
In your object creation, I can see new JedisPooled(poolConfig, dbUrl, dbPort);
, which means you are actually creating and using JedisPooled
[1]. This narrows down the possible behaviors of UnifiedJedis and so I am providing answer to your questions only for JedisPooled.
In JedisPooled you don't have to get a connection from pool and release it after sending a command. It is automatically done JedisPooled methods.
Note [1]: JedisPooled is a sub-class of UnifiedJedis. That's why you could set a JedisPooled object in a UnifiedJedis variable.