1, 引入Maven 或gradle依赖

主要是开启starter-cache 和引入caffeine

  1. dependencies {
  2. implementation("org.springframework.boot:spring-boot-starter-cache")
  3. implementation("com.github.ben-manes.caffeine:caffeine:2.8.5")
  4. }

2, 在application class开启

  1. @EnableCaching
  2. @SpringBootApplication
  3. class DemoCacheApplication

3, 写配置类

  1. @Configuration
  2. class AppConfig {
  3. @Bean
  4. fun cacheManager(): CacheManager {
  5. return CaffeineCacheManager("Student")
  6. .apply {
  7. isAllowNullValues = false
  8. setCaffeine(
  9. Caffeine.newBuilder()
  10. .maximumSize(100)
  11. .expireAfterAccess(1, TimeUnit.HOURS)
  12. )
  13. }
  14. }
  15. }

4, 在具体的类上使用caffeine

  1. interface StudentRepository : CrudRepository<Student, Long>
  2. @Service
  3. @CacheConfig(cacheNames = ["Student"])
  4. class StudentService(val studentRepository: StudentRepository) {
  5. @Cacheable(key = "#id")
  6. fun findStudentById(id: Long) = studentRepository.findById(id)
  7. @CacheEvict(key = "#id")
  8. fun updateStudent(id: Long, student: Student) {
  9. val existingStudent = this.findStudentById(id).get().copy(name = student.name)
  10. studentRepository.save(existingStudent)
  11. }
  12. }

注意@CacheEvict (缓存移除)的用法, 当使用updateStudent 方法后, 会移除对应的id值的缓存, 参考https://www.concretepage.com/spring/cacheevict_spring

5, 其他相关class

  1. @Entity
  2. data class Student(
  3. @Id
  4. val id: Long?,
  5. val name: String
  6. )
  7. @RestController
  8. class StudentController(val studentService: StudentService, val cacheManager: CacheManager) {
  9. @GetMapping("/{id}")
  10. fun getStudent(@PathVariable id: Long) = studentService.findStudentById(id)
  11. @GetMapping("/update/{id}")
  12. fun updateStudent(@PathVariable id: Long) =
  13. studentService.updateStudent(id, Student(id, "Name ${UUID.randomUUID()}"))
  14. @GetMapping("/all")
  15. fun allCache(): MutableCollection<String> = cacheManager.cacheNames
  16. }

本文参考项目:
https://github.com/lynas/spring-cache-non-reactive
https://www.youtube.com/watch?v=_j9htDP8AhQ