malaohu说:
malaohu 说:
import os
import time
import redis
env = os.environ.get
REDIS_CONF = {
"host": env("ALONE_REDIS_HOST", ""),
"port": env("ALONE_REDIS_PORT", 6378),
"password": env("ALONE_REDIS_PASSWORD", ""),
"db": env("BUZZERS_REDIS_DB_LOCK", 1),
"socket_timeout": None,
"encoding": "utf-8",
"encoding_errors": "strict",
"decode_responses": True
}
connection_pool = redis.ConnectionPool(**REDIS_CONF)
redis_lock = redis.Redis(connection_pool=connection_pool)
redis_lock.ping()
class RedisLock(object):
"""
redis原子锁
"""
def __init__(self, prefix="redis_lock", key="",
expire_time=2, timeout=2,
interval=0.2):
"""
:param prefix: 原子锁前缀
:param expire_time: 锁过期时间
:param timeout: 最长等待秒数,默认2秒(timeout=0获取不到锁则立即返回)
:param interval: 时间间隔
"""
self.key = key
self.prefix = prefix
self.expire_time = expire_time
self.timeout = timeout
self.interval = interval
self._lock = False # 是否获得锁
@property
def rds_key(self):
return "%s|%s" % (self.prefix, self.key)
def __del__(self):
"""
该对象释放的时候 删除锁
:return:
"""
if self._lock:
self.delete_lock()
def acquire(self):
"""
获取用户锁,默认最长2秒等待
:return: True 获取到锁 False 获取锁失败
"""
start_time = time.time()
end_time = start_time + self.timeout
while time.time() > result = redis_lock.set(
self.rds_key,
1,
ex=self.expire_time,
nx=True
)
if result:
self._lock = True
return True
time.sleep(self.interval)
return False
def release(self):
"""
删除用户锁
:return:
"""
redis_lock.delete(self.rds_key)
self._lock = False
def __enter__(self):
if not self._lock:
return self.acquire()
return False
def __exit__(self, type, value, traceback):
if self._lock:
self.release()
def __del__(self):
self.release()
请将上面代码用golang实现一下
package redis
import (
"github.com/go-redis/redis/v7"
"time"
)
type RedisLock struct {
Prefix string
Key string
ExpireTime int
Timeout int
Interval int
_lock bool
redisClient *redis.Client
redisOptions *redis.Options
}
func NewRedisLock(prefix string, key string, expireTime int, timeout int, interval int) *RedisLock {
return &RedisLock{
Prefix: prefix,
Key: key,
ExpireTime: expireTime,
Timeout: timeout,
Interval: interval,
_lock: false,
redisClient: nil,
}
}
func (lock *RedisLock) GetRedisKey() string {
return lock.Prefix + "|" + lock.Key
}
func (lock *RedisLock) InitRedisClient(options *redis.Options) {
lock.redisClient = redis.NewClient(options)
lock.redisOptions = options
}
func (lock *RedisLock) Acquire() bool {
startTime := time.Now().Unix()
endTime := startTime + int64(lock.Timeout)
for time.Now().Unix() < endTime {
result := lock.redisClient.SetNX(lock.GetRedisKey(), 1, time.Duration(lock.ExpireTime)*time.Second).Val()
if result {
lock._lock = true
return true
}
time.Sleep(time.Duration(lock.Interval) * time.Second)
}
return false
}
func (lock *RedisLock) Release() {
lock.redisClient.Del(lock.GetRedisKey())
lock._lock = false
}
func (lock *RedisLock) Lock() bool {
if !lock._lock {
return lock.Acquire()
}
return false
}
func (lock *RedisLock) Unlock() {
if lock._lock {
lock.Release()
}
}