使用Redis实现分布式锁

以下是使用Redis在高并发下实现的一把分布式锁示例,直接上代码,两种方式:

实现方式一:直接用Redis当分布式锁

@RequestMapping("/deduct_stock")
    public String getbykey(String key) {
        String lockKey = "product" + key;
        String uuid = UUID.randomUUID().toString();
        //最简单的分布式锁
        Boolean locked = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, uuid,30,TimeUnit.SECONDS);
        if(!locked){
            return "error_code";
        }
        try{
            synchronized (this) {
                String result = stringRedisTemplate.opsForValue().get(key);
                if (StringUtils.hasLength(result)) {
                    int number = Integer.parseInt(result);
                    if (number > 0) {
                        number--;
                        stringRedisTemplate.opsForValue().set("stock", number + "");
                        System.out.println("库存为:" + number);
                    }else{
                        System.out.println("库存不足");
                    }
                }
                return result;
            }
        }finally {
            if(uuid.equals(stringRedisTemplate.opsForValue().get(lockKey))) {
                stringRedisTemplate.delete(lockKey);
            }
        }

    }

 

实现方式二:使用Redisson插件

1、引入依赖:

  <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.6.5</version>
        </dependency>

2、初始化配置bean

Component
@Configuration
public class ApplicationConfig {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public Redisson getRedisson() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + redisHost + ":" + port).setPassword(password);

        return (Redisson) Redisson.create(config);
    }
}

3、使用

        String lockKey = "product" + key;
        RLock redissonLock = redisson.getLock(lockKey);

        redissonLock.lock();

        try{
            synchronized (this) {
                String result = stringRedisTemplate.opsForValue().get(key);
                if (StringUtils.hasLength(result)) {
                    int number = Integer.parseInt(result);
                    if (number > 0) {
                        number--;
                        stringRedisTemplate.opsForValue().set("stock", number + "");
                        System.out.println("库存为:" + number);
                    }else{
                        System.out.println("库存不足");
                    }
                }
                return result;
            }
        }finally {
            redissonLock.unlock();
        }

 4、Redisson分布式锁原理

 

posted @ 2022-06-20 21:26  明&天  阅读(635)  评论(0编辑  收藏  举报