zoukankan      html  css  js  c++  java
  • 分布式锁

    一: 使用redis:

        @PostMapping("/v1/getLock2")
        public  BaseResponse  getLock2(@RequestBody GxyTeacherInfoDto dto) throws  Exception{
            String key = "product_001";
            String lockvalue = UUID.randomUUID().toString();
            Boolean bool = stringRedisTemplate.opsForValue().setIfAbsent(key,lockvalue,10,TimeUnit.SECONDS);
            if(!bool) {
                System.out.println("err");
                return BaseResponse.error();
            }
            try {
                int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
                if (stock > 0) {
                    int realStock = stock - 1;
                    stringRedisTemplate.opsForValue().set("stock",realStock+"");
                    System.out.println("售卖成功,剩余" + realStock);
                    return BaseResponse.ok();
                } else {
                    System.out.println("err2");
                    return BaseResponse.error();
                }
            } finally {
                if(lockvalue.equals(stringRedisTemplate.opsForValue().get(key))) {
                    stringRedisTemplate.delete(key);
                }
            }
    
    
        }

    二: 使用Redisson:

    @Bean
    public Redisson redisson(){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://IP:port");
        return (Redisson)Redisson.create(config);
    }

        @PostMapping("/v1/getLock3")
        public  BaseResponse  getLock3(@RequestBody GxyTeacherInfoDto dto) throws  Exception{
            String lockKey = "product_001";
            RLock redissonLock = redisson.getLock(lockKey);
            try {
                int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
                if (stock > 0) {
                    int realStock = stock - 1;
                    stringRedisTemplate.opsForValue().set("stock",realStock+"");
                    System.out.println("售卖成功,剩余" + realStock);
                    return BaseResponse.ok();
                } else {
                    System.out.println("err2");
                    return BaseResponse.error();
                }
            } finally {
                redissonLock.unlock();
            }
        }
    
    
  • 相关阅读:
    项目部署
    nginx
    IDEA中Lombok插件的安装与使用
    Git常用命令总结
    CentOS 7 NAT模式上网配置
    一名3年工作经验的java程序员应该具备的技能
    maven 项目加载本地JAR
    linux压缩(解压缩)命令详解
    jdk7与jdk8环境共存与切换
    linux服务器卸载本机默认安装的jdk
  • 原文地址:https://www.cnblogs.com/z360519549/p/12499050.html
Copyright © 2011-2022 走看看