使用redisson实现分布式秒杀功能
redisson相比原生的jredis具有排队的功能,不一致秒杀时,一时获取锁失败就返回失败。
秒杀的原理就是使用redis的分布式锁的功能,保证每次抢购不会出现超卖的情况
1引入pomdependencygroupIdorg。redissongroupIdredissonartifactIdversion3。16。8versiondependency2完整代码及解析如下packagehtmdemo;importcom。ruoyi。common。core。redis。RedisCache;importorg。redisson。api。RLock;importorg。redisson。api。RedissonClient;importorg。springframework。beans。factory。annotation。Autowired;importorg。springframework。stereotype。Component;importjava。util。ArrayList;importjava。util。concurrent。;使用redisson来实现分布式的秒杀功能authorAdministratorComponentpublicclassReddisonTest{AutowiredprivateRedisCacheredisCache;AutowiredRedissonClientredissonClient;秒杀throwsExecutionExceptionthrowsInterruptedExceptionpublicvoidsecondkill()throwsExecutionException,InterruptedException{加锁的实现方式ExecutorServiceexecExecutors。newFixedThreadPool(50);ArrayListFutureIntegerfuturesnewArrayList();RLockstockLockredissonClient。getLock(stockLock);for(inti0;i50;i){FutureIntegerfsubmitexec。submit((){intdoneCount0;初始化做的任务为0if(stockLock。tryLock(1,1,TimeUnit。SECONDS)){获取到锁,则做业务trylock(param1,param2,param3):尝试获取锁param1:等待时间(在这个时间内不停获取锁)param2:获取成功后锁的有效时间param3:时间单位(秒分。。。)intstockredisCache。getCacheObject(stock);stock;redisCache。setCacheObject(stock,stock);doneCount;isHeldByCurrentThread()的作用是查询当前线程是否保持此锁定if(stockLock。isHeldByCurrentThread()){stockLock。unlock();}}returndoneCount;});futures。add(fsubmit);}IntegersaleToal0;for(inti0;ifutures。size();i){FutureIntegercountfutures。get(i);saleToalsaleToalcount。get();}System。out。println(最终的卖出:saleToal);}}
以上的核心代码为得到锁对象RLockstockLockredissonClient。getLock(stockLock);尝试获取锁if(stockLock。tryLock(1,1,TimeUnit。SECONDS))