Redis Lock
Overview
This section mainly describes the use of redis to create a distribution lock.
Preparing
- Complete golang installation
- Start redis service
- Redis created
Description
- Random version number, prevent outdated releases.
- Can reenter, automatic renewal.
Methodological description
- 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 - SetExpire
Function signature:
SetExpire func(seconds int)
description:
1. Set expiration time
entry:
1. seconds: expiration time, in seconds - Acquire
Function signature:
Acquire func() (bool, error)
description:
1. Get lock
return value:
1. bool: get lock
2. error: operator error - 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 - Release
Function signature:
Release func() (bool, error)
description:
1. Get lock
return value:
1. bool: get lock
2. error: operator error - 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:
}
}