skip to Main Content

I have a service that uses jedis to read from redis. Obviously I don’t intend to establish a new connection with every GET request but curious on the guard rails i need in case read fails because of connection failures ? To clean up idle connections i have configured timeout on server side. Reference link

Can some jedis/redis experts here recommend me the ideal way keeping latency in mind. I can think of the following, if there is any better way, please suggest

  1. If read fails due to connection failure, try to establish connection
    again and then read again.
  2. Before every read, verify
    jedis.isBroken() or jedis.isConnected(). Should i verify both or either would suffice ?
  3. Do jedis.ping() and on success only read , else try re-establish the connection.

2

Answers


  1. nodejs with use ioredis package

    function connect() {
    
      let isConnected = false
    
      redis = new Redis(process.env.REDIS_URL)
    
      redis.on('connect', async (err) => {
        console.log('Redis Connected')
        isConnected = true
      })
      
      redis.on('error', async (err) => {
        console.log(err)
        isConnected = false
      })
    }
    

    You can know like this

    Login or Signup to reply.
  2. Use JedisPoola or JedisPooledb and forget the hassles of connection management. This will cover your (1) and (2).

    For (3), you can use GenericObjectPoolConfig#setTestOnBorrow(true). Both JedisPoolc and JedisPooledd accepts a GenericObjectPoolConfig in some of their constructors.

    [a] JedisPool is available since very long time ago.
    [b] JedisPooled is available since version 4.0.0.
    [c] It is GenericObjectPoolConfig<Jedis> for JedisPool.
    [d] It is GenericObjectPoolConfig<Connection> for JedisPooled.


    An example with JedisPooled:

      GenericObjectPoolConfig<Connection> poolConfig = new GenericObjectPoolConfig<>();
      poolConfig.setTestOnBorrow(true);
    
      HostAndPort hostAndPort = new HostAndPort(HOST, PORT);   // server host and port
    
      JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
          .timeoutMillis(TIMEOUT)           // set your preferred timeout
          .user(USERNAME)                   // server username, if any
          .password(PASSWORD)               // server password (for that user)
          .build();
    
      JedisPooled jedis = new JedisPooled(poolConfig, hostAndPort, clientConfig);
    
      jedis.sadd("planets", "Venus");       // just example
      jedis.sadd("planets", "Mars");        // just example
    
      jedis.close();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search