Caching with Spring Data Redis

本文将介绍如何使用Spring Data Redis项目作为Spring Cache抽象的缓存提供者,包括依赖配置、服务实现、配置文件示例及输出解析。重点在于通过Spring的@Cacheable注解实现基于SpEL条件的缓存,以及展示如何配置JedisConnectionFactory、RedisTemplate和RedisCacheManager。通过XML和Java配置方式演示了如何启用声明式缓存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


In the example below, I’ll show you how to use the Spring Data – Redis project as a caching provider for the Spring Cache Abstraction that was introduced in Spring 3.1. I get a lot of questions about how to use Spring’s Java based configuration so I’ll provide both XML and Java based configurations for your review.

Dependencies

The following dependencies were used in this example:
 
 
 

01 <?xml version='1.0' encoding='UTF-8'?>
02 <project xmlns='http://maven.apache.org/POM/4.0.0'
05     <modelVersion>4.0.0</modelVersion>
06     <groupId>com.joshuawhite.example</groupId>
07     <artifactId>spring-redis-example</artifactId>
08     <version>1.0</version>
09     <packaging>jar</packaging>
10     <name>Spring Redis Example</name>
11     <dependencies>
12         <dependency>
13             <groupId>org.springframework.data</groupId>
14             <artifactId>spring-data-redis</artifactId>
15             <version>1.0.2.RELEASE</version>
16         </dependency>       
17         <!-- required for @Configuration annotation -->
18         <dependency>
19             <groupId>cglib</groupId>
20             <artifactId>cglib</artifactId>
21             <version>2.2.2</version>
22         </dependency>
23         <dependency>
24             <groupId>redis.clients</groupId>
25             <artifactId>jedis</artifactId>
26             <version>2.0.0</version>
27             <type>jar</type>
28             <scope>compile</scope>
29         </dependency>
30         <dependency>
31             <groupId>log4j</groupId>
32             <artifactId>log4j</artifactId>
33             <version>1.2.14</version>
34         </dependency>
35     </dependencies>
36     <build>
37         <plugins>
38             <plugin>
39                 <groupId>org.apache.maven.plugins</groupId>
40                 <artifactId>maven-compiler-plugin</artifactId>
41                 <configuration>
42                     <source>1.6</source>
43                     <target>1.6</target>
44                 </configuration>
45             </plugin>
46         </plugins>
47     </build>
48 </project>

Code and Configuration

The HelloService example below is very simple. As you will see in the implementation, it simply returns a String with “Hello” prepended to the name that is passed in.

1 package com.joshuawhite.example.service;
2  
3 public interface HelloService {
4  
5     String getMessage(String name);
6  
7 }

Looking at the HelloServiceImpl class (below), you can see that I am leveraging Spring’s @Cacheable annotation to add caching capabilities to the getMessage method. For more details on the capabilities of this annotation, take a look at the Cache Abstraction documentation. For fun, I am using the Spring Expression Language (SpEL) to define a condition. In this example, the methods response will only be cached when the name passed in is “Joshua”.

01 package com.joshuawhite.example.service;
02  
03 import org.springframework.cache.annotation.Cacheable;
04 import org.springframework.stereotype.Service;
05  
06 @Service('helloService')
07 public class HelloServiceImpl implements HelloService {
08  
09     /**
10      * Using SpEL for conditional caching - only cache method executions when
11      * the name is equal to 'Joshua'
12      */
13     @Cacheable(value='messageCache', condition=''Joshua'.equals(#name)')
14     public String getMessage(String name) {
15         System.out.println('Executing HelloServiceImpl' +
16                         '.getHelloMessage(\'' + name + '\')');
17  
18         return 'Hello ' + name + '!';
19     }
20  
21 }

The App class below contains our main method and is used to select between XML and Java based configurations. Each of theSystem.out.println‘s are used to demonstrate when caching is taking place. As a reminder, we only expect method executions passing in “Joshua” to be cached. This will be more clear when we look at the programs output later.

01 package com.joshuawhite.example;
02  
03 import org.springframework.cache.Cache;
04 import org.springframework.cache.CacheManager;
05 import org.springframework.context.ApplicationContext;
06 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
07 import org.springframework.context.support.GenericXmlApplicationContext;
08  
09 import com.joshuawhite.example.config.AppConfig;
10 import com.joshuawhite.example.service.HelloService;
11  
12 public class App {
13  
14     public static void main(String[] args) {
15  
16         boolean useJavaConfig  = true;
17         ApplicationContext ctx = null;
18  
19         //Showing examples of both Xml and Java based configuration
20         if (useJavaConfig ) {
21                 ctx = new AnnotationConfigApplicationContext(AppConfig.class);
22         }
23         else {
24                 ctx = new GenericXmlApplicationContext('/META-INF/spring/app-context.xml');
25         }
26  
27         HelloService helloService = ctx.getBean('helloService', HelloService.class);
28  
29         //First method execution using key='Josh', not cached
30         System.out.println('message: ' + helloService.getMessage('Josh'));
31  
32         //Second method execution using key='Josh', still not cached
33         System.out.println('message: ' + helloService.getMessage('Josh'));
34  
35         //First method execution using key='Joshua', not cached
36         System.out.println('message: ' + helloService.getMessage('Joshua'));
37  
38         //Second method execution using key='Joshua', cached
39         System.out.println('message: ' + helloService.getMessage('Joshua'));
40  
41         System.out.println('Done.');
42     }
43  
44 }

Notice that component scanning is still used when using the XML based configuration. You can see that I am using the @Serviceannotation on line 6 of HelloServiceImpl.java above. Next we will take a look at how to configure a jedisConnectionFactory,redisTemplate and cacheManager.

Configuring the JedisConnectionFactory

For this example, I chose to use Jedis as our Java client of choice because it is listed on the Redis site as being the “recommended”client library for Java. As you can see, the setup is very straight forward. While I am explicitly setting use-pool=true, it the source code indicates that this is the default. The JedisConnectionFactory also provides the following defaults when not explicitly set:

  • hostName=”localhost”
  • port=6379
  • timeout=2000 ms
  • database=0
  • usePool=true

Note: Though the database index is configurable, the JedisConnectionFactory only supports connecting to one Redis database at a time. Because Redis is single threaded, you are encouraged to set up multiple instances of Redis instead of using multiple databases within a single process. This allows you to get better CPU/resource utilization. If you plan to use redis-cluster, only a single database is supported. For more information about the defaults used in the connection pool, take a look at the implementation of JedisPoolConfigor the Apache Commons Pool org.apache.commons.pool.impl.GenericObjectPool.Config and it’s enclosingorg.apache.commons.pool.impl.GenericObjectPool class.

Configuring the RedisTemplate

As you would expect from a Spring “template” class, the RedisTemplate takes care of serialization and connection management and (providing you are using a connection pool) is thread safe. By default, the RedisTemplate uses Java serialization (JdkSerializationRedisSerializer). Note that serializing data into Redis essentially makes Redis an “opaque” cache. While other serializers allow you to map the data into Redis, I have found serialization, especially when dealing with object graphs, is faster and simpler to use. That being said, if you have a requirement that other non-java applications be able to access this data, mapping is your best out-of-the-box option. I have had a great experience using Hessian and Google Protocol Buffers/protostuff. I’ll share some sample implementations of the RedisSerializer in a future post.

Configuring the RedisCacheManager

Configuring the RedisCacheManager is straight forward. As a reminder, the RedisCacheManager is dependent on a RedisTemplatewhich is dependent on a connection factory, in our case JedisConnectionFactory, that can only connect to a single database at a time. As a workaround, the RedisCacheManager has the capability of setting up a prefix for your cache keys.

Warning: When dealing with other caching solutions, Spring’s CacheManger usually contains a map of Cache (each implementing map like functionality) implementations that are backed by separate caches. Using the default RedisCacheManager configuration, this is not the case. Based on the javadoc comment on the RedisCacheManager, its not clear if this is a bug or simply incomplete documentation.

“…By default saves the keys by appending a prefix (which acts as a namespace).”

While the DefaultRedisCachePrefix which is configured in the RedisCacheManager certainly supports this, it is not enabled by default. As a result, when you ask the RedisCacheManager for a Cache of a given name, it simply creates a new Cache instance that points to the same database. As a result, the Cache instances are all the same. The same key will retrieve the same value in all Cache instances.

As the javadoc comment alludes to, prefixs can be used to setup client managed (Redis doesn’t support this functionality natively) namespaces that essentially create “virtual” caches within the same database. You can turn this feature on by callingredisCacheManager.setUsePrefix(true) either using the Spring XML or Java configuration.

01 <?xml version='1.0' encoding='UTF-8'?>
02 <beans
09     xsi:schemaLocation='
10  
12  
15  
16     <context:component-scan base-package='com.joshuawhite.example.service' />
17     <context:property-placeholder location='classpath:/redis.properties'/>
18  
19     <!-- turn on declarative caching -->
20     <cache:annotation-driven />
21  
22     <!-- Jedis ConnectionFactory -->
23     <bean
24         id='jedisConnectionFactory'
25         class='org.springframework.data.redis.connection.jedis.JedisConnectionFactory'
26         p:host-name='${redis.host-name}'
27         p:port='${redis.port}'
28         p:use-pool='true'/>
29  
30     <!-- redis template definition -->
31     <bean
32         id='redisTemplate'
33         class='org.springframework.data.redis.core.RedisTemplate'
34         p:connection-factory-ref='jedisConnectionFactory'/>
35  
36     <!-- declare Redis Cache Manager -->
37     <bean
38         id='cacheManager'
39         class='org.springframework.data.redis.cache.RedisCacheManager'
40         c:template-ref='redisTemplate'/>
41  
42 </beans>

The Java configuration below is equivalent to the XML configuration above. People usually get hung up on using aPropertySourcesPlaceholderConfigurer. To do that, you need to use both the @PropertySource annotation and define aPropertySourcesPlaceholderConfigurer bean. The PropertySourcesPlaceholderConfigurer will not be sufficient on its own.

01 package com.joshuawhite.example.config;
02  
03 import org.springframework.beans.factory.annotation.Value;
04 import org.springframework.cache.CacheManager;
05 import org.springframework.context.annotation.Bean;
06 import org.springframework.context.annotation.ComponentScan;
07 import org.springframework.context.annotation.Configuration;
08 import org.springframework.context.annotation.PropertySource;
09 import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
10 import org.springframework.data.redis.cache.RedisCacheManager;
11 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
12 import org.springframework.data.redis.core.RedisTemplate;
13  
14 @Configuration
15 @ComponentScan('com.joshuawhite.example')
16 @PropertySource('classpath:/redis.properties')
17 public class AppConfig {
18  
19  private @Value('${redis.host-name}') String redisHostName;
20  private @Value('${redis.port}'int redisPort;
21  
22  @Bean
23  public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
24      return new PropertySourcesPlaceholderConfigurer();
25  }
26  
27  @Bean
28  JedisConnectionFactory jedisConnectionFactory() {
29      JedisConnectionFactory factory = new JedisConnectionFactory();
30      factory.setHostName(redisHostName);
31      factory.setPort(redisPort);
32      factory.setUsePool(true);
33      return factory;
34  }
35  
36  @Bean
37  RedisTemplate<Object, Object> redisTemplate() {
38      RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
39      redisTemplate.setConnectionFactory(jedisConnectionFactory());
40      return redisTemplate;
41  }
42  
43  @Bean
44  CacheManager cacheManager() {
45      return new RedisCacheManager(redisTemplate());
46  }
47  
48 }

Here is the properties file that is used by both configurations. Replace the values below with the host and port that you are using.

1 redis.host-name=yourHostNameHere
2 redis.port=6379

Output

Finally, here is the output from our brief example application. Notice that no matter how many times we call getHelloMessage('Josh'), the methods response does not get cached. This is because we defined a condition (see HelloServiceImpl.java, line 13) where we only cache the methods response when the name equals “Joshua”. When we call getHelloMessage('Joshua') for the first time, the method is executed. The second time however, it is not.

1 Executing HelloServiceImpl.getHelloMessage('Josh')
2 message: Hello Josh!
3 Executing HelloServiceImpl.getHelloMessage('Josh')
4 message: Hello Josh!
5 Executing HelloServiceImpl.getHelloMessage('Joshua')
6 message: Hello Joshua!
7 Executing HelloServiceImpl.getHelloMessage('Joshua')
8 message: Hello Joshua!
9 Done.

This concludes our brief over view of caching with Spring Data Redis.
 

Reference: Caching with Spring Data Redis from our JCG partner Joshua White at the Joshua White’s Blog blog.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值