2020-05-22 16:52:24 +01:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2020-05-23 11:34:44 +01:00
|
|
|
"hash/fnv"
|
2020-05-22 16:52:24 +01:00
|
|
|
"time"
|
|
|
|
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/metadata"
|
2020-05-23 11:34:44 +01:00
|
|
|
cache "github.com/patrickmn/go-cache"
|
2020-05-22 16:52:24 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// NewCache returns an initialised cache.
|
|
|
|
func NewCache() *Cache {
|
|
|
|
return &Cache{
|
2020-05-23 11:34:44 +01:00
|
|
|
cache: cache.New(cache.NoExpiration, 30*time.Second),
|
2020-05-22 16:52:24 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cache for responses
|
|
|
|
type Cache struct {
|
2020-05-23 11:34:44 +01:00
|
|
|
cache *cache.Cache
|
2020-05-22 16:52:24 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get a response from the cache
|
2020-07-27 13:22:00 +01:00
|
|
|
func (c *Cache) Get(ctx context.Context, req Request) (interface{}, bool) {
|
2020-05-23 11:34:44 +01:00
|
|
|
return c.cache.Get(key(ctx, req))
|
2020-05-22 16:52:24 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set a response in the cache
|
2020-07-27 13:22:00 +01:00
|
|
|
func (c *Cache) Set(ctx context.Context, req Request, rsp interface{}, expiry time.Duration) {
|
2020-05-23 11:34:44 +01:00
|
|
|
c.cache.Set(key(ctx, req), rsp, expiry)
|
2020-05-22 16:52:24 +01:00
|
|
|
}
|
|
|
|
|
2020-05-24 18:45:57 +01:00
|
|
|
// List the key value pairs in the cache
|
|
|
|
func (c *Cache) List() map[string]string {
|
|
|
|
items := c.cache.Items()
|
|
|
|
|
|
|
|
rsp := make(map[string]string, len(items))
|
|
|
|
for k, v := range items {
|
|
|
|
bytes, _ := json.Marshal(v.Object)
|
|
|
|
rsp[k] = string(bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
return rsp
|
|
|
|
}
|
|
|
|
|
2020-05-23 11:34:44 +01:00
|
|
|
// key returns a hash for the context and request
|
2020-07-27 13:22:00 +01:00
|
|
|
func key(ctx context.Context, req Request) string {
|
2020-05-27 09:07:59 +01:00
|
|
|
ns, _ := metadata.Get(ctx, "Micro-Namespace")
|
2020-05-22 16:52:24 +01:00
|
|
|
|
2020-05-23 11:34:44 +01:00
|
|
|
bytes, _ := json.Marshal(map[string]interface{}{
|
2020-05-27 09:07:59 +01:00
|
|
|
"namespace": ns,
|
2020-05-23 11:34:44 +01:00
|
|
|
"request": map[string]interface{}{
|
2020-07-27 13:22:00 +01:00
|
|
|
"service": req.Service(),
|
|
|
|
"endpoint": req.Endpoint(),
|
|
|
|
"method": req.Method(),
|
|
|
|
"body": req.Body(),
|
2020-05-23 11:34:44 +01:00
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
h := fnv.New64()
|
2020-05-22 16:52:24 +01:00
|
|
|
h.Write(bytes)
|
|
|
|
return fmt.Sprintf("%x", h.Sum(nil))
|
|
|
|
}
|