I'm trying to use redis server as cache. Due to the requirements I am bound to follow some constraints :-
Following the constraints I did lot of research and able to achieve the desired results.
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.