[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>一、使用场景
通常在分布式系统中,我们经常会从数据库中读取数据和修改数据,然而这不是一个原子操作,在并发时就会导致数据的不正确,例如一会下面的电商秒杀,库存数量的更新就会遇到。
<>二、实现锁的条件
1.互斥性:在任何时候,都有一个客户端持有锁
2.不能出现死锁:即在一个客户端持有锁的期间内,如果客户端出现故障也不能影响后续的客户端可以持有锁
3.保证上锁和解锁的是同一个客户端
<>三、具体实现
*
<>setnx+expire (加锁)
setnx k1 value1 expire 5 seconds #成功返回1,在键k1不存在的时候将key的值设置为value1 setnx k1
value2 expire 5 seconds #失败返回0,因为k1已经存在值value1了,相当于已经有客户端吃锁了,设置失败 del k1
#删除k1的值,成功返回1,这里的del相当于释放锁 setnx k1 value2 expire 5 seconds #成功,返回1 type
orderService struct { orderRepository repository.OrderRepository goodsService
service.IGoodsService redis *redis.Client } func (s *orderService)
tryLock(userId, goodsId, lockId int64) (err error) { var res bool //Redis
Setnx命令在指定的 key 不存在时,为 key 设置指定的值(key存在了不能覆盖) if res, err =
s.redis.SetNX(service.Ctx, fmt.Sprintf("lock:%d:%d", userId, goodsId), lockId,
time.Minute).Result(); err != nil { log.Printf("redis.SetNx() failed, err: %v",
err) err = code.RedisErr return } if !res { err = code.MiaoshaFailed } return }
*
<>lua脚本
if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then
redis.call('expire',KEYS[1],ARGV[2]) else return 0 end;
*
<>设置ttl
SET key value [EX seconds] [PX milliseconds] [NX|XX]
EX seconds:将键的过期时间设置为seconds秒。
PX milliseconds:将键的过期时间设置为milliseconds毫秒。
NX : 只在键不存在时, 才对键进行设置操作。
XX : 只在键已经存在时, 才对键进行设置操作。