季節は春が好きなマスタカです
今回はSpringbootにキャッシュを入れてみた
・gradle
implementation("org.springframework.boot:spring-boot-starter-cache")
・Application
@EnableCaching
@SpringBootApplication
class MasterkaApplication
fun main(args: Array<String>) {
runApplication<MasterkaApplication>(*args)
}
・Controller
@RestController
class RestAPiController(val service: MasterkaService) {
@GetMapping("/get")
fun getApi(): DummyResponse {
return service.getApi()
}
}
・Service
interface MasterkaService {
fun getApi(): DummyResponse
}
@Service
class MasterkaServiceImpl : MasterkaService {
@Cacheable("getApi")
override fun getApi(): DummyResponse {
Thread.sleep(2000L)
return DummyResponse("masterka")
}
}
data class DummyResponse(val message: String)
sleep2秒してるので初回のレスポンスだけすごく遅い。
ただし2回目からはキャッシュが乗るので爆速になる
キャッシュがのると@CcaheableになってるgetApiは呼ばれずに以前に返却した値が返る
デフォルトのCacheはConcurrentHashMap
設定変えるとキャッシュ対象を変えれる
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-caching
試しにやってみましたが、ものすごい楽にキャッシュ入れれてびっくりしました
これ使って爆速にしていきたいと思います
まだまだ勉強は続くよ
参考
https://spring.io/guides/gs/caching/
関連記事:
- SpringBootでActuatorを使う
- 初めてのSpring Bootを実行してみる
- Kotlin + Gradle.kts + Intellijでspring-boot-devtoolsを動かす