How to create common interface for jedis pool and cluster

Jedis is most popular Java client for using Redis. It has added support for cluster also. Unfortunately non-cluster and cluster class do not extend the same interface. Hence programming to interface is not problam and it does not make sense to have 2 similar classes, one for non-cluster Redis and one for cluster redis. But we can hack into the Jedis code via reflection and minimize this duplication of the code. Here is the code which you can use :

 private JedisClusterConnectionHandler jedisConnHandler;
 
 
    synchronized private void initCacheManager()
    {
 
        if (this.jedisPool == null && this.jedisConnHandler == null)
        {
 
            try
            {
 
                if (isCluster)
                {
                    if (jedisConnHandler == null)
                    {
                        Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
                        jedisClusterNode.add(new HostAndPort(host, port));
 
                        JedisCluster jedisCluster = new JedisCluster(jedisClusterNode, new 
 
JedisPoolConfig());
                        if (password != null && password.length() > 0)
                            jedisCluster.auth(password);
                        try
                        {
                            Field connectionHandlerField = 
 
JedisCluster.class.getDeclaredField("connectionHandler");
                            connectionHandlerField.setAccessible(true);
                            jedisConnHandler = (JedisClusterConnectionHandler) 
 
connectionHandlerField.get(jedisCluster);
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
                else if (this.jedisPool == null)
                {
 
                    this.jedisPool = new JedisPool(new JedisPoolConfig(), host, port, 
 
Protocol.DEFAULT_TIMEOUT,
                            password);
 
                }
 
            }
            catch (Exception e)
            {
 
            }
 
        }
 
    }
 
    public Jedis getClient() {
        this.initCacheManager();
        if(this.jedisConnHandler != null)
            return ((JedisSlotBasedConnectionHandler)jedisConnHandler).getConnection();
        else
            return this.jedisPool.getResource();
    }

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *