title: Cache the result of a Mono from a WebClient call in a Spring WebFlux web application
body: <p>I am looking to cache a <code>Mono</code> (only if it is successful) which is the result of a WebClient call.  </p>
  
  <p>From reading the project reactor addons docs I don't feel that <a href="https://projectreactor.io/docs/extra/3.2.0.RELEASE/api/reactor/cache/CacheMono.html" rel="noreferrer">CacheMono</a> is a good fit as it caches the errors as well which I do not want.</p>
  
  <p>So instead of using <code>CacheMono</code> I am doing the below:</p>
  
  <pre><code>Cache&lt;MyRequestObject, Mono&lt;MyResponseObject&gt;&gt; myCaffeineCache = 
      Caffeine.newBuilder()
              .maximumSize(100)
              .expireAfterWrite(Duration.ofSeconds(60))
              .build();
  
  MyRequestObject myRequestObject = ...;
  
  Mono&lt;MyResponseObject&gt; myResponseObject = myCaffeineCache.get(myRequestObject,
      requestAsKey -&gt; WebClient.create()
                               .post()
                               .uri("http://www.example.com")
                               .syncBody(requestAsKey)
                               .retrieve()
                               .bodyToMono(MyResponseObject.class)
                               .cache()
                               .doOnError(t -&gt; myCaffeineCache.invalidate(requestAsKey)));
  </code></pre>
  
  <p>Here I am calling cache on the <code>Mono</code> and then adding it to the caffeine cache. </p>
  
  <p>Any errors will enter <code>doOnError</code> to invalidate the cache.</p>
  
  <p>Is this a valid approach to caching a <code>Mono</code> WebClient response?</p>