Integrating Redis Cache into Spring Boot: Installation, Configuration, and Usage
This guide explains how to install Redis, configure it within a Spring Boot application, define custom Redis helper interfaces and implementations, and demonstrates testing and practical usage of caching annotations for efficient data retrieval.
In real-world development, caching is essential to improve system performance by storing frequently accessed data close to the client. This article walks through the complete process of integrating Redis with a Spring Boot project.
1. Installation
Download Redis from https://redis.io/download and install it locally. After installation, start the Redis server by running redis-server.exe. The server startup is confirmed by the displayed console output.
2. Integration into Spring Boot
Add the Redis starter dependency to pom.xml:
<!-- 整合Redis缓存支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>Configure Redis connection properties in application.yml:
##默认密码为空
redis:
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
jedis:
pool:
#连接池最大连接数(使用负值表示没有限制)
max-active: 100
#连接池中的最小空闲连接
max-idle: 10
#连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 100000
#连接超时时间(毫秒)
timeout: 5000
#默认是索引为0的数据库
database: 0Create a RedisConfiguration class that extends CachingConfigurerSupport and enables caching with @EnableCaching. Inside, define a custom KeyGenerator, a CacheManager bean using RedisCacheManager, and a RedisTemplate<String, String> bean with proper serializers.
@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object p : params) {
sb.append(p.toString());
}
System.out.println("调用Redis缓存Key : " + sb.toString());
return sb.toString();
}
};
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.create(factory);
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(om);
template.setValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}Define a generic RedisHelper<HK, T> interface that declares common Redis operations (hash, list, value, expiration, etc.).
public interface RedisHelper<HK, T> {
void hashPut(String key, HK hashKey, T domain);
Map<HK, T> hashFindAll(String key);
T hashGet(String key, HK hashKey);
void hashRemove(String key, HK hashKey);
Long listPush(String key, T domain);
Long listUnshift(String key, T domain);
List<T> listFindAll(String key);
T listLPop(String key);
void valuePut(String key, T domain);
T getValue(String key);
void remove(String key);
boolean expirse(String key, long timeout, TimeUnit timeUnit);
}Implement the interface in RedisHelperImpl, injecting RedisTemplate and obtaining operation objects for hash, list, set, zset, and value.
@Service("RedisHelper")
public class RedisHelperImpl<HK, T> implements RedisHelper<HK, T> {
private RedisTemplate<String, T> redisTemplate;
private HashOperations<String, HK, T> hashOperations;
private ListOperations<String, T> listOperations;
private ZSetOperations<String, T> zSetOperations;
private SetOperations<String, T> setOperations;
private ValueOperations<String, T> valueOperations;
@Autowired
public RedisHelperImpl(RedisTemplate<String, T> redisTemplate) {
this.redisTemplate = redisTemplate;
this.hashOperations = redisTemplate.opsForHash();
this.listOperations = redisTemplate.opsForList();
this.zSetOperations = redisTemplate.opsForZSet();
this.setOperations = redisTemplate.opsForSet();
this.valueOperations = redisTemplate.opsForValue();
}
@Override
public void hashPut(String key, HK hashKey, T domain) {
hashOperations.put(key, hashKey, domain);
}
// ... other method implementations omitted for brevity ...
@Override
public boolean expirse(String key, long timeout, TimeUnit timeUnit) {
return redisTemplate.expire(key, timeout, timeUnit);
}
}3. Testing
Write a JUnit test class TestRedis that autowires StringRedisTemplate, RedisTemplate, and RedisHelperImpl. The tests demonstrate basic value storage, object serialization, and retrieval.
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisHelperImpl redisHelper;
@Test
public void test() throws Exception {
Author user = new Author();
user.setName("Alex");
user.setIntro_l("不会打篮球的程序不是好男人");
redisHelper.valuePut("aaa", user);
System.out.println(redisHelper.getValue("aaa"));
}
// Additional test for object operations omitted for brevity
}4. Practical Application
Enable caching in the main application class with @EnableCaching and use @Cacheable(value="poemInfo") on controller methods to automatically cache results.
@EnableCaching
@SpringBootApplication
public class PoetryApplication {
public static void main(String[] args) {
SpringApplication.run(PoetryApplication.class, args);
}
}
@RestController
@RequestMapping("/poem")
public class AuthorController {
@Autowired
private AuthorRepository authorRepository;
@Cacheable(value = "poemInfo")
@PostMapping("/poemInfo")
public Result<Author> author(@RequestParam("author_id") int author_id,
@RequestParam("author_name") String author_name) {
// method body omitted for brevity
}
}With these steps, Redis is fully integrated into the Spring Boot project, providing a flexible caching layer for both simple values and complex objects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
