思路:在 redis 中设置一个值表示加了锁,然后释放锁的时候就把这个 key 删除。

@SpringBootTest
public class Test2 {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private Redisson redisson;
    @Test
    void Test1(){
        String lockKey="produce-1";
        //防止中途宕机或者异常时出现的问题
        String clientId= UUID.randomUUID().toString();  
        try{
              Boolean redult=redisTemplate.opsForValue().setIfAbsent(lockKey,clientId,10, TimeUnit.SECONDS); 
              if(!redult){
                  System.out.println("系统繁忙!");
                  return;
              } 
            int goodsPrice= Integer.parseInt(redisTemplate.opsForValue().get("goodsPrice"));
            if (goodsPrice>100){
                redisTemplate.opsForValue().set("goodsPrice","100");
            }else {
                System.out.println("价格小于等于一百");
            } 
        }finally {
           if (clientId.equals(redisTemplate.opsForValue().get(lockKey))){
//            释放锁
               redisTemplate.delete("lockKey");
           }
        }
    }

}

使用redisson

@SpringBootTest
public class Test2 {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private Redisson redisson;
    @Test
    void Test1(){
        String lockKey="produce-1";
 
        RLock redissonLock=redisson.getLock(lockKey);
        try{
            redissonLock.lock(30, TimeUnit.SECONDS);
            int goodsPrice= Integer.parseInt(redisTemplate.opsForValue().get("goodsPrice"));
            if (goodsPrice>100){
                redisTemplate.opsForValue().set("goodsPrice","100");
            }else {
                System.out.println("价格小于等于一百");
            }
            goodsPrice= Integer.parseInt(redisTemplate.opsForValue().get("goodsPrice"));
            System.out.println(goodsPrice);
        }finally {
            redissonLock.unlock();
        }

    }

}

主要考虑问题:并发、宕机

解决方案:通过UUID来加标识,设置该值有效时间