cache_test.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package cache
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math"
  6. "strconv"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/tal-tech/go-zero/core/errorx"
  11. "github.com/tal-tech/go-zero/core/hash"
  12. "github.com/tal-tech/go-zero/core/stores/redis"
  13. "github.com/tal-tech/go-zero/core/syncx"
  14. )
  15. type mockedNode struct {
  16. vals map[string][]byte
  17. errNotFound error
  18. }
  19. func (mc *mockedNode) DelCache(keys ...string) error {
  20. var be errorx.BatchError
  21. for _, key := range keys {
  22. if _, ok := mc.vals[key]; !ok {
  23. be.Add(mc.errNotFound)
  24. } else {
  25. delete(mc.vals, key)
  26. }
  27. }
  28. return be.Err()
  29. }
  30. func (mc *mockedNode) GetCache(key string, v interface{}) error {
  31. bs, ok := mc.vals[key]
  32. if ok {
  33. return json.Unmarshal(bs, v)
  34. }
  35. return mc.errNotFound
  36. }
  37. func (mc *mockedNode) SetCache(key string, v interface{}) error {
  38. data, err := json.Marshal(v)
  39. if err != nil {
  40. return err
  41. }
  42. mc.vals[key] = data
  43. return nil
  44. }
  45. func (mc *mockedNode) SetCacheWithExpire(key string, v interface{}, expire time.Duration) error {
  46. return mc.SetCache(key, v)
  47. }
  48. func (mc *mockedNode) Take(v interface{}, key string, query func(v interface{}) error) error {
  49. if _, ok := mc.vals[key]; ok {
  50. return mc.GetCache(key, v)
  51. }
  52. if err := query(v); err != nil {
  53. return err
  54. }
  55. return mc.SetCache(key, v)
  56. }
  57. func (mc *mockedNode) TakeWithExpire(v interface{}, key string, query func(v interface{}, expire time.Duration) error) error {
  58. return mc.Take(v, key, func(v interface{}) error {
  59. return query(v, 0)
  60. })
  61. }
  62. func TestCache_SetDel(t *testing.T) {
  63. const total = 1000
  64. r1, clean1, err := createMiniRedis()
  65. assert.Nil(t, err)
  66. defer clean1()
  67. r2, clean2, err := createMiniRedis()
  68. assert.Nil(t, err)
  69. defer clean2()
  70. conf := ClusterConf{
  71. {
  72. RedisConf: redis.RedisConf{
  73. Host: r1.Addr(),
  74. Type: redis.NodeType,
  75. },
  76. Weight: 100,
  77. },
  78. {
  79. RedisConf: redis.RedisConf{
  80. Host: r2.Addr(),
  81. Type: redis.NodeType,
  82. },
  83. Weight: 100,
  84. },
  85. }
  86. c := NewCache(conf, syncx.NewSharedCalls(), NewCacheStat("mock"), errPlaceholder)
  87. for i := 0; i < total; i++ {
  88. if i%2 == 0 {
  89. assert.Nil(t, c.SetCache(fmt.Sprintf("key/%d", i), i))
  90. } else {
  91. assert.Nil(t, c.SetCacheWithExpire(fmt.Sprintf("key/%d", i), i, 0))
  92. }
  93. }
  94. for i := 0; i < total; i++ {
  95. var v int
  96. assert.Nil(t, c.GetCache(fmt.Sprintf("key/%d", i), &v))
  97. assert.Equal(t, i, v)
  98. }
  99. assert.Nil(t, c.DelCache())
  100. for i := 0; i < total; i++ {
  101. assert.Nil(t, c.DelCache(fmt.Sprintf("key/%d", i)))
  102. }
  103. for i := 0; i < total; i++ {
  104. var v int
  105. assert.Equal(t, errPlaceholder, c.GetCache(fmt.Sprintf("key/%d", i), &v))
  106. assert.Equal(t, 0, v)
  107. }
  108. }
  109. func TestCache_OneNode(t *testing.T) {
  110. const total = 1000
  111. r, clean, err := createMiniRedis()
  112. assert.Nil(t, err)
  113. defer clean()
  114. conf := ClusterConf{
  115. {
  116. RedisConf: redis.RedisConf{
  117. Host: r.Addr(),
  118. Type: redis.NodeType,
  119. },
  120. Weight: 100,
  121. },
  122. }
  123. c := NewCache(conf, syncx.NewSharedCalls(), NewCacheStat("mock"), errPlaceholder)
  124. for i := 0; i < total; i++ {
  125. if i%2 == 0 {
  126. assert.Nil(t, c.SetCache(fmt.Sprintf("key/%d", i), i))
  127. } else {
  128. assert.Nil(t, c.SetCacheWithExpire(fmt.Sprintf("key/%d", i), i, 0))
  129. }
  130. }
  131. for i := 0; i < total; i++ {
  132. var v int
  133. assert.Nil(t, c.GetCache(fmt.Sprintf("key/%d", i), &v))
  134. assert.Equal(t, i, v)
  135. }
  136. assert.Nil(t, c.DelCache())
  137. for i := 0; i < total; i++ {
  138. assert.Nil(t, c.DelCache(fmt.Sprintf("key/%d", i)))
  139. }
  140. for i := 0; i < total; i++ {
  141. var v int
  142. assert.Equal(t, errPlaceholder, c.GetCache(fmt.Sprintf("key/%d", i), &v))
  143. assert.Equal(t, 0, v)
  144. }
  145. }
  146. func TestCache_Balance(t *testing.T) {
  147. const (
  148. numNodes = 100
  149. total = 10000
  150. )
  151. dispatcher := hash.NewConsistentHash()
  152. maps := make([]map[string][]byte, numNodes)
  153. for i := 0; i < numNodes; i++ {
  154. maps[i] = map[string][]byte{
  155. strconv.Itoa(i): []byte(strconv.Itoa(i)),
  156. }
  157. }
  158. for i := 0; i < numNodes; i++ {
  159. dispatcher.AddWithWeight(&mockedNode{
  160. vals: maps[i],
  161. errNotFound: errPlaceholder,
  162. }, 100)
  163. }
  164. c := cacheCluster{
  165. dispatcher: dispatcher,
  166. errNotFound: errPlaceholder,
  167. }
  168. for i := 0; i < total; i++ {
  169. assert.Nil(t, c.SetCache(strconv.Itoa(i), i))
  170. }
  171. counts := make(map[int]int)
  172. for i, m := range maps {
  173. counts[i] = len(m)
  174. }
  175. entropy := calcEntropy(counts, total)
  176. assert.True(t, len(counts) > 1)
  177. assert.True(t, entropy > .95, fmt.Sprintf("entropy should be greater than 0.95, but got %.2f", entropy))
  178. for i := 0; i < total; i++ {
  179. var v int
  180. assert.Nil(t, c.GetCache(strconv.Itoa(i), &v))
  181. assert.Equal(t, i, v)
  182. }
  183. for i := 0; i < total/10; i++ {
  184. assert.Nil(t, c.DelCache(strconv.Itoa(i*10), strconv.Itoa(i*10+1), strconv.Itoa(i*10+2)))
  185. assert.Nil(t, c.DelCache(strconv.Itoa(i*10+9)))
  186. }
  187. var count int
  188. for i := 0; i < total/10; i++ {
  189. var val int
  190. if i%2 == 0 {
  191. assert.Nil(t, c.Take(&val, strconv.Itoa(i*10), func(v interface{}) error {
  192. *v.(*int) = i
  193. count++
  194. return nil
  195. }))
  196. } else {
  197. assert.Nil(t, c.TakeWithExpire(&val, strconv.Itoa(i*10), func(v interface{}, expire time.Duration) error {
  198. *v.(*int) = i
  199. count++
  200. return nil
  201. }))
  202. }
  203. assert.Equal(t, i, val)
  204. }
  205. assert.Equal(t, total/10, count)
  206. }
  207. func TestCacheNoNode(t *testing.T) {
  208. dispatcher := hash.NewConsistentHash()
  209. c := cacheCluster{
  210. dispatcher: dispatcher,
  211. errNotFound: errPlaceholder,
  212. }
  213. assert.NotNil(t, c.DelCache("foo"))
  214. assert.NotNil(t, c.DelCache("foo", "bar", "any"))
  215. assert.NotNil(t, c.GetCache("foo", nil))
  216. assert.NotNil(t, c.SetCache("foo", nil))
  217. assert.NotNil(t, c.SetCacheWithExpire("foo", nil, time.Second))
  218. assert.NotNil(t, c.Take(nil, "foo", func(v interface{}) error {
  219. return nil
  220. }))
  221. assert.NotNil(t, c.TakeWithExpire(nil, "foo", func(v interface{}, duration time.Duration) error {
  222. return nil
  223. }))
  224. }
  225. func calcEntropy(m map[int]int, total int) float64 {
  226. var entropy float64
  227. for _, v := range m {
  228. proba := float64(v) / float64(total)
  229. entropy -= proba * math.Log2(proba)
  230. }
  231. return entropy / math.Log2(float64(len(m)))
  232. }