redisson相比原生的jredis具有排隊(duì)的功能,不一致秒殺時(shí),一時(shí)獲取鎖失敗就返回失敗。
秒殺的原理就是使用redis的分布式鎖的功能,保證每次搶購(gòu)不會(huì)出現(xiàn)超賣(mài)的情況
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來(lái)實(shí)現(xiàn)分布式的秒殺功能 * @author Administrator * */@Componentpublic class ReddisonTest {@Autowiredprivate RedisCache redisCache;@AutowiredRedissonClient redissonClient;/** * 秒殺 * @throws ExecutionException * @throws InterruptedException */public void secondkill() throws ExecutionException, InterruptedException { //加鎖的實(shí)現(xiàn)方式ExecutorService exec = Executors.newFixedThreadPool(50);ArrayList futures = new ArrayList();RLock stockLock = redissonClient.getLock(“stockLock”);for (int i = 0; i {int doneCount = 0;//初始化做的任務(wù)為0if(numLock.tryLock(1,1,TimeUnit.SECONDS)){//獲取到鎖,則做業(yè)務(wù)/** * trylock(param1,param2,param3):嘗試獲取鎖 * @param1:等待時(shí)間(在這個(gè)時(shí)間內(nèi)不停獲取鎖) * @param2:獲取成功后鎖的有效時(shí)間 * @param3:時(shí)間單位(秒/分/…)*/int stock = redisCache.getCacheObject(“stock”);stock–;redisCache.setCacheObject(“stock”, stock);doneCount++;//isHeldByCurrentThread()的作用是查詢當(dāng)前線程是否保持此鎖定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("最終的賣(mài)出:"+saleToal);}}
以上的核心代碼為
//得到鎖對(duì)象RLock stockLock = redissonClient.getLock(“stockLock”);//嘗試獲取鎖if(numLock.tryLock(1,1,TimeUnit.SECONDS))