美文网首页
redis同步代码

redis同步代码

作者: camlboy | 来源:发表于2017-08-14 16:28 被阅读40次
    <?php  
    header("content-type:text/html;charset=utf-8");  
    $redis = new redis();  
    $result = $redis->connect('10.10.10.119', 6379);  
    $mywatchkey = $redis->get("mywatchkey");  
    $rob_total = 100;   //抢购数量  
    if($mywatchkey<$rob_total){  
        $redis->watch("mywatchkey");  
        $redis->multi();  
          
        //设置延迟,方便测试效果。  
        sleep(5);  
        //插入抢购数据  
        $redis->hSet("mywatchlist","user_id_".mt_rand(1, 9999),time());  
        $redis->set("mywatchkey",$mywatchkey+1);  
        $rob_result = $redis->exec();  
        if($rob_result){  
            $mywatchlist = $redis->hGetAll("mywatchlist");  
            echo "抢购成功!<br/>";  
            echo "剩余数量:".($rob_total-$mywatchkey-1)."<br/>";  
            echo "用户列表:<pre>";  
            var_dump($mywatchlist);  
        }else{  
            echo "手气不好,再抢购!";exit;  
        }  
    }  
    private StringRedisTemplate stringRedisTemplate;
    public static ThreadLocal<String> holder = new ThreadLocal<>();
    
    public Boolean setConcurrentLock(String key, long expireTime) throws InterruptedException {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        while (!ops.setIfAbsent(key, String.valueOf(System.currentTimeMillis() + expireTime))) {
            stringRedisTemplate.watch(key);
            Long expire = Long.parseLong(ops.get(key));
            if (expire != null && expire < System.currentTimeMillis()) {
                stringRedisTemplate.multi();
                Long oldExpire = Long.parseLong(ops.getAndSet(key, String.valueOf(System.currentTimeMillis() + expireTime)));
                if (stringRedisTemplate.exec() != null && oldExpire != null && oldExpire < System.currentTimeMillis()) {
                    break;
                }
            } else {
                stringRedisTemplate.unwatch();
            }
            TimeUnit.MILLISECONDS.sleep(3);
        }
        holder.set(ops.get(key));
        return true;
    }
    
    public void deleteConcurrentLock(String key) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        Long expire = Long.valueOf(ops.get(key));
        if(exprie.equals(holder.get())){
            stringRedisTemplate.delete(key);
        }
        holder.remove();
    }
    ```http://blog.csdn.net/u012116196/article/details/51782934

    相关文章

      网友评论

          本文标题:redis同步代码

          本文链接:https://www.haomeiwen.com/subject/kbiurxtx.html