Redis Lock

Overview

This section mainly describes the use of redis to create a distribution lock.

Preparing

  1. Complete golang installation
  2. Start redis service
  3. Redis created

Description

  1. Random version number, prevent outdated releases.
  2. Can reenter, automatic renewal.

Methodological description

  1. NewRedisLock

    1. Function signature:
    2. NewRedisLock func(store *Redis, key string) *RedisLock
    3. description:
    4. 1. Deleting a single record will also clear the key cache
    5. Default expiration time of 1500 ms
    6. in participation:
    7. 1. store: redis instance
    8. 2. key: key
    9. return value:
    10. 1. *RedLock: redis locker instance
  2. SetExpire

    1. Function signature:
    2. SetExpire func(seconds int)
    3. description:
    4. 1. Set expiration time
    5. entry:
    6. 1. seconds: expiration time, in seconds
  3. Acquire

    1. Function signature:
    2. Acquire func() (bool, error)
    3. description:
    4. 1. Get lock
    5. return value:
    6. 1. bool: get lock
    7. 2. error: operator error
  4. AcquireCtx

    1. Function signature:
    2. AcquireCtx func(ctx context.Context) (bool, error)
    3. description:
    4. 1. Get lock
    5. Input:
    6. 1. ctx: context
    7. Return value:
    8. 1. bool: Whether to get lock
    9. 2. error: operator error
  5. Release

    1. Function signature:
    2. Release func() (bool, error)
    3. description:
    4. 1. Get lock
    5. return value:
    6. 1. bool: get lock
    7. 2. error: operator error
  6. ReleaseCtx

  1. Function signature:
  2. ReleaseCtx function (ctx context.Context) (bool, error)
  3. description:
  4. 1. Release Lock
  5. Input:
  6. 1. ctx: context
  7. Return value:
  8. 1. bool: Is locked released actively
  9. . error: operator

Use demo

  1. {
  2. conf := RedisConf{
  3. Host: "127.0.0.1:55000",
  4. Type: "node",
  5. Pass: "123456",
  6. Tls: false,
  7. }
  8. rds := MustNewRedis(conf)
  9. lock := NewRedisLock(rds, "test")
  10. lock.SetExpire(10)
  11. acquire, err := lock.Acquire()
  12. switch {
  13. case err != nil:
  14. // deal err
  15. case acquire:
  16. defer lock.Release()
  17. // Add code here
  18. case !acquire:
  19. }
  20. }