redisson相比原生的jredis具有排队的功能,不一致秒杀时,一时获取锁失败就返回失败。
秒杀的原理就是使用redis的分布式锁的功能,保证每次抢购不会出现超卖的情况
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.16.8</version>
</dependency>
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
*
*/
@Component
public class ReddisonTest {
@Autowired
private RedisCache redisCache;
@Autowired
RedissonClient redissonClient;
/**
* 秒杀
* @throws ExecutionException
* @throws InterruptedException
*/
public void secondkill() throws ExecutionException, InterruptedException {
//加锁的实现方式
ExecutorService exec = Executors.newFixedThreadPool(50);
ArrayList<Future<Integer>> futures = new ArrayList<>();
RLock stockLock = redissonClient.getLock("stockLock");
for (int i = 0; i < 50; i++) {
Future<Integer> fsubmit = exec.submit(() -> {
int doneCount = 0;//初始化做的任务为0
if(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<Integer> count = futures.get(i);
saleToal = saleToal + count.get();
}
System.out.println("最终的卖出:"+saleToal);
}
}
以上的核心代码为
//得到锁对象
RLock stockLock = redissonClient.getLock("stockLock");
//尝试获取锁
if(numLock.tryLock(1,1,TimeUnit.SECONDS))