redisson相比原生的jredis具有排队的功能,不一致秒杀时,一时获取锁失败就返回失败。
秒杀的原理就是使用redis的分布式锁的功能,保证每次抢购不会出现超卖的情况
1 引入pom
org.redissonredisson3.16.8
2 完整代码及解析如下
package htmdemo;import com.ruoyi.common.core.redis.RedisCache;import org.redisson.api.RLock;import org.redisson.api.RedissonClient;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.util.ArrayList;import java.util.concurrent.*;/** * 使用redisson来实现分布式的秒杀功能 * @author Administrator * */@Componentpublic class ReddisonTest {@Autowiredprivate RedisCache redisCache;@AutowiredRedissonClient redissonClient;/** * 秒杀 * @throws ExecutionException * @throws InterruptedException */public void secondkill() throws ExecutionException, InterruptedException { //加锁的实现方式ExecutorService exec = Executors.newFixedThreadPool(50);ArrayList futures = new ArrayList();RLock stockLock = redissonClient.getLock(“stockLock”);for (int i = 0; i {int doneCount = 0;//初始化做的任务为0if(numLock.tryLock(1,1,TimeUnit.SECONDS)){//获取到锁,则做业务/** * trylock(param1,param2,param3):尝试获取锁 * @param1:等待时间(在这个时间内不停获取锁) * @param2:获取成功后锁的有效时间 * @param3:时间单位(秒/分/…)*/int stock = redisCache.getCacheObject(“stock”);stock–;redisCache.setCacheObject(“stock”, stock);doneCount++;//isHeldByCurrentThread()的作用是查询当前线程是否保持此锁定if(numLock.isHeldByCurrentThread()){numLock.unlock();}}return doneCount;});futures.add(fsubmit);}Integer saleToal = 0;for (int i = 0; i < futures.size(); i++) {Future count = futures.get(i);saleToal = saleToal + count.get();}System.out.println("最终的卖出:"+saleToal);}}
以上的核心代码为
//得到锁对象RLock stockLock = redissonClient.getLock(“stockLock”);//尝试获取锁if(numLock.tryLock(1,1,TimeUnit.SECONDS))