Redis Lock

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
Function signature:
    NewRedisLock func(store *Redis, key string) *RedisLock
description:
    1. Deleting a single record will also clear the key cache
    Default expiration time of 1500 ms
in participation:
    1. store: redis instance
    2. key: key
return value:
    1. *RedLock: redis locker instance
  1. SetExpire
Function signature:
    SetExpire func(seconds int)
description:
    1. Set expiration time
entry:
    1. seconds: expiration time, in seconds
  1. Acquire
Function signature:
    Acquire func() (bool, error)
description:
    1. Get lock
return value:
    1. bool: get lock
    2. error: operator error
  1. AcquireCtx
Function signature:
AcquireCtx func(ctx context.Context) (bool, error)
description:
    1. Get lock
Input:
    1. ctx: context
Return value:
    1. bool: Whether to get lock
    2. error: operator error
  1. Release
Function signature:
Release func() (bool, error)
description:
    1. Get lock
return value:
    1. bool: get lock
    2. error: operator error
  1. ReleaseCtx
Function signature:
    ReleaseCtx function (ctx context.Context) (bool, error)
description:
    1. Release Lock
Input:
    1. ctx: context
Return value:
    1. bool: Is locked released actively
    . error: operator

Use demo

{
    conf := RedisConf{
        Host: "127.0.0.1:55000",
        Type: "node",
        Pass: "123456",
        Tls:  false,
    }

    rds := MustNewRedis(conf)

    lock := NewRedisLock(rds, "test")

    lock.SetExpire(10)

    acquire, err := lock.Acquire()

    switch {
    case err != nil:
        // deal err
    case acquire:
        defer lock.Release()
        // Add code here

    case !acquire:

    }
}