How to configure caching annotations in Spring Boot?

Spring Boot allows you to configure caching using cache annotations, with two main approaches.

  1. Enable caching support by using the @EnableCaching annotation, and then use cache annotations such as @Cacheable, @CachePut, @CacheEvict on the methods that need caching.
@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@Service
public 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);
    }
}
  1. Configure cache-related properties in the application.properties or application.yml file, such as cache type and expiration time.
#使用Redis缓存
spring.cache.type=redis

#Redis配置
spring.redis.host=localhost
spring.redis.port=6379
spring.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

Please note that the example above uses Redis as the caching storage. If you would like to use a different caching implementation, you can modify the configuration accordingly.

bannerAds