adapter_redis.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Copyright 2020 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package adapter
  7. import (
  8. "context"
  9. "github.com/gogf/gf/container/gvar"
  10. "github.com/gogf/gf/database/gredis"
  11. "github.com/gogf/gf/os/gcache"
  12. "time"
  13. )
  14. // Redis is the gcache adapter implements using Redis server.
  15. type Redis struct {
  16. redis *gredis.Redis
  17. }
  18. // newAdapterMemory creates and returns a new memory cache object.
  19. func NewRedis(redis *gredis.Redis) gcache.Adapter {
  20. return &Redis{
  21. redis: redis,
  22. }
  23. }
  24. // Set sets cache with <key>-<value> pair, which is expired after <duration>.
  25. // It does not expire if <duration> == 0.
  26. // It deletes the <key> if <duration> < 0 or given <value> is nil.
  27. func (c *Redis) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error {
  28. var err error
  29. if value == nil || duration < 0 {
  30. _, err = c.redis.Ctx(ctx).DoVar("DEL", key)
  31. } else {
  32. if duration == 0 {
  33. _, err = c.redis.Ctx(ctx).DoVar("SET", key, value)
  34. } else {
  35. _, err = c.redis.Ctx(ctx).DoVar("SETEX", key, uint64(duration.Seconds()), value)
  36. }
  37. }
  38. return err
  39. }
  40. // Update updates the value of <key> without changing its expiration and returns the old value.
  41. // The returned value <exist> is false if the <key> does not exist in the cache.
  42. //
  43. // It deletes the <key> if given <value> is nil.
  44. // It does nothing if <key> does not exist in the cache.
  45. func (c *Redis) Update(ctx context.Context, key interface{}, value interface{}) (oldValue interface{}, exist bool, err error) {
  46. var (
  47. v *gvar.Var
  48. oldDuration time.Duration
  49. )
  50. // TTL.
  51. v, err = c.redis.Ctx(ctx).DoVar("TTL", key)
  52. if err != nil {
  53. return
  54. }
  55. oldDuration = v.Duration()
  56. if oldDuration == -2 {
  57. // It does not exist.
  58. return
  59. }
  60. // Check existence.
  61. v, err = c.redis.Ctx(ctx).DoVar("GET", key)
  62. if err != nil {
  63. return
  64. }
  65. oldValue = v.Val()
  66. // DEL.
  67. if value == nil {
  68. _, err = c.redis.Ctx(ctx).DoVar("DEL", key)
  69. if err != nil {
  70. return
  71. }
  72. return
  73. }
  74. // Update the value.
  75. if oldDuration == -1 {
  76. _, err = c.redis.Ctx(ctx).DoVar("SET", key, value)
  77. } else {
  78. oldDuration *= time.Second
  79. _, err = c.redis.Ctx(ctx).DoVar("SETEX", key, uint64(oldDuration.Seconds()), value)
  80. }
  81. return oldValue, true, err
  82. }
  83. // UpdateExpire updates the expiration of <key> and returns the old expiration duration value.
  84. //
  85. // It returns -1 if the <key> does not exist in the cache.
  86. // It deletes the <key> if <duration> < 0.
  87. func (c *Redis) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
  88. var (
  89. v *gvar.Var
  90. )
  91. // TTL.
  92. v, err = c.redis.Ctx(ctx).DoVar("TTL", key)
  93. if err != nil {
  94. return
  95. }
  96. oldDuration = v.Duration()
  97. if oldDuration == -2 {
  98. // It does not exist.
  99. oldDuration = -1
  100. return
  101. }
  102. oldDuration *= time.Second
  103. // DEL.
  104. if duration < 0 {
  105. _, err = c.redis.Ctx(ctx).Do("DEL", key)
  106. return
  107. }
  108. // Update the expire.
  109. if duration > 0 {
  110. _, err = c.redis.Ctx(ctx).Do("EXPIRE", key, uint64(duration.Seconds()))
  111. }
  112. // No expire.
  113. if duration == 0 {
  114. v, err = c.redis.Ctx(ctx).DoVar("GET", key)
  115. if err != nil {
  116. return
  117. }
  118. _, err = c.redis.Ctx(ctx).Do("SET", key, v.Val())
  119. }
  120. return
  121. }
  122. // GetExpire retrieves and returns the expiration of <key> in the cache.
  123. //
  124. // It returns 0 if the <key> does not expire.
  125. // It returns -1 if the <key> does not exist in the cache.
  126. func (c *Redis) GetExpire(ctx context.Context, key interface{}) (time.Duration, error) {
  127. v, err := c.redis.Ctx(ctx).DoVar("TTL", key)
  128. if err != nil {
  129. return 0, err
  130. }
  131. switch v.Int() {
  132. case -1:
  133. return 0, nil
  134. case -2:
  135. return -1, nil
  136. default:
  137. return v.Duration() * time.Second, nil
  138. }
  139. }
  140. // SetIfNotExist sets cache with <key>-<value> pair which is expired after <duration>
  141. // if <key> does not exist in the cache. It returns true the <key> dose not exist in the
  142. // cache and it sets <value> successfully to the cache, or else it returns false.
  143. //
  144. // The parameter <value> can be type of <func() interface{}>, but it dose nothing if its
  145. // result is nil.
  146. //
  147. // It does not expire if <duration> == 0.
  148. // It deletes the <key> if <duration> < 0 or given <value> is nil.
  149. func (c *Redis) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (bool, error) {
  150. var err error
  151. // Execute the function and retrieve the result.
  152. if f, ok := value.(func() (interface{}, error)); ok {
  153. value, err = f()
  154. if value == nil {
  155. return false, err
  156. }
  157. }
  158. // DEL.
  159. if duration < 0 || value == nil {
  160. v, err := c.redis.Ctx(ctx).DoVar("DEL", key, value)
  161. if err != nil {
  162. return false, err
  163. }
  164. if v.Int() == 1 {
  165. return true, err
  166. } else {
  167. return false, err
  168. }
  169. }
  170. v, err := c.redis.Ctx(ctx).DoVar("SETNX", key, value)
  171. if err != nil {
  172. return false, err
  173. }
  174. if v.Int() > 0 && duration > 0 {
  175. // Set the expire.
  176. _, err := c.redis.Ctx(ctx).Do("EXPIRE", key, uint64(duration.Seconds()))
  177. if err != nil {
  178. return false, err
  179. }
  180. return true, err
  181. }
  182. return false, err
  183. }
  184. // Sets batch sets cache with key-value pairs by <data>, which is expired after <duration>.
  185. //
  186. // It does not expire if <duration> == 0.
  187. // It deletes the keys of <data> if <duration> < 0 or given <value> is nil.
  188. func (c *Redis) Sets(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error {
  189. if len(data) == 0 {
  190. return nil
  191. }
  192. // DEL.
  193. if duration < 0 {
  194. var (
  195. index = 0
  196. keys = make([]interface{}, len(data))
  197. )
  198. for k, _ := range data {
  199. keys[index] = k
  200. index += 1
  201. }
  202. _, err := c.redis.Ctx(ctx).Do("DEL", keys...)
  203. if err != nil {
  204. return err
  205. }
  206. }
  207. if duration == 0 {
  208. var (
  209. index = 0
  210. keyValues = make([]interface{}, len(data)*2)
  211. )
  212. for k, v := range data {
  213. keyValues[index] = k
  214. keyValues[index+1] = v
  215. index += 2
  216. }
  217. _, err := c.redis.Ctx(ctx).Do("MSET", keyValues...)
  218. if err != nil {
  219. return err
  220. }
  221. }
  222. if duration > 0 {
  223. var err error
  224. for k, v := range data {
  225. if err = c.Set(ctx, k, v, duration); err != nil {
  226. return err
  227. }
  228. }
  229. }
  230. return nil
  231. }
  232. // Get retrieves and returns the associated value of given <key>.
  233. // It returns nil if it does not exist or its value is nil.
  234. func (c *Redis) Get(ctx context.Context, key interface{}) (interface{}, error) {
  235. v, err := c.redis.Ctx(ctx).DoVar("GET", key)
  236. if err != nil {
  237. return nil, err
  238. }
  239. return v.Val(), nil
  240. }
  241. // GetOrSet retrieves and returns the value of <key>, or sets <key>-<value> pair and
  242. // returns <value> if <key> does not exist in the cache. The key-value pair expires
  243. // after <duration>.
  244. //
  245. // It does not expire if <duration> == 0.
  246. // It deletes the <key> if <duration> < 0 or given <value> is nil, but it does nothing
  247. // if <value> is a function and the function result is nil.
  248. func (c *Redis) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (interface{}, error) {
  249. v, err := c.Get(ctx, key)
  250. if err != nil {
  251. return nil, err
  252. }
  253. if v == nil {
  254. return value, c.Set(ctx, key, value, duration)
  255. } else {
  256. return v, nil
  257. }
  258. }
  259. // GetOrSetFunc retrieves and returns the value of <key>, or sets <key> with result of
  260. // function <f> and returns its result if <key> does not exist in the cache. The key-value
  261. // pair expires after <duration>.
  262. //
  263. // It does not expire if <duration> == 0.
  264. // It deletes the <key> if <duration> < 0 or given <value> is nil, but it does nothing
  265. // if <value> is a function and the function result is nil.
  266. func (c *Redis) GetOrSetFunc(ctx context.Context, key interface{}, f func() (interface{}, error), duration time.Duration) (interface{}, error) {
  267. v, err := c.Get(ctx, key)
  268. if err != nil {
  269. return nil, err
  270. }
  271. if v == nil {
  272. value, err := f()
  273. if err != nil {
  274. return nil, err
  275. }
  276. if value == nil {
  277. return nil, nil
  278. }
  279. return value, c.Set(ctx, key, value, duration)
  280. } else {
  281. return v, nil
  282. }
  283. }
  284. // GetOrSetFuncLock retrieves and returns the value of <key>, or sets <key> with result of
  285. // function <f> and returns its result if <key> does not exist in the cache. The key-value
  286. // pair expires after <duration>.
  287. //
  288. // It does not expire if <duration> == 0.
  289. // It does nothing if function <f> returns nil.
  290. //
  291. // Note that the function <f> should be executed within writing mutex lock for concurrent
  292. // safety purpose.
  293. func (c *Redis) GetOrSetFuncLock(ctx context.Context, key interface{}, f func() (interface{}, error), duration time.Duration) (interface{}, error) {
  294. return c.GetOrSetFunc(ctx, key, f, duration)
  295. }
  296. // Contains returns true if <key> exists in the cache, or else returns false.
  297. func (c *Redis) Contains(ctx context.Context, key interface{}) (bool, error) {
  298. v, err := c.redis.Ctx(ctx).DoVar("EXISTS", key)
  299. if err != nil {
  300. return false, err
  301. }
  302. return v.Bool(), nil
  303. }
  304. // Remove deletes the one or more keys from cache, and returns its value.
  305. // If multiple keys are given, it returns the value of the deleted last item.
  306. func (c *Redis) Remove(ctx context.Context, keys ...interface{}) (value interface{}, err error) {
  307. if len(keys) == 0 {
  308. return nil, nil
  309. }
  310. // Retrieves the last key value.
  311. if v, err := c.redis.Ctx(ctx).DoVar("GET", keys[len(keys)-1]); err != nil {
  312. return nil, err
  313. } else {
  314. value = v.Val()
  315. }
  316. // Deletes all given keys.
  317. _, err = c.redis.Ctx(ctx).DoVar("DEL", keys...)
  318. return value, err
  319. }
  320. // Data returns a copy of all key-value pairs in the cache as map type.
  321. func (c *Redis) Data(ctx context.Context) (map[interface{}]interface{}, error) {
  322. // Keys.
  323. v, err := c.redis.Ctx(ctx).DoVar("KEYS", "*")
  324. if err != nil {
  325. return nil, err
  326. }
  327. keys := v.Slice()
  328. // Values.
  329. v, err = c.redis.Ctx(ctx).DoVar("MGET", keys...)
  330. if err != nil {
  331. return nil, err
  332. }
  333. values := v.Slice()
  334. // Compose keys and values.
  335. data := make(map[interface{}]interface{})
  336. for i := 0; i < len(keys); i++ {
  337. data[keys[i]] = values[i]
  338. }
  339. return data, nil
  340. }
  341. // Keys returns all keys in the cache as slice.
  342. func (c *Redis) Keys(ctx context.Context) ([]interface{}, error) {
  343. v, err := c.redis.Ctx(ctx).DoVar("KEYS", "*")
  344. if err != nil {
  345. return nil, err
  346. }
  347. return v.Slice(), nil
  348. }
  349. // Values returns all values in the cache as slice.
  350. func (c *Redis) Values(ctx context.Context) ([]interface{}, error) {
  351. // Keys.
  352. v, err := c.redis.Ctx(ctx).DoVar("KEYS", "*")
  353. if err != nil {
  354. return nil, err
  355. }
  356. keys := v.Slice()
  357. // Values.
  358. v, err = c.redis.Ctx(ctx).DoVar("MGET", keys...)
  359. if err != nil {
  360. return nil, err
  361. }
  362. return v.Slice(), nil
  363. }
  364. // Size returns the size of the cache.
  365. func (c *Redis) Size(ctx context.Context) (size int, err error) {
  366. v, err := c.redis.Ctx(ctx).DoVar("DBSIZE")
  367. if err != nil {
  368. return 0, err
  369. }
  370. return v.Int(), nil
  371. }
  372. // Clear clears all data of the cache.
  373. // Note that this function is sensitive and should be carefully used.
  374. func (c *Redis) Clear(ctx context.Context) error {
  375. // The "FLUSHDB" may not be available.
  376. if _, err := c.redis.Ctx(ctx).DoVar("FLUSHDB"); err != nil {
  377. keys, err := c.Keys(ctx)
  378. if err != nil {
  379. return err
  380. }
  381. _, err = c.Remove(ctx, keys...)
  382. return err
  383. }
  384. return nil
  385. }
  386. // Close closes the cache.
  387. func (c *Redis) Close(ctx context.Context) error {
  388. // It does nothing.
  389. return nil
  390. }