redis分布式锁实现n台服务器跑定时任务,确保只有一台服务器运行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25958497/article/details/82630818

1,redis分布式锁 setnx方法实现原子操作,确保并发安全

    setnx(key,v);   //只用到key  value用key值即可
        不存在 返回 1
        存在    返回 0

    expire(key,seconds);seconds是过期时间 单位 秒
查询过期时间
ttl key 
    返回-1        key未设置过期时间
    返回-2        key已过期
    返回正数    则是过期时间 秒

2,我使用redis分布式锁的基本思路

1 任务运行  执行setnx 如返回1后,设置key过期间,(为了确保下次正常运行),然后再执行任务!
2 各个服务器时间必须一致,确保并发安全! 根据业务需要设置过期时间!
例如定时任务(设置过期的时间>大于服务器误差时间即可)
3 为什么不用del(k);? 以防删除失败!导致任务下次无法运行

示例代码

/**
     * redis 实现原子操作 不存在1 存在0
     * 
     * @param key
     * @param value
     * @return
     */
    public static int setnx(String key,String value) {
        Jedis jedis = null;
        try {
            jedis = ConnectionManager.getConnection();
            int j=jedis.setnx(key, value).intValue();
            //添加key成功 设置过期时间
            if(j==1){
                int seconds=59;
                jedis.expire(key, seconds);
            }else{
                //没有设置过期时间 会返回-1 del掉
                Long lt=jedis.ttl(key);
                if(lt==-1){
                    jedis.del(key);
                }

            }
            return j;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ConnectionManager.closeConnection(jedis);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/qq_25958497/article/details/82630818
今日推荐