国产毛多水多高潮高清,久热这里只有精品视频6,国内精品久久久久久久久电影网,国产男同志CHINA69,精品999日本久久久影院,人人妻人人澡人人爽人人精品,亚洲中文无码永久免

使用redisson实现分布式秒杀功能-网上做网赌辅助软件的

使用redisson实现分布式秒杀功能

2026-01-17 13:06:57投稿人:手機(jī)上賭錢的軟件有哪些(巢湖)有限公司圍觀5524963 評(píng)論

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

redisson相比原生的jredis具有排隊(duì)的功能 ,不一致秒殺時(shí),一時(shí)獲取鎖失敗就返回失敗。

秒殺的原理就是使用redis的分布式鎖的功能 ,保證每次搶購不會(huì)出現(xiàn)超賣的情況


1 引入pom

org.redissonredisson            3.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來實(shí)現(xiàn)分布式的秒殺功能 * @author Administrator * */@Componentpublic class ReddisonTest { 	@Autowired    private RedisCache redisCache;    @Autowired    RedissonClient 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 < 50; i++) {             Futurefsubmit = exec.submit(() ->{                 int doneCount = 0;//初始化做的任務(wù)為0                if(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++) {             Futurecount = futures.get(i);            saleToal = saleToal + count.get();        }        System.out.println("最終的賣出:"+saleToal);    }}


以上的核心代碼為

//得到鎖對(duì)象RLock stockLock = redissonClient.getLock("stockLock");//嘗試獲取鎖if(numLock.tryLock(1,1,TimeUnit.SECONDS))
展開閱讀全文

投稿時(shí)間:2022-09-04  最后更新 :2022-09-04