Java Code Examples for redis.clients.jedis.Jedis#setnx()

The following examples show how to use redis.clients.jedis.Jedis#setnx() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LockTest.java    From code with Apache License 2.0 6 votes vote down vote up
public static boolean wrongGetLock2(Jedis jedis, String lockKey, int expireTime) {

        long expires = System.currentTimeMillis() + expireTime;
        String expiresStr = String.valueOf(expires);

        // 如果当前锁不存在,返回加锁成功
        if (jedis.setnx(lockKey, expiresStr) == 1) {
            return true;
        }

        // 如果锁存在,获取锁的过期时间
        String currentValueStr = jedis.get(lockKey);
        if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
            // 锁已过期,获取上一个锁的过期时间,并设置现在锁的过期时间
            String oldValueStr = jedis.getSet(lockKey, expiresStr);
            if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
                // 考虑多线程并发的情况,只有一个线程的设置值和当前值相同,它才有权利加锁
                return true;
            }
        }

        // 其他情况,一律返回加锁失败
        return false;

    }
 
Example 2
Source File: JedisUtil.java    From scaffold-cloud with MIT License 6 votes vote down vote up
/**
 * setnx
 *
 * @param key
 * @param value
 * @return
 */
public static Long setnx(String key, String value, int seconds) {
    Long result = 0L;
    Jedis jedis = null;
    try {
        jedis = getResource();
        result = jedis.setnx(key, value);
        if (seconds > 0) {
            jedis.expire(key, seconds);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        close(jedis);
    }
    return result;
}
 
Example 3
Source File: RedisCache.java    From framework with Apache License 2.0 6 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param key
 * @param value
 * @param expireTime
 * @return <br>
 */
@Override
public boolean setnx(final String key, final String value, final int expireTime) {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        if (jedis.setnx(key, value) - 1 == 0) {
            jedis.expire(key, expireTime);
            return true;
        }
    }
    finally {
        if (jedis != null) {
            jedis.close();
        }
    }
    return false;
}
 
Example 4
Source File: JLock.java    From spring-redis-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 获得锁,超时退出
 *
 * @param id
 * @param timeout 超时时间(ms)
 * @return
 */
public static boolean getLock(String id, long timeout) {
    Jedis jedis = JedisProxy.create();
    long lock = 0;
    long start = System.currentTimeMillis();
    long pexpire = timeout > 0 ? timeout : EXPIRE * 1000;
    while (lock != 1) {
        long now = System.currentTimeMillis();
        //判断超时
        if (timeout > 0 && now > start + timeout) {
            return false;
        }
        long timestamp = now + EXPIRE + 1;
        String key = String.format(LOCK, id);
        lock = jedis.setnx(key, String.valueOf(timestamp));
        if (lock == 1) {
            jedis.pexpire(key, pexpire);
            LOGGER.trace("redis lock setnx");
        } else {
            sleep();
        }
    }
    return true;
}
 
Example 5
Source File: RGTRedisService.java    From redis-game-transaction with Apache License 2.0 6 votes vote down vote up
/**
 * 设置
 * @param key
 * @param value
 * @return
 */
@Override
public boolean setNxString(String key, String value, int seconds) throws Exception{
    Jedis jedis = null;
    boolean success = true;
    boolean result = false;
    try {
        jedis = jedisPool.getResource();
        result = (jedis.setnx(key, value) != 0);
        if(seconds > -1){
            jedis.expire(key, seconds);
        }
    } catch (Exception e) {
        success = false;
        releasBrokenReidsSource(jedis, key, "setNxString", e, false);
        throw e;
    } finally {
        releaseReidsSource(success, jedis);
    }

    return result;

}
 
Example 6
Source File: JedisLock.java    From aaden-pay with Apache License 2.0 6 votes vote down vote up
/**
 * Acquire lock.
 * 
 * @param jedis
 * @return true if lock is acquired, false acquire timeouted
 * @throws InterruptedException
 *             in case of thread interruption
 */
public synchronized boolean acquire(Jedis jedis) throws InterruptedException {
	int timeout = timeoutMsecs * 1000;
	while (timeout >= 0) {
		if (jedis.setnx(lockKey, lockKey) == 1) {
			// lock acquired
			locked = Boolean.TRUE;
			jedis.setex(lockKey, expireMsecs, lockKey);
			return locked;
		}
		timeout -= 100;
		try {
			Thread.sleep(100);
		} catch (Exception e) {
		}
	}
	return false;
}
 
Example 7
Source File: RedisClient.java    From apollo with GNU General Public License v2.0 5 votes vote down vote up
/**
 * add if not exists
 *
 * @param key
 * @param value
 * @param expiration
 *
 * @return false if redis did not execute the option
 *
 * @throws Exception
 */
public boolean add(String key, Object value, Integer expiration) throws Exception {
    Jedis jedis = null;

    try {

        jedis = this.jedisPool.getResource();
        long begin = System.currentTimeMillis();
        // 操作setnx与expire成功返回1,失败返回0,仅当均返回1时,实际操作成功
        Long result = jedis.setnx(SafeEncoder.encode(key), serialize(value));
        if (expiration > 0) {
            result = result & jedis.expire(key, expiration);
        }
        long end = System.currentTimeMillis();
        if (result == 1L) {
            logger.info("add key:" + key + ", spends: " + (end - begin) + "ms");
        } else {
            logger.info("add key: " + key + " failed, key has already exists! ");
        }

        return result == 1L;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        this.jedisPool.returnBrokenResource(jedis);
        throw e;
    } finally {
        if (jedis != null) {
            this.jedisPool.returnResource(jedis);
        }
    }
}
 
Example 8
Source File: TransactionTest.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Jedis jedis = new Jedis("192.168.108.131", 7000);
    String userId = "abc";
    String key = keyFor(userId);
    jedis.setnx(key, String.valueOf(5)); // setnx 做初始化
    System.out.println(doubleAccount(jedis, userId));
    jedis.close();
}
 
Example 9
Source File: JedisLock.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
/**
 * Acquire lock.
 *
 * @param jedis
 * @return true if lock is acquired, false acquire timeouted
 * @throws InterruptedException in case of thread interruption
 */
protected synchronized boolean acquire(Jedis jedis) throws InterruptedException {
    int timeout = acquiryTimeoutInMillis;
    while (timeout >= 0) {

        final Lock newLock = asLock(System.currentTimeMillis() + lockExpiryInMillis);
        if (jedis.setnx(lockKeyPath, newLock.toString()) == 1) {
            this.lock = newLock;
            return true;
        }

        final String currentValueStr = jedis.get(lockKeyPath);
        final Lock currentLock = Lock.fromString(currentValueStr);
        if (currentLock.isExpiredOrMine(lockUUID)) {
            String oldValueStr = jedis.getSet(lockKeyPath, newLock.toString());
            if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
                this.lock = newLock;
                return true;
            }
        }

        timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
        Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);
    }

    return false;
}
 
Example 10
Source File: RedisLock.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public boolean acquire(Jedis jedis) {
    String value = jedis.get(lockKey);
    if (value == null) {
        boolean success = jedis.setnx(lockKey, lockValue) == 1;
        if (success) {
            jedis.expire(lockKey, expiredSeconds);
            return true;
        }
    } else if (lockValue.equals(value)) {
        jedis.expire(lockKey, expiredSeconds);
        return true;
    }
    return false;
}
 
Example 11
Source File: JLock.java    From spring-redis-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 检查锁是否存在,立刻返回
 *
 * @param id
 * @param timeout
 * @return
 */
public static boolean checkLock(String id, long timeout) {
    Jedis jedis = JedisProxy.create();
    String key = String.format(LOCK, id);
    long exists = jedis.setnx(key, String.valueOf(System.currentTimeMillis()));
    if (exists == 0) {
        return false;
    }
    jedis.pexpire(key, timeout);
    return true;
}
 
Example 12
Source File: RedisServiceImpl.java    From ace-cache with Apache License 2.0 5 votes vote down vote up
@Override
public Long setnx(String key, String value) {
    Jedis jedis = null;
    try {
        jedis = pool.getResource();
        return jedis.setnx(key, value);
    } catch (Exception e) {

        LOGGER.error(e.getMessage());
        return 0L;
    } finally {
        returnResource(pool, jedis);
    }
}
 
Example 13
Source File: RedisClient.java    From Mykit with Apache License 2.0 5 votes vote down vote up
public Long setnx(String key, String value) {
	Jedis client = jedisPool.getResource();
	try {
		Long result = client.setnx(key, value);
		System.out.println("setnx key=" + key + " value=" + value + "result=" + result);
		return result;
	} finally {
		// 向连接池“归还”资源
		jedisPool.returnResourceObject(client);
	}
}
 
Example 14
Source File: RedisPoolUtil.java    From redis-distributed-lock with Apache License 2.0 5 votes vote down vote up
public static Long setnx(String key, String value){
    Jedis jedis = null;
    Long result = null;
    try {
        jedis = RedisPool.getJedis();
        result = jedis.setnx(key, value);
    } catch (Exception e){
        e.printStackTrace();
    } finally {
        if (jedis != null) {
            jedis.close();
        }
        return result;
    }
}
 
Example 15
Source File: JedisUtil.java    From SpringBoot-Home with Apache License 2.0 5 votes vote down vote up
/**
 * 设值
 *
 * @param key
 * @param value
 * @return
 */
public Long setnx(String key, String value) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        return jedis.setnx(key, value);
    } catch (Exception e) {
        log.error("set key:{} value:{} error", key, value, e);
        return null;
    } finally {
        close(jedis);
    }
}
 
Example 16
Source File: JedisUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
/**
 * setnx
 *
 * @param key
 * @param value
 * @return
 */
public static Long setnx(String key, String value) {
    Long result = 0L;
    Jedis jedis = null;
    try {
        jedis = getResource();
        result = jedis.setnx(key, value);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        close(jedis);
    }
    return result;
}
 
Example 17
Source File: LockTest.java    From code with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试获取分布式锁
 * @param jedis Redis客户端
 * @param lockKey 锁
 * @param requestId 请求标识
 * @param expireTime 超期时间
 */
public static void wrongGetLock1(Jedis jedis, String lockKey, String requestId, int expireTime) {

    Long result = jedis.setnx(lockKey, requestId);
    if (result == 1) {
        // 若在这里程序突然崩溃,则无法设置过期时间,将发生死锁
        jedis.expire(lockKey, expireTime);
    }

}
 
Example 18
Source File: DefaultRedis.java    From craft-atom with MIT License 4 votes vote down vote up
private Long setnx0(Jedis j, String key, String value) {
	return j.setnx(key, value);
}
 
Example 19
Source File: JedisUtil.java    From BigData with GNU General Public License v3.0 3 votes vote down vote up
/**
 * 添加一条记录,仅当给定的key不存在时才插入
 * 
 * @param String
 *            key
 * @param String
 *            value
 * @return long 状态码,1插入成功且key不存在,0未插入,key存在
 * */
public long setnx(String key, String value) {
	Jedis jedis = getJedis();
	long str = jedis.setnx(key, value);
	returnJedis(jedis);
	return str;
}
 
Example 20
Source File: JedisUtil.java    From Project with Apache License 2.0 3 votes vote down vote up
/**
 * 添加一条记录,仅当给定的key不存在时才插入
 * 
 * @param  key
 * @param  value
 * @return long 状态码,1插入成功且key不存在,0未插入,key存在
 */
public long setnx(String key, String value) {
	Jedis jedis = getJedis();
	long str = jedis.setnx(key, value);
	jedis.close();
	return str;
}