memcache.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package store
  2. import (
  3. "context"
  4. "go-common/library/cache/memcache"
  5. "go-common/library/log"
  6. )
  7. // Memcache represents the cache with memcached persistence
  8. type Memcache struct {
  9. pool *memcache.Pool
  10. }
  11. // NewMemcache new a memcache store.
  12. func NewMemcache(c *memcache.Config) *Memcache {
  13. if c == nil {
  14. panic("cache config is nil")
  15. }
  16. return &Memcache{
  17. pool: memcache.NewPool(c),
  18. }
  19. }
  20. // Set save the result to memcache store.
  21. func (ms *Memcache) Set(ctx context.Context, key string, value []byte, expire int32) (err error) {
  22. item := &memcache.Item{
  23. Key: key,
  24. Value: value,
  25. Expiration: expire,
  26. }
  27. conn := ms.pool.Get(ctx)
  28. defer conn.Close()
  29. if err = conn.Set(item); err != nil {
  30. log.Error("conn.Set(%s) error(%v)", key, err)
  31. }
  32. return
  33. }
  34. // Get get result from mc by locaiton+params.
  35. func (ms *Memcache) Get(ctx context.Context, key string) ([]byte, error) {
  36. conn := ms.pool.Get(ctx)
  37. defer conn.Close()
  38. r, err := conn.Get(key)
  39. if err != nil {
  40. if err == memcache.ErrNotFound {
  41. //ignore not found error
  42. return nil, nil
  43. }
  44. log.Error("conn.Get(%s) error(%v)", key, err)
  45. return nil, err
  46. }
  47. return r.Value, nil
  48. }