github.com/micro/go-micro/v2@v2.9.1/client/cache.go (about)

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