Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transition from JedisPool to JedisCluster

My Application uses ElastiCache on AWS for caching purposes. Our current set up uses a basic Redis Cluster with no sharding or failover. We need to now move to a Clustered Redis Elastic Cache with sharding, failover etc enabled. Creating a new cluster on AWS was the easy bit, but we are a bit lost on how to modify our java code to reads and write from the cluster.

Current Implementation - Initialize a JedisPool.

JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(100);
jedisPoolConfig.setMaxIdle(10);
jedisPoolConfig.setMaxWaitMillis(50);
jedisPoolConfig.setTestOnBorrow(true);

String host = "mycache.db8e1v.0001.usw2.cache.amazonaws.com";
int port = 6379;
int timeout = 50;

JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout)

A Jedis object is borrowed from the pool everytime we need to perform an operation

Jedis jedis = JedisPool.getResource();

The new implementation would be

JedisPoolConfig jedisPoolConfig = ...
HostAndPort hostAndPort = new HostAndPort(host, port);
jedisCluster = new JedisCluster(Collections.singleton(hostAndPort), jedisPoolConfig);

Question: The documentation says JedisCluster is to be used in place of Jedis (not JedisPool). Does this mean I need to create and destroy a JedisCluster object in each thread. Or can I re-use the same object and it will handle the thread safety? When do I exactly close the JedisCluster then? At the end of the application?

like image 622
Pranav Kapoor Avatar asked Mar 05 '23 21:03

Pranav Kapoor


1 Answers

The JedisCluster holds internal JedisPools for each node in the cluster.

Does this mean I need to create and destroy a JedisCluster object in each thread. Or can I re-use the same object and it will handle the thread safety?

You can reuse the same object.

When do I exactly close the JedisCluster then? At the end of the application?

Yes.

like image 159
Guy Korland Avatar answered Mar 15 '23 14:03

Guy Korland