Redisson分布式锁

本文介绍了如何使用Redisson分布式锁防止缓存击穿和处理多用户扣减库存的场景,并通过AOP封装加锁逻辑,实现注解驱动的分布式锁管理。
摘要由CSDN通过智能技术生成

Redisson分布式锁+AOP

1. Redisson分布式锁的简单使用

1.1 防止缓存击穿

假如系统中的某个资源获取非常活跃,即使加了Redis缓存,在缓存失效的一瞬间,大量的请求会打进数据库,这时可能会导致数据库线程资源打满,严重情况下可能会宕机,这种情况下在重建缓存的时候需要加分布式锁 (理论上 synchronized 级别的锁也可以解决,这样重建缓存的线程就等于当前服务实例的个数)。

/**
 * @author wangxun
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户Controller")
public class UserController extends BaseController {
   
    // 自定义的,为了实现动态修改缓存的失效时间
    @Autowired
    private RedisKeyProperties redisKeyProperties;
    // RedisTemplate.opsForValue()
    @Autowired
    private ValueOperations<String, Object> valueOperations;
	// RedissonClient
    @Autowired
    private RedissonClient redissonClient;
	// com.github.benmanes.caffeine.cache.Caffeine 的本地缓存
    @Autowired
    private Cache<String, User> localCache;

    @PostMapping("/getById/{id}")
    public Result<User> getById(@PathVariable Long id) throws InterruptedException {
   
        return success(getById01(id));
//        return success(getById02(id));
//        return success(getById03(id));
//        return success(getById04(id));
    }

    // 伪代码,代码没有规范化
    private User getById01(Long id) {
   
        String redisKey = redisKeyProperties.getUser().getRedisKey().replace("{id}", id.toString());
        // TODO: 一级缓存中获取
        User user = localCache.getIfPresent(redisKey);
        if (Objects.nonNull(user)) {
   
            return user;
        }

        // TODO: 二级缓存中获取
        user = (User) valueOperations.get(redisKey);
        if (Objects
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值