Java分布式集群,使用synchronized和Redis保证Job的原子性

1.使用synchronized保证并发时,同时只会有一个请求执行该代码段;

2.在执行前先设置并获取Reids标记,先设置然后获取确保是否已经执行;SetOption.SET_IF_ABSENT 可以保证Reids如果存在Key的话就不再Set;

 

public synchronized static boolean isWorking(final String keyLock, final String uuidValue,long seconds){
        
        if(null == keyLock || uuidValue == null) {
            return false;
        }
        RedisConnection redisConnection = null;
        try {
            JedisConnectionFactory jedisConnectionFactory = ac.getBean("jedisConnectionFactory", JedisConnectionFactory.class);
            StringRedisTemplate redisTemplate = new StringRedisTemplate(jedisConnectionFactory);
            String value = System.currentTimeMillis() + "::" + uuidValue;
            logger.info("{} 尝试获取锁: {}, value:{}", ip, keyLock, value);
            //必须设置和过期同时执行
            redisConnection = redisTemplate.getConnectionFactory().getConnection();
            redisConnection.set(keyLock.getBytes(),
                    value.getBytes(), Expiration.seconds(seconds), SetOption.SET_IF_ABSENT);
            
            if(value.equals(redisTemplate.opsForValue().get(keyLock))){
                logger.info("{} 成功获取锁: {}, value:{}", ip, keyLock, value);
                return true;
            }
            logger.info("{} 无法获取锁: {}, value:{}", ip, keyLock, value);
            return false;
        }catch(Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }finally {
            if(null != redisConnection) {
                redisConnection.close();
            }
        }
        
    }

 

posted @ 2018-05-09 10:55 Bodi 阅读(...) 评论(...) 编辑 收藏