Spring Boot可以使用缓存注解来配置缓存,主要有两种方式:
使用@EnableCaching注解开启缓存支持,在需要缓存的方法上使用缓存注解,如@Cacheable、@CachePut、@CacheEvict等。@SpringBootApplication@EnableCachingpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}@Servicepublic class UserService { @Cacheable("users") public User getUserById(Long id) { // 从数据库查询用户信息 return userRepository.findById(id).orElse(null); } @CachePut(value = "users", key = "#user.id") public User saveUser(User user) { // 保存用户信息到数据库 return userRepository.save(user); } @CacheEvict(value = "users", key = "#id") public void deleteUserById(Long id) { // 从数据库删除用户信息 userRepository.deleteById(id); }}在application.properties或application.yml文件中配置缓存相关的属性,如缓存类型、缓存过期时间等。#使用Redis缓存spring.cache.type=redis#Redis配置spring.redis.host=localhostspring.redis.port=6379spring.redis.password=spring.redis.database=0#缓存过期时间(单位:秒)spring.cache.redis.time-to-live=3600#使用Redis缓存spring: cache: type: redis#Redis配置spring: redis: host: localhost port: 6379 password: database: 0#缓存过期时间(单位:秒)spring: cache: redis: time-to-live: 3600注意:以上示例使用了Redis作为缓存存储,如果需要使用其他缓存实现,可以相应地修改配置。