memcache.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package cache
  2. import (
  3. "errors"
  4. "time"
  5. "github.com/bradfitz/gomemcache/memcache"
  6. )
  7. //Memcache struct contains *memcache.Client
  8. type Memcache struct {
  9. conn *memcache.Client
  10. }
  11. //NewMemcache create new memcache
  12. func NewMemcache(server ...string) *Memcache {
  13. mc := memcache.New(server...)
  14. return &Memcache{mc}
  15. }
  16. //Get return cached value
  17. func (mem *Memcache) Get(key string) interface{} {
  18. if item, err := mem.conn.Get(key); err == nil {
  19. return string(item.Value)
  20. }
  21. return nil
  22. }
  23. // IsExist check value exists in memcache.
  24. func (mem *Memcache) IsExist(key string) bool {
  25. _, err := mem.conn.Get(key)
  26. if err != nil {
  27. return false
  28. }
  29. return true
  30. }
  31. //Set cached value with key and expire time.
  32. func (mem *Memcache) Set(key string, val interface{}, timeout time.Duration) error {
  33. v, ok := val.(string)
  34. if !ok {
  35. return errors.New("val must string")
  36. }
  37. item := &memcache.Item{Key: key, Value: []byte(v), Expiration: int32(timeout / time.Second)}
  38. return mem.conn.Set(item)
  39. }
  40. //Delete delete value in memcache.
  41. func (mem *Memcache) Delete(key string) error {
  42. return mem.conn.Delete(key)
  43. }