Spring Redis Application Configuration Example
This tutorial shows how to create and configure a Spring Redis Application. We use Java Configuration to configure Spring.
Dependencies
To start you need to add the following dependencies to your project.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.memorynotfound.redis</groupId>
<artifactId>redis-spring-cache</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>REDDIS - ${project.artifactId}</name>
<url>https://memorynotfound.com</url>
<properties>
<project.build.sourceencoding>UTF-8</project.build.sourceencoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>
Reading from and writing to Redis
Note: that in the setValue()
method we excplicitly expire the key after 5 seconds.
package com.memorynotfound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
@Autowired
private RedisTemplate< String, Object > template;
public Object getValue(final String key) {
return template.opsForValue().get(key);
}
public void setValue(final String key, final String value) {
template.opsForValue().set(key, value);
// set a expire for a message
template.expire(key, 5, TimeUnit.SECONDS);
}
}
Redis Configuration
Add the redis.properties to the classpath.
redis.host=localhost
redis.port=6379
Spring Redis Configuration
We need to create and configure the JedisConnectionFactory
which by default should be able to connect to a standard Redis without any configuration but you can also explicitly set the connection properties. We also need to configure a RedisTemplate
which will read/write data to and from redis.
package com.memorynotfound;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@ComponentScan("com.memorynotfound")
@PropertySource("classpath:/redis.properties")
public class AppConfig {
private @Value("${redis.host}") String redisHost;
private @Value("${redis.port}") int redisPort;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisHost);
factory.setPort(redisPort);
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate< String, Object > redisTemplate() {
final RedisTemplate< String, Object > template = new RedisTemplate< String, Object >();
template.setConnectionFactory( jedisConnectionFactory() );
template.setKeySerializer( new StringRedisSerializer() );
template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
return template;
}
}
Message Producer
Here we are setting a key with an appropriate value. Note: that in the service we explicitly set the expire message to 5 seconds. Check what happens if we first get the corresponding key, then wait a couple of seconds and then try to get the key again.
package com.memorynotfound;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MessageProducer {
public static void main(String... args) throws InterruptedException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
RedisService redisService = ctx.getBean(RedisService.class);
redisService.setValue("key", "hello world!");
System.out.println("message: " + redisService.getValue("key"));
Thread.sleep(1000 * 6);
System.out.println("message: " + redisService.getValue("key"));
}
}
Output
As expected the first time the key is present, but it automatically expired after 5 seconds.
message: hello world!
message: null
Nice tutorial.
How about if we want to use with spring boot application?
Thanks
You can simply use this code inside your spring boot project.
Make sure you add all the required dependencies of this project.
Hope this helps.