Spring Caching with Redis
Spring Data Redis project provide an CacheManager implementation for Redis.
Get Redis
Get a copy of Redis from official Redis website.
In most of linux distribution, you can install it from distribution repository directly.
Before you run you codes, make sure it is running.
Enable Caching
Add
@EnableCaching(mode=AdviceMode.ASPECTJ)
annotation on the configuration class if you are using Java based configuration.@Configuration ... @EnableCaching(mode=AdviceMode.ASPECTJ) public class JpaConfig {...}
Then, configure a Redis specific
CacheManager
.@Override @Bean public CacheManager cacheManager() { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate()); return cacheManager; } @Bean public RedisTemplate redisTemplate() { RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); return redisTemplate; } @Bean public JedisConnectionFactory jedisConnectionFactory() { // JedisPoolConfig poolConfig=new JedisPoolConfig(); // poolConfig.set JedisConnectionFactory connectionFactory = new JedisConnectionFactory(); connectionFactory.setHostName("192.168.1.103"); connectionFactory.setUsePool(true); return connectionFactory; } @Override @Bean public KeyGenerator keyGenerator() { return new SimpleKeyGenerator(); }
Do not forget to add the spring-data-redis dependency in your Maven pom.xml file.
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency>
Code sample
Check out the sample codes.
And explore the spring-cache-redis folder.
评论