redisson相比原生的jredis具有排队的功能,不一致秒杀时,一时获取锁失败就返回失败。 秒杀的原理就是使用redis的分布式锁的功能,保证每次抢购不会出现超卖的情况 1引入pomdependencygroupIdorg。redissongroupIdredissonartifactIdversion3。16。8versiondependency2完整代码及解析如下importcom。ruoyi。common。core。redis。RedisCimportorg。redisson。api。RLimportorg。redisson。api。RedissonCimportorg。springframework。beans。factory。annotation。Aimportorg。springframework。stereotype。Cimportjava。util。ArrayLimportjava。util。concurrent。;使用redisson来实现分布式的秒杀功能authorAdministratorComponentpublicclassReddisonTest{AutowiredprivateRedisCacheredisCAutowiredRedissonClientredissonC秒杀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);redisCache。setCacheObject(stock,stock);doneCisHeldByCurrentThread()的作用是查询当前线程是否保持此锁定if(stockLock。isHeldByCurrentThread()){stockLock。unlock();}}returndoneC});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))