3

I need 3 separate caches:

  • Response with some data
  • Null
  • Exception

I've already defined the two caches

@Caching(cacheable = {
    @Cacheable(value = "SomeCache", key = "#a1", unless = "#result == null"),
    @Cacheable(value = "SomeNullCache", key = "#a1", unless = "#result != null")})

So, I have to implement the last case.

JSR-107 provides @CacheResult annotation with exceptionCacheName attribute, but how can I do this using Spring Cache? I don't want to combine JSR-107 and Spring Cache.

Evgeny Mironenko
  • 389
  • 3
  • 5
  • 26

1 Answers1

4

The cache abstraction does not support caching exception throw by annotated method. Your setup looks very weird to me. Why would you use two different regions for null and non-null values?

Use the standard annotation if you want such setup.

I don't want to combine JSR-107 and Spring Cache.

The id generation being different (to be spec compliant and keeping backward compatibility), I wouldn't recommend such usage. At least not on the same region.

Stephane Nicoll
  • 31,977
  • 9
  • 97
  • 89
  • I have to distinguish null, non-null, exceptional values and put them into the difference caches, because they have different configuration (life time and so on). If the cache abstraction does not support caching exception throw, how can I define the separate caches for null and non-null values? @CacheResult annotation doesn't have _condition_ or _unless_ attributes. – Evgeny Mironenko Oct 04 '16 at 12:07
  • Only one annotation for JSR-107 is allowed so they don't support that use case. The time-to-live difference between null and non null values is mental (sorry. Again.). – Stephane Nicoll Oct 04 '16 at 13:46
  • I understand the need to handle null / error results differently - you probably want to cache real results longer, but retry sooner. I suggest to wrap all kinds of results (ok / null / exception) into another object with these info; and then you can have separate methods that you could "run through" based on the type of result. But that's not much readable code. Maybe you can avoid annotations in this case and simply use the caching API directly. – Ondra Žižka Mar 02 '20 at 13:36