Implement a Redis Cache Service in Java

Despina Papatheodorou
1 min readMay 15, 2022

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 https://redis.io/docs/about/

Jedis is a client library in Java for Redis

Install Redis
Check the instructions in https://redis.io/docs/getting-started/installation/

Java implementation

Add the Maven dependency in pom.xml

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.2</version>
</dependency>

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.*/
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;
}

Unit Test:

@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 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 https://redis.io/commands/
and for Jedis implemetation the https://javadoc.io/doc/redis.clients/jedis/latest/index.html

Code is also availible in https://github.com/despoina555/CodeExamples/blob/main/src/main/java/org/despina/JedisCacheService.java
and the unit test in
https://github.com/despoina555/CodeExamples/blob/main/src/test/java/org/despina/AppTest.java

--

--