redis同步代码

<?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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容