Implement a Redis Cache Service in Java

What is Redis: 
Redis is an open source , in-memory data structure store used as a database, cache, message broker, and streaming engine.
More info in

Jedis is a client library in Java for Redis

Install Redis
Check the instructions in

Java implementation

Add the Maven dependency in pom.xml


Create a new class JedisCacheService

private Jedis jedis;
 * Initialize the cache (default: port 6379 , localhost)
 * if you have started the service on a non-default port or a remote machine,
 * you should configure it by passing the correct values as parameters into the constructor.*/
 jedis = new Jedis();
/** expirationTimeinSeconds = timeout for the specified key. */ void set(String key, String value, int expirationTimeinSeconds) {
 jedis.setex(key, expirationTimeinSeconds, value);
String get(String key) {
String data = jedis.get(key);
 if (data != null)
   return data;
return null;

Unit Test:

public void storeDataToRedisCache(){
 int expirationTimeInSeconds = (int) TimeUnit.DAYS.toSeconds(30);
 JedisCacheService jedisCacheService = new JedisCacheService();
 String key = “key-1”;
 String value = “value-1”;
 jedisCacheService.set(key, value,expirationTimeInSeconds);
 String valueInCache = jedisCacheService.get(key);

Redis CLI

You can verify by checking from command line the data stored in Redis using the redis-cli

redis:6379> keys *
1) “key-1”

redis:6379> mget key-1
1) “value-1”

For more info for redis commands check the documentation
and for Jedis implemetation the

Code is also availible in
and the unit test in