spring 如何给函数返回增加缓存
时间: 2024-03-02 13:52:51 浏览: 89
在 Spring 中,可以使用 Spring Cache 技术来实现函数的缓存。具体实现步骤如下:
1. 在 pom.xml 文件中添加依赖。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
```
2. 在 Spring Boot 应用的启动类上添加 @EnableCaching 注解,开启缓存功能。
```java
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
3. 在需要缓存的函数上添加 @Cacheable 注解,指定缓存的名称和缓存的 Key。
```java
@Service
public class UserService {
@Autowired
private UserDao userDao;
@Cacheable(value = "userCache", key = "#id")
public User getUserById(int id) {
return userDao.getUserById(id);
}
}
```
4. 配置缓存管理器,可以使用 Ehcache、Redis 等缓存实现,也可以使用 Spring Boot 默认的 ConcurrentMapCacheManager。在 application.properties 文件中添加如下配置:
```properties
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
```
这样,每次调用 getUserById 方法时,会先从缓存中查找对应的数据,如果缓存中存在,则直接返回缓存中的数据;如果缓存中不存在,则调用 userDao.getUserById 方法获取数据,并将数据存入缓存中。需要注意的是,缓存的 Key 可以使用 SpEL 表达式来动态生成,例如可以使用 "#user.id" 表示以用户 id 作为缓存的 Key。另外,Spring Cache 还支持 @CachePut、@CacheEvict、@Caching 等注解,用于更新缓存、清除缓存等操作。
阅读全文
相关推荐

















