Is there any better way available to implement redis as cache for different applications in clustered environment

时间:2019-01-07 13:21:22

标签: java rest redis architecture jedis

I'm trying to use redis server as cache. Due to the requirements I am bound to follow some constraints :-

  1. XML base configurations instead of annotations.
  2. Use of Jedis library to perform caching related activity like fetch all cache objects, fetch single cache object, remove all cache objects, save all cache objects, save single cache object etc.
  3. Cache key will be object and values will be Object or list of objects.

Following the constraints I did lot of research and able to achieve the desired results.

  1. I created a bean using xml configurations which has 2 constructor arguments. (cache name, reference of jedis pool)
  2. In the other bean definition for the above jedis pool (redis.clients.jedis.JedisPool) I have put the host and port (where the redis server is running) as constructor arguments for jedis pool class.
  3. make sure redis server is running.
  4. build and deploy the application.
  5. Now written some methods to perform caching related activity as mentioned above.

    a) save all cache objects, save single cache object :- used hset method of jedispool passing 3 arguments - cache name as byte array, cache key byte array after serializing the key object as byte array, cache value byte array after serializing the value object as byte array. (save all will be done by calling save in loop)

    b) fetch all cache objects, fetch single cache object :- used hgetAll method of jedispool class by passing cache name as byte array. and hget method of jedispool class by passing cache name as byte array and cache key object as byte array.

    c) for removing cache object :- call jedispool hdel method passing by passing cache name as byte array and cache key object as byte array.

    redis.clients jedis 2.6.2

    public synchronized void put(Key key, Object object) throws Exception {

        jedisPool.hset("cache-name-one", methodToSerializeKey(key), methodToSerializeObject(object));
    }
    

    public synchronized void remove(Key key) throws Exception {

        jedisPool.hdel("cache-name-one", methodToSerializeKey(key));
    
    }
    

    public synchronized Object get(Key key) throws Exception {

        return methodToDeserialize(jedisPool.hget("cache-name-one", methodToSerializeKey(key)));
    }
    

All above implementation is working fine.I would like to know if anything can be improved here.

Also we will have multiple cache object available to be save like "cache-name-two, cache-name-three". As I read in one of the article the best approach is to have redis instance run on different ports on same server.

This will work in this scenario as well I believe.

Also as per my understanding I don't need to return redisPool instance after every operation as it is created once in bean initialization face.

0 个答案:

没有答案