redis事务解决超卖问题
redis的事务提供了一种将多个命令请求打包,然后一次性、按顺序性地执行多个命令的机制。
在事务执行期间,服务器不会中断事务而去执行其它客户端的命令请求,它会将事务中的所有命令执行完毕,然后才去处理其它客户端的命令请求。
事务以multi命令开始,然后将多个命令放到事务当中,最后由exec命令将这个事务提交给服务器执行。
1.引入相关jar包
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-redis</artifactid> <version>2.7.0</version> </dependency>
2.代码段
package com.example.demo; import org.springframework.beans.factory.annotation.autowired; import org.springframework.dao.dataaccessexception; import org.springframework.data.redis.core.redisoperations; import org.springframework.data.redis.core.redistemplate; import org.springframework.data.redis.core.sessioncallback; import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.restcontroller; import java.util.uuid; /** * @author lucifer * @description todo * @date 2022-08-10 */ @restcontroller public class controller { @autowired redistemplate redistemplate; //写入缓存中,因为这里的模拟的是一个商品被多人抢,所以value值随便吧 @getmapping("/test1") public void test1(){ redistemplate.opsforvalue().set("item1",uuid.randomuuid().tostring()); } //模拟多人抢一个商品,并且只有一件 @getmapping("/test") public string test(){ //生成随机的userid(模拟多用户去抢一个商品) string userid=uuid.randomuuid().tostring(); //redis key 商品id 为了模拟写成1 string key="item"+1; //如果redis中不存在抢这个商品的缓存,就代表抢失败 //商品独一份 if(!redistemplate.haskey(key)){ throw new runtimeexception("你没有抢到"); } //执行redis的事务 redistemplate.execute(new sessioncallback() { @override public object execute(redisoperations operations) throws dataaccessexception { //在使用multi()开始的事务期间观察给定的修改key operations.watch(key); //标记事务块的开始。 命令将被排队 operations.multi(); //设置key-value operations.opsforvalue().set(key,userid); //如果任何被监视的key已被修改,则操作将失败 return operations.exec(); } }); //删除 避免这个商品被其他人抢到了 redistemplate.delete(key); //todo....数据库操作 return "你抢到了"; } }
3.测试
用50个线程并发去调用接口,模拟多人并发抢商品的功能;
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论