Spring Redis Cache Manager Example

This tutorial shows how to use and configure Spring Redis Cache Manager. Caching service calls can greatly benefit your response time.

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>http://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>

Spring Redis Cache Service

We leverage spring’s @Cacheable annotation to add caching capabilities to the play() method. We can provide a condition to the annotation. In this example the methods response will only be cached when the instrument passed in is “guitar”.

Note: when providing a condition in the @Cacheable annotation make sure the SpEL-name aligns with the parameter name(s) of the method.
package com.memorynotfound;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MusicService {

    @Cacheable(value="messageCache", condition="'guitar'.equals(#instrument)")
    public String play( final String instrument ) {
        System.out.println("Executing: " + this.getClass().getSimpleName() + ".play(" + instrument + ")");
        return "paying " + instrument + "!";
    }
}

Redis Configuration

Add the redis.properties to the classpath.

redis.host=localhost
redis.port=6379

Spring Redis Cache Configuration

package com.memorynotfound;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
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.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
@EnableCaching
@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<Object, Object> redisTemplate() {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }

    @Bean
    CacheManager cacheManager() {
        return new RedisCacheManager(redisTemplate());
    }
}

Executing Spring Redis Cache Example

Let’s bootstrap the spring configuration and call the play() method a couple of times and see what happens.

package com.memorynotfound;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class RedisCacheExample {

    public static void main(String[] args) {

        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        MusicService musicService = ctx.getBean(MusicService.class);

        System.out.println("message: " + musicService.play("trumpet"));
        System.out.println("message: " + musicService.play("trumpet"));
        System.out.println("message: " + musicService.play("guitar"));
        System.out.println("message: " + musicService.play("guitar"));

        System.out.println("Done.");
    }

}

As expected only the second call with parameter guitar is cached.

Executing: MusicService.play(trumpet)
message: paying trumpet!
Executing: MusicService.play(trumpet)
message: paying trumpet!
message: Helloguitar
message: Helloguitar
Done.

References

Download

You may also like...