基于reidsson 的分布式锁
package com.me.redis_lock.controller;
import cn.hutool.core.collection.CollectionUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisClientConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@RestController
public class IndexController {
@Autowired
RedisTemplate redisTemplate;
private static final String GOODS="GOODS";
private static final String LOCK="LOCK";
@Autowired
private RedissonClient redissonClient;
@GetMapping("goods")
/**
* redissonClient 分布式锁
* 内置看门狗机制
* 实现 锁的续期
*/
public String buyGoods(){
RLock lock = redissonClient.getLock("LOCK");
try {
System.out.println("加锁");
lock.lock();
String string = (String) redisTemplate.opsForValue().get(GOODS);
// 库存
int goodCount =0;
if (!StringUtils.isEmpty(string)){
goodCount = Integer.parseInt(string);
}
if (goodCount>0){
// 购买
int realCount = goodCount -1;
redisTemplate.opsForValue().set(GOODS,realCount+"");
String stre =Thread.currentThread().getId()+"成功购买到商品,库存剩余"+realCount+"件";
System.out.println(stre);
return stre;
}else{
System.out.println("商品已售完");
return "商品已售完";
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (lock.isLocked()){
if(lock.isHeldByCurrentThread()){
lock.unlock();
}
}
}
return "";
}基于redis + lua 脚本实现的
package com.me.redis_lock.controller;
import cn.hutool.core.collection.CollectionUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisClientConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@RestController
public class IndexController {
@Autowired
RedisTemplate redisTemplate;
private static final String GOODS="GOODS";
private static final String LOCK="LOCK";
/**
* redis 版本 分布式锁 setnx 不存在则设置成功 否则失败
*/
@GetMapping("goods2")
public String buyGoods2(){
String uuid =UUID.randomUUID().toString();
try {
// 分布式锁 实现 确保设置超时时间和 设置操作的原子性 时间需要根据业务实际设置
Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(LOCK, uuid, 1, TimeUnit.SECONDS);
if (!aBoolean){
System.out.println("未获得锁");
return "未获得锁";
}
// 获取库存
String string = (String) redisTemplate.opsForValue().get(GOODS);
// 库存 大于0
int goodCount =0;
if (!StringUtils.isEmpty(string)){
goodCount = Integer.parseInt(string);
}
if (goodCount>0){
// 购买 库存减1
int realCount = goodCount -1;
redisTemplate.opsForValue().set(GOODS,realCount+"");
String stre ="成功购买到商品,库存剩余"+realCount+"件";
System.out.println(stre);
return stre;
}else{
System.out.println("商品已售完");
return "商品已售完";
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 只能删除该线程申请的锁 避免误删 其他线程的 锁
// if (redisTemplate.opsForValue().get(LOCK).equals(uuid)){
// redisTemplate.delete(LOCK);
// }
// while (true){
// redisTemplate.watch(LOCK);
// if (uuid.equals(redisTemplate.opsForValue().get(LOCK))){
// redisTemplate.setEnableTransactionSupport(true);
// redisTemplate.multi();
// redisTemplate.delete(LOCK);
// List<Object> exec = redisTemplate.exec();
// if (exec ==null){
// continue;
// }
// }
// redisTemplate.unwatch();
// break;
// }
// lua 脚本 保证原子性
String sc="if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
"then\n" +
" return redis.call(\"del\",KEYS[1])\n" +
"else\n" +
" return 0\n" +
"end";
DefaultRedisScript script = new DefaultRedisScript(sc,Long.class);
List<String > keys = CollectionUtil.newArrayList(LOCK);
List<String > args = CollectionUtil.newArrayList(uuid);
Object execute = redisTemplate.opsForValue().getOperations().execute(script, keys,uuid);
if (execute!=null ){
System.out.println("execute:"+execute);
}else{
System.out.println("解锁失败");
}
// lock.unlock();
}
return "";
}
}if redis.call("get",KEYS[1]) == ARGV[1]
then
return redis.call("del",KEYS[1])
else
return 0
end基于redis sortedset 实现延时任务 springboot
cccc基于 Redis 实现延时任务有以下缺点: 精度有限:Redis 的延迟任务依赖于系统的定时检查机制,而不是精确的定时器,任务执行可能存在延迟,系统负载高或检查间隔长时延迟更明显。 功能有限:相比专业任务调度系统,Redis 提供的延迟任务功能较简单,对于复杂需求,如任务依赖、优先级等,需额外逻辑实现。 稳定性较差:Redis 实现延迟任务缺乏重试机制和 ACK 确认机制,任务执行失败后无法自动重试,任务可能丢失或重复执行,且 Redis 服务器故障时,未处理任务会丢失。 单点故障风险:若未正确配置 Redis 集群或主从复制,单个 Redis 实例故障可能导致整个延迟任务系统瘫痪。 无序性问题:Redis 延迟队列是一个无序队列,多个任务同时到期时,无法保证任务的处理顺序,可能导致任务乱序执行。 容量受限:Redis 的容量受限于单机内存大小,当延迟队列中任务数量过大时,可能导致 Redis 内存溢出,造成队列阻塞或服务不可用。 缺乏监控管理功能:Redis 延迟队列本身缺乏对任务的监控和管理功能,无法统计队列中任务数量、处理速度等信息,也无法对任务进行重新派发或删除等操作。 数据丢失风险:Redis 是内存数据库,数据存储在内存中,若 Redis 服务器发生故障或重启,且未开启持久化或持久化配置不当,延迟队列中的任务可能丢失。 过期策略问题:使用 Redis 过期事件监听实现延时任务时,由于 Redis 的惰性删除和定期删除机制,可能存在 key 过期但事件未触发的情况,导致任务延迟执行。 消息重复消费:在多服务实例下,使用 Redis 的 pub/sub 模式实现延时任务时,可能存在消息重复消费的问题,增加代码开发量和维护难度。 性能瓶颈:当延迟任务量较大时,使用 ZRANGEBYSCORE 等命令可能会导致性能瓶颈,影响任务的及时处理。