@Cacheable和 @CachePut的区别
时间: 2023-11-22 14:48:05 浏览: 31
@Cacheable和@CachePut都是Spring框架中用于缓存的注解,它们的区别在于:
- @Cacheable注解会先查询缓存,如果缓存中存在所需数据,则直接返回缓存数据,否则执行方法并将方法返回值存入缓存中。
- @CachePut注解不会查询缓存,而是每次都会执行方法,并将方法返回值存入缓存中。
下面是一个示例代码,演示了@Cacheable和@CachePut的区别:
```python
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
public class UserService {
@Cacheable(value = "userCache", key = "#userId")
public User getUserById(String userId) {
// 从数据库中查询用户信息
User user = userDao.getUserById(userId);
return user;
}
@CachePut(value = "userCache", key = "#user.userId")
public User updateUser(User user) {
// 更新用户信息到数据库
userDao.updateUser(user);
return user;
}
}
```
在上面的示例中,getUserById方法使用了@Cacheable注解,当第一次调用该方法时,会从数据库中查询用户信息,并将查询结果存入缓存中。当再次调用该方法时,会直接从缓存中获取用户信息,而不是再次查询数据库。
updateUser方法使用了@CachePut注解,每次调用该方法都会执行方法体中的代码,并将方法返回值存入缓存中。这样可以保证缓存中的数据与数据库中的数据保持一致。