[英]How do I tell Spring Cache to cache the exceptions in @Cacheable annotation?
[英]Spring cache for specific values @Cacheable annotation
我只想在結果的屬性包含特定值時才緩存方法的結果。 例如
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 ==(長代碼列表)時緩存響應。 請注意,上一行中的數據只不過是 APIOutput object。 我如何使用除非或任何其他方法來實現它。 我正在考慮編寫一個 function ,它將doApicall方法結果作為輸入,並返回 true 或 false 並將該方法稱為除非 =“調用方法”。 但我不知道該怎么做。 非常感謝任何幫助。
unless
使用SpEL ,否則您可以指定要評估的表達式。 返回的值作為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,並且可以創建自定義表達式解析器。
感謝 Yatharth 和約翰。 以下是對我有用的條件。 以下表達式中的結果代碼是一個列表
@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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.