在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    使用redisson實(shí)現(xiàn)分布式秒殺功能

    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))

    鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場(chǎng),版權(quán)歸原作者所有,如有侵權(quán)請(qǐng)聯(lián)系管理員(admin#wlmqw.com)刪除。
    上一篇 2022年9月4日 15:05
    下一篇 2022年9月4日 15:05

    相關(guān)推薦

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時(shí)間:周一至周五,10:30-18:30,節(jié)假日休息