【问题标题】:Spring cache for specific values @Cacheable annotationSpring缓存特定值@Cacheable注解
【发布时间】:2021-08-22 23:49:37
【问题描述】:

我只想在结果的属性包含特定值时才缓存方法的结果。例如

Class APIOutput(code: Int, message: String)
sealed class Response<out T : Any> : Serializable {
    data class Success<out T : Any>(val data: T) : Response<T>()
    data class Error(val errorText: String, val errorCode: Int) : Response<Nothing>()
}
@Cacheable(
        key = "api-key",
        unless = "do something here"
    )
fun doApicall(uniqueId: Long): Response<APIOutput> {
        //make API call
        val output = callAPI(uniqueId)
        return Response.Success(output)
}

在上述方法中,我只想在 Response.Success.data.code ==(长代码列表)时缓存响应。 请注意,在上一行中,data 只不过是 APIOutput 对象。我如何使用除非或任何其他方法来实现它。我正在考虑编写一个函数,该函数将 doApicall 方法结果作为输入,并返回 true 或 false 并将该方法调用为除非 =“调用方法”。但我不知道该怎么做。非常感谢任何帮助。

【问题讨论】:

    标签: spring spring-boot kotlin caching spring-cache


    【解决方案1】:

    感谢 Yatharth 和约翰!以下是对我有用的条件。以下表达式中的 resultcodes 是一个列表

    @Cacheable(
                key = "api-key",
                unless = "!(#result instanceof T(com.abc.Response\$Success)) 
                or (#result instanceof T(com.abc.Response\$Success) 
                and !(T(com.abc.APIStatus).resultCodes.contains(#result.data.code)))"
    )
    fun doApicall(uniqueId: Long): Response<APIOutput> {
        //make API call
        val output = callAPI(uniqueId)
        return Response.Success(output)
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用SpELunless 中指定要计算的表达式。返回值以result 的形式提供,因此您可以执行以下操作 -

      @Cacheable(
              key = "api-key",
              unless = "#result!=null or #result.success.data.code!=200"
          )
      fun doApicall(uniqueId: Long): Response<APIOutput> {
              //make API call
              val output = callAPI(uniqueId)
              return Response.Success(output)
      }
      

      如果现有功能不足以满足您的用例,您甚至可以在 SpEL 中使用 Regex,并且可以创建自定义表达式解析器。

      【讨论】:

      猜你喜欢
      • 2018-02-07
      • 2019-08-28
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多