1, 引入Maven 或gradle依赖
主要是开启starter-cache 和引入caffeine
dependencies {
implementation("org.springframework.boot:spring-boot-starter-cache")
implementation("com.github.ben-manes.caffeine:caffeine:2.8.5")
}
2, 在application class开启
@EnableCaching
@SpringBootApplication
class DemoCacheApplication
3, 写配置类
@Configuration
class AppConfig {
@Bean
fun cacheManager(): CacheManager {
return CaffeineCacheManager("Student")
.apply {
isAllowNullValues = false
setCaffeine(
Caffeine.newBuilder()
.maximumSize(100)
.expireAfterAccess(1, TimeUnit.HOURS)
)
}
}
}
4, 在具体的类上使用caffeine
interface StudentRepository : CrudRepository<Student, Long>
@Service
@CacheConfig(cacheNames = ["Student"])
class StudentService(val studentRepository: StudentRepository) {
@Cacheable(key = "#id")
fun findStudentById(id: Long) = studentRepository.findById(id)
@CacheEvict(key = "#id")
fun updateStudent(id: Long, student: Student) {
val existingStudent = this.findStudentById(id).get().copy(name = student.name)
studentRepository.save(existingStudent)
}
}
注意@CacheEvict (缓存移除)的用法, 当使用updateStudent 方法后, 会移除对应的id值的缓存, 参考https://www.concretepage.com/spring/cacheevict_spring
5, 其他相关class
@Entity
data class Student(
@Id
val id: Long?,
val name: String
)
@RestController
class StudentController(val studentService: StudentService, val cacheManager: CacheManager) {
@GetMapping("/{id}")
fun getStudent(@PathVariable id: Long) = studentService.findStudentById(id)
@GetMapping("/update/{id}")
fun updateStudent(@PathVariable id: Long) =
studentService.updateStudent(id, Student(id, "Name ${UUID.randomUUID()}"))
@GetMapping("/all")
fun allCache(): MutableCollection<String> = cacheManager.cacheNames
}
本文参考项目:
https://github.com/lynas/spring-cache-non-reactive
https://www.youtube.com/watch?v=_j9htDP8AhQ