go-micro.dev/v5@v5.12.0/client/cache.go (about)

     1  package client
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"hash/fnv"
     8  	"time"
     9  
    10  	cache "github.com/patrickmn/go-cache"
    11  
    12  	"go-micro.dev/v5/metadata"
    13  	"go-micro.dev/v5/transport/headers"
    14  )
    15  
    16  // NewCache returns an initialized cache.
    17  func NewCache() *Cache {
    18  	return &Cache{
    19  		cache: cache.New(cache.NoExpiration, 30*time.Second),
    20  	}
    21  }
    22  
    23  // Cache for responses.
    24  type Cache struct {
    25  	cache *cache.Cache
    26  }
    27  
    28  // Get a response from the cache.
    29  func (c *Cache) Get(ctx context.Context, req *Request) (interface{}, bool) {
    30  	return c.cache.Get(key(ctx, req))
    31  }
    32  
    33  // Set a response in the cache.
    34  func (c *Cache) Set(ctx context.Context, req *Request, rsp interface{}, expiry time.Duration) {
    35  	c.cache.Set(key(ctx, req), rsp, expiry)
    36  }
    37  
    38  // List the key value pairs in the cache.
    39  func (c *Cache) List() map[string]string {
    40  	items := c.cache.Items()
    41  
    42  	rsp := make(map[string]string, len(items))
    43  
    44  	for k, v := range items {
    45  		bytes, _ := json.Marshal(v.Object)
    46  		rsp[k] = string(bytes)
    47  	}
    48  
    49  	return rsp
    50  }
    51  
    52  // key returns a hash for the context and request.
    53  func key(ctx context.Context, req *Request) string {
    54  	ns, _ := metadata.Get(ctx, headers.Namespace)
    55  
    56  	bytes, _ := json.Marshal(map[string]interface{}{
    57  		"namespace": ns,
    58  		"request": map[string]interface{}{
    59  			"service":  (*req).Service(),
    60  			"endpoint": (*req).Endpoint(),
    61  			"method":   (*req).Method(),
    62  			"body":     (*req).Body(),
    63  		},
    64  	})
    65  
    66  	h := fnv.New64()
    67  	h.Write(bytes)
    68  
    69  	return fmt.Sprintf("%x", h.Sum(nil))
    70  }