在 Spring 框架中,Spring Cache
是一个用于简化缓存操作的抽象层,而 Redis 是一种常用的高性能键值存储系统,常被用作缓存数据库。通过将 Redis 与 Spring Cache 集成,可以轻松实现基于 Redis 的缓存管理。
以下是使用 Redis 和 Spring Cache 的基本步骤和配置说明:
在 Maven 或 Gradle 中添加必要的依赖项。
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>redis.clientsgroupId>
<artifactId>jedisartifactId>
dependency>
dependencies>
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'redis.clients:jedis'
在 application.yml
或 application.properties
文件中配置 Redis 连接信息。
spring:
redis:
host: localhost # Redis 服务器地址
port: 6379 # Redis 端口
password: # Redis 密码(如果没有密码则留空)
timeout: 5000ms # 超时时间
lettuce:
pool:
max-active: 8 # 最大连接数
max-idle: 8 # 最大空闲连接数
min-idle: 0 # 最小空闲连接数
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=5000
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
在 Spring Boot 应用程序的主类上添加 @EnableCaching
注解以启用缓存功能。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
通过配置 RedisCacheManager
来定义 Redis 缓存的行为。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
@Configuration
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // 设置缓存过期时间为 10 分钟
.disableCachingNullValues() // 不缓存 null 值
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer())); // 使用 JSON 序列化
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(cacheConfiguration)
.build();
}
}
Spring Cache 提供了一些注解来简化缓存操作。常用注解包括:
@Cacheable
:从缓存中读取数据,如果缓存中没有,则执行方法并将结果存入缓存。@CachePut
:更新缓存中的数据。@CacheEvict
:清除缓存中的数据。@Caching
:组合多个缓存操作。import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
// 模拟从数据库中获取用户
System.out.println("Fetching user from database for ID: " + id);
return new User(id, "User" + id);
}
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
// 更新用户信息
System.out.println("Updating user in cache: " + user);
return user;
}
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
// 删除用户信息
System.out.println("Deleting user from cache: " + id);
}
}
编写测试代码来验证缓存是否正常工作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
}
访问 /user/1
时,第一次会触发数据库查询并缓存结果,后续访问将直接从 Redis 中读取缓存数据。
可以通过 Redis 客户端工具(如 redis-cli
或 Redis Desktop Manager)查看缓存内容。
例如,使用 redis-cli
查看所有缓存键:
keys *
通过结合 Redis 和 Spring Cache,可以快速实现基于 Redis 的分布式缓存功能。Spring Cache 提供了简洁的注解方式,降低了缓存管理的复杂性。根据实际需求,还可以进一步优化 Redis 的配置,例如设置不同的缓存过期时间、序列化方式等。