Cache

  1. Usage
  2. Cache Keys
  3. Conditional Caching
  4. Event Listeners

Cache policies limit unnecessary load by caching and returning previous execution results, when possible.

Usage

Creating and using a CachePolicy for a cache is simple:

// Store connections under the "connection" key in the cache
cachePolicy := cachePolicy.Builder(cache).
  WithKey("connection").
  Build()
  
// Get a connection from the cache, else create a new one
connection, err := failsafe.Get(Connect, cachePolicy)

Cache Keys

A CachePolicy can use a key specified at the policy level, as shown above, to store cached execution results. It can also use a cache key provided at execution time, via a Context, allowing different keys to be used for different executions:

ctx := context.WithValue(context.Background(), cachepolicy.CacheKey, "connection")
connection, err := failsafe.NewExecutor(cachePolicy).
  WithContext(ctx).
  Get(Connect)

Conditional Caching

By default, any non-error execution results will be cached. But a CachePolicy can also be configured only cache results when a condition is met:

builder.CacheIf(func(response *http.Response, err error) bool {
  return response != nil && response.StatusCode == 200
})

Event Listeners

A CachePolicy can notify you with an ExecutionEvent when a result is added to the cache:

builder.OnResultCached(func(e failsafe.ExecutionEvent[any]) {
  logger.Info("Cached result", "result", e.LastResult())
})

It can also notify you when a cache hit or miss occurs:

builder.OnCacheHit(func(e failsafe.ExecutionDoneEvent[any]) {
  logger.Info("Cache hit", "result", e.Result)
}).onCacheMiss(func(e failsafe.ExecutionEvent[any]) {
  logger.Info("Cache miss")
})