温馨提示×

springboot怎么配置缓存注解

小亿
88
2024-01-19 18:35:29
栏目: 编程语言

Spring Boot可以使用缓存注解来配置缓存,主要有两种方式:

  1. 使用@EnableCaching注解开启缓存支持,在需要缓存的方法上使用缓存注解,如@Cacheable、@CachePut、@CacheEvict等。
@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. 在application.properties或application.yml文件中配置缓存相关的属性,如缓存类型、缓存过期时间等。
#使用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

注意:以上示例使用了Redis作为缓存存储,如果需要使用其他缓存实现,可以相应地修改配置。

0