Use hash/fnv, add tests, fix request bug

This commit is contained in:
Ben Toogood
2020-05-23 11:34:44 +01:00
parent 7d7f4046e8
commit 496293afa1
3 changed files with 99 additions and 34 deletions

View File

@@ -2,63 +2,52 @@ package client
import (
"context"
"crypto/sha1"
"encoding/json"
"fmt"
"sync"
"hash/fnv"
"time"
"github.com/micro/go-micro/v2/metadata"
cache "github.com/patrickmn/go-cache"
)
// NewCache returns an initialised cache.
// TODO: Setup a go routine to expire records in the cache.
func NewCache() *Cache {
return &Cache{
values: make(map[string]interface{}),
cache: cache.New(cache.NoExpiration, 30*time.Second),
}
}
// Cache for responses
type Cache struct {
values map[string]interface{}
mutex sync.Mutex
cache *cache.Cache
}
// Get a response from the cache
func (c *Cache) Get(ctx context.Context, req *Request) interface{} {
md, _ := metadata.FromContext(ctx)
ck := cacheKey{req, md}
c.mutex.Lock()
defer c.mutex.Unlock()
if val, ok := c.values[ck.Hash()]; ok {
return val
}
return nil
func (c *Cache) Get(ctx context.Context, req *Request) (interface{}, bool) {
return c.cache.Get(key(ctx, req))
}
// Set a response in the cache
func (c *Cache) Set(ctx context.Context, req *Request, rsp interface{}, expiry time.Duration) {
c.cache.Set(key(ctx, req), rsp, expiry)
}
// key returns a hash for the context and request
func key(ctx context.Context, req *Request) string {
md, _ := metadata.FromContext(ctx)
ck := cacheKey{req, md}
c.mutex.Lock()
c.values[ck.Hash()] = rsp
defer c.mutex.Unlock()
}
bytes, _ := json.Marshal(map[string]interface{}{
"metadata": md,
"request": map[string]interface{}{
"service": (*req).Service(),
"endpoint": (*req).Endpoint(),
"method": (*req).Method(),
"body": (*req).Body(),
},
})
type cacheKey struct {
Request *Request
Metadata metadata.Metadata
}
// Source: https://gobyexample.com/sha1-hashes
func (k *cacheKey) Hash() string {
bytes, _ := json.Marshal(k)
h := sha1.New()
h := fnv.New64()
h.Write(bytes)
return fmt.Sprintf("%x", h.Sum(nil))
}