1. 开启spring的缓存支持
首先需要在Spring Boot中添加缓存依赖,可以使用Spring Boot提供的starter来简化配置,例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
然后在springboot的启动类(配置类)中添加 @EnableCaching
@SpringBootApplication
@EnableCaching //注解开启spring自带的缓存
public class APP {
public static void main(String[] args) {
SpringApplication.run(APP.class);
}
}
然后还可以在配置类中定义一个类型为CachaManager的bean,这个CacheManager是一个接口,有
多种实现,如果不配置,则会使用自动配置的ConcurrentMapCacheManager,
ConcurrentHashMap将缓存信息直接存储在本地jvm内存中,不过线上环境一般是集群的方
式,可以通过redis实现,如果配置了多个CacheManager可以在yml文件中选择
spring:
cache:
type: simple # simple就是使用的ConcurrentMapCacheManager
2. 在service中需要使用缓存的方法上添加注解
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Cacheable(value = "userCache", key = "#userId")
public User getUserById(Long userId) {
return userRepository.findById(userId).orElse(null);
}
@CacheEvict(value = "userCache", key = "#userId")
public void deleteUserById(Long userId) {
userRepository.deleteById(userId);
}
@CachePut(value = "userCache", key = "#user.userId")
public User saveUser(User user) {
return userRepository.save(user);
}
}
上面的例子演示了三种不同的缓存注解:
-
@Cacheable
:表示该方法执行时会先查找缓存,如果缓存中存在对应的结果,则直接返回缓存中的结果;否则执行该方法并缓存结果。value
属性表示缓存的名字,key
属性表示缓存的键值,在这里我们使用userId
作为缓存的键。 -
@CacheEvict
:表示该方法执行时会清除缓存,value
和key
属性与@Cacheable
相同。 -
@CachePut
:表示该方法执行时会更新缓存,即使缓存中已经存在该键值,也会执行该方法并更新缓存。value
和key
属性与@Cacheable
相同。
以上就是Spring Boot缓存的基本使用方法,使用缓存可以提高应用程序的性能和响应速度,减轻数据库等后端服务的压力。