spring-boot 踩坑程序员

spring-boot-cache应用小结(Redis篇)

2019-03-14  本文已影响1人  aef5bc56a01e

背景

最近公司项目处于停滞期,私想着是时候优化代码了,于是想到了缓存的应用。于是遇到了一系列的问题,在此稍作总结。
之前自己用redis存东西的时候,都是手动操作,略显麻烦,于是就想着用一下spring-cache。

spring-boot-cache

spring cache支持天然支持多种缓存

相关注解

配置

spring:
  cache:
    type: redis  #要用的缓存类型
    cache-names: test #默认的缓存名称,如果在对应的cacheName不指定,则会用到该名字
    redis:
      key-prefix:  TEST_ #缓存key的前缀,如果不配置,则会根据cacheNames和key组合为redis的key
      time-to-live:  10m #缓存时间

Talk is cheap, show me code.

import java.io.Serializable
import javax.persistence.Entity
import javax.persistence.Id
import org.springframework.cache.annotation.Cacheable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory

inline fun <reified T> logger(): Logger {
    return LoggerFactory.getLogger(T::class.java)
}

@Entity
data class SysConfig(
        @Id
        var id: Long = 0,
        var key: String? = null,
        var value: String? = null,
        var remark: String? = null,
        var status: Int = 0
): Serializable

interface SysConfigRepository : JpaRepository<SysConfig, Long> {
    fun findByKey(key: String): SysConfig?
}

@Service
class SysConfigService(val configRepository: SysConfigRepository) {
    val log = logger<SysConfigService>()
    @Cacheable("SYS_CONFIG_DETAIL", key = "#name + '_' + #i")
    fun findByName(name: String, i: Int): SysConfig? {
        log.info("load from db {} {}", name, i)
        return configRepository.findByKey(name)
    }

    @Cacheable("SYS_CONFIG_ALL")
    fun all(): List<SysConfig> {
        log.info("load from db")
        return configRepository.findAll()
    }
}

@RestController
@RequestMapping("config")
class SysConfigController(val sysConfigService: SysConfigService) {

    @GetMapping("/{name}")
    fun config(@PathVariable("name") name: String,
               @RequestParam(value = "i", required = false, defaultValue = "0")i: Int) = sysConfigService.findByName(name, i)

    @GetMapping("")
    fun config() = sysConfigService.all()
}

访问对应的url即可去redis中观察

image.png

PS:如果有缓存hash需求的可参看我的另外一篇文章《spring-boot-cache之 lettuce VS redisson》

上一篇 下一篇

猜你喜欢

热点阅读