simple_cache.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package cache
  2. import (
  3. "errors"
  4. "reflect"
  5. "sync"
  6. )
  7. // 此处实现了一个简单的缓存,用于测试
  8. // SimpleCache is a simple cache implementation
  9. type SimpleCache struct {
  10. data map[string]interface{}
  11. mu sync.Mutex
  12. maxBytes int64
  13. usedBytes int64
  14. }
  15. func (s *SimpleCache) Get(key string, value interface{}) error {
  16. s.mu.Lock()
  17. defer s.mu.Unlock()
  18. // 使用反射将存储的值设置到传入的指针变量中
  19. val := reflect.ValueOf(value)
  20. if val.Kind() != reflect.Ptr {
  21. return errors.New("value must be a pointer")
  22. }
  23. v, ok := s.data[key]
  24. if !ok {
  25. //设为空值
  26. val.Elem().Set(reflect.Zero(val.Elem().Type()))
  27. return nil
  28. }
  29. vval := reflect.ValueOf(v)
  30. if val.Elem().Type() != vval.Type() {
  31. //设为空值
  32. val.Elem().Set(reflect.Zero(val.Elem().Type()))
  33. return nil
  34. }
  35. val.Elem().Set(reflect.ValueOf(v))
  36. return nil
  37. }
  38. func (s *SimpleCache) Set(key string, value interface{}, exp int) error {
  39. s.mu.Lock()
  40. defer s.mu.Unlock()
  41. // 检查传入的值是否是指针,如果是则取其值
  42. val := reflect.ValueOf(value)
  43. if val.Kind() == reflect.Ptr {
  44. val = val.Elem()
  45. }
  46. s.data[key] = val.Interface()
  47. return nil
  48. }
  49. func (s *SimpleCache) Gc() error {
  50. return nil
  51. }
  52. func NewSimpleCache() *SimpleCache {
  53. return &SimpleCache{
  54. data: make(map[string]interface{}),
  55. }
  56. }