Implement a Redis Cache Service in Java

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.2</version>
</dependency>
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.*/
JedisCacheService(){
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;
}
@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);
Assert.assertEquals(value,valueInCache);
}
redis:6379> keys *
1) “key-1”
redis:6379> mget key-1
1) “value-1”

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store