redis控制业务多线程并发是否重复
注意: 如果执行时间超过redis的过期时间就会出现误删后面需要单独处理
public void main(String[] args) {
//背景需求 每个人同时只能对商品操作一次(多线程并发的场景),使用redis锁进行锁处理 防止同一个多次请求 这里面的redis是老版本没有用新的
//模拟不同人
String personID = UUID.randomUUID().toString();
// 模拟不同商品
String goodId = UUID.randomUUID().toString();
//拼接为唯一业务员
String uniqueKey = personID.concat("-").concat(goodId);
try {
//redis 存储 如果已经存在则false
Boolean isTrue = redisLockByKeyExist(uniqueKey, "", 5000);
while (!isTrue){
//设置等待时间 轮训等待时间
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(300));
//重新尝试加锁
isTrue = redisLockByKeyExist(uniqueKey, "", 5000);
}
//处理业务
doSomeThinking();
}catch (Exception e){
log.error("====业务执行失败,失败业务key:{},原因:{}====",uniqueKey,e.getMessage());
} finally {
//解锁
delKey(uniqueKey);
}
}
private void doSomeThinking() {
System.out.println("哈哈");
}
public Boolean redisLockByKeyExist(String lockName, String lockValue, Integer expireSecs) {
//redis连接过程不做演示
Jedis jedis = getJedis();
try {
String lockResult = jedis.set(lockName, lockValue, "NX", "EX", expireSecs);
log.error("=====redis存入锁名称{}====,结果{}",lockName,lockResult);
if (ApiCodeEnum.SUCCESS.getMsgCode().startsWith(lockResult)){
return true;
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
returnResource(jedis);
}
return false;
}
public void delKey(String key) {
Jedis jedis = getJedis();
try {
jedis.del(key);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
//关闭redis连接 不做演示
returnResource(jedis);
}
}



