Spring Cache 操作详解
在现代的应用程序中,缓存是提升性能、减少数据源压力的重要手段之一。Spring Boot 提供了一个简洁的缓存抽象框架——spring-boot-starter-cache
,而 Redis 作为一个高性能的内存数据库,是缓存实现的理想选择。本文将介绍如何结合 Spring Boot Starter Cache 与 Redis 来实现缓存管理。
1. 添加依赖
首先,在 Spring Boot 项目中集成 Redis 和缓存功能,需要在 pom.xml
中添加相关依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring-boot-starter-cache
提供了 Spring 的缓存抽象,而 spring-boot-starter-data-redis
使我们能够使用 Redis 作为缓存存储。
2. 配置 Redis 连接
在 application.yml
或 application.properties
中配置 Redis 连接信息。以下是使用 application.yml
的示例:
spring:
redis:
host: localhost
port: 6379
password: yourpassword # 如果没有密码可以省略
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
cache:
type: redis # 将缓存类型指定为 redis
以上配置告诉 Spring Boot 使用 Redis 作为缓存存储,并配置了 Redis 连接的主机、端口和连接池。
3. 启用缓存功能
在主启动类或配置类中,添加 @EnableCaching
注解来开启 Spring Boot 的缓存支持:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
@EnableCaching
将启用缓存机制,允许在应用程序中使用缓存注解。
4. 使用缓存注解
Spring 提供了一系列注解用于缓存操作,其中最常用的是 @Cacheable
、@CachePut
和 @CacheEvict
。下面通过示例介绍如何使用这些注解。
@Cacheable
@Cacheable
注解用于将方法的返回值缓存起来,之后调用相同参数时将直接返回缓存的内容,而不是再次执行方法。
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) {
// 模拟耗时操作
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new User(id, "John Doe");
}
}
上面的代码中,getUserById
方法被 @Cacheable
注解标注,缓存名称为 users
,缓存的键为方法参数 id
。当第一次调用该方法时,结果将被缓存起来,之后使用相同的 id
调用时将直接从缓存中获取数据,而不会再次执行方法逻辑。
@CachePut
@CachePut
用于更新缓存,不会跳过方法执行。它确保方法执行并将结果存入缓存。
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user)