org.springframework.data.redis.core.types.Expiration Java Examples

The following examples show how to use org.springframework.data.redis.core.types.Expiration. 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: RedissonConnection.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public void set(byte[] key, byte[] value, Expiration expiration, SetOption option) {
    if (expiration == null) {
        set(key, value);
    } else if (expiration.isPersistent()) {
        if (option == null || option == SetOption.UPSERT) {
            set(key, value);
        }
        if (option == SetOption.SET_IF_ABSENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "XX");
        }
    } else {
        if (option == null || option == SetOption.UPSERT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds());
        }
        if (option == SetOption.SET_IF_ABSENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "XX");
        }
    }
}
 
Example #2
Source File: RedisLockProvider.java    From ShedLock with Apache License 2.0 6 votes vote down vote up
@Override
public void unlock() {
    Expiration keepLockFor = getExpiration(lockConfiguration.getLockAtLeastUntil());
    RedisConnection redisConnection = null;
    // lock at least until is in the past
    if (keepLockFor.getExpirationTimeInMilliseconds() <= 0) {
        try {
            redisConnection = redisConnectionFactory.getConnection();
            redisConnection.del(key.getBytes());
        } catch (Exception e) {
            throw new LockException("Can not remove node", e);
        } finally {
            close(redisConnection);
        }
    } else {
        try {
            redisConnection = redisConnectionFactory.getConnection();
            redisConnection.set(key.getBytes(), buildValue(lockConfiguration.getLockAtMostUntil()), keepLockFor, SetOption.SET_IF_PRESENT);
        } finally {
            close(redisConnection);
        }
    }
}
 
Example #3
Source File: SpringRedisLock.java    From AutoLoadCache with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean setnx(String key, String val, int expire) {
    if (null == redisConnectionFactory || null == key || key.isEmpty()) {
        return false;
    }
    RedisConnection redisConnection = getConnection();
    try {
        Expiration expiration = Expiration.from(expire, TimeUnit.SECONDS);
        return redisConnection.stringCommands().set(STRING_SERIALIZER.serialize(key), STRING_SERIALIZER.serialize(val), expiration, RedisStringCommands.SetOption.SET_IF_ABSENT);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    } finally {
        RedisConnectionUtils.releaseConnection(redisConnection, redisConnectionFactory);
    }
    return false;
}
 
Example #4
Source File: RedisLeaderManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void electLeader()
{
    log.debug( "Election attempt by nodeId:" + this.nodeId );
    redisTemplate.getConnectionFactory().getConnection().set( key.getBytes(), nodeId.getBytes(),
        Expiration.from( timeToLiveSeconds, TimeUnit.SECONDS ), SetOption.SET_IF_ABSENT );
    if ( isLeader() )
    {
        renewLeader();
        Calendar calendar = Calendar.getInstance();
        calendar.add( Calendar.SECOND, (int) (this.timeToLiveSeconds / 2) );
        log.debug( "Next leader renewal job nodeId:" + this.nodeId + " set at " + calendar.getTime().toString() );
        JobConfiguration leaderRenewalJobConfiguration = new JobConfiguration( CLUSTER_LEADER_RENEWAL,
            JobType.LEADER_RENEWAL, null, true );
        leaderRenewalJobConfiguration.setLeaderOnlyJob( true );
        schedulingManager.scheduleJobWithStartTime( leaderRenewalJobConfiguration, calendar.getTime() );
    }
}
 
Example #5
Source File: RedissonConnection.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public void set(byte[] key, byte[] value, Expiration expiration, SetOption option) {
    if (expiration == null) {
        set(key, value);
    } else if (expiration.isPersistent()) {
        if (option == null || option == SetOption.UPSERT) {
            set(key, value);
        }
        if (option == SetOption.SET_IF_ABSENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "XX");
        }
    } else {
        if (option == null || option == SetOption.UPSERT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds());
        }
        if (option == SetOption.SET_IF_ABSENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            write(key, StringCodec.INSTANCE, RedisCommands.SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "XX");
        }
    }
}
 
Example #6
Source File: RedisSpringDataCache.java    From jetcache with Apache License 2.0 6 votes vote down vote up
@Override
protected CacheResult do_PUT_IF_ABSENT(K key, V value, long expireAfterWrite, TimeUnit timeUnit) {
    RedisConnection con = null;
    try {
        con = connectionFactory.getConnection();
        CacheValueHolder<V> holder = new CacheValueHolder(value, timeUnit.toMillis(expireAfterWrite));
        byte[] newKey = buildKey(key);
        Boolean result = con.set(newKey, valueEncoder.apply(holder),
               Expiration.from(expireAfterWrite, timeUnit), RedisStringCommands.SetOption.ifAbsent());
        if (Boolean.TRUE.equals(result)) {
            return CacheResult.SUCCESS_WITHOUT_MSG;
        }/* else if (result == null) {
            return CacheResult.EXISTS_WITHOUT_MSG;
        } */ else {
            return CacheResult.EXISTS_WITHOUT_MSG;
        }
    } catch (Exception ex) {
        logError("PUT_IF_ABSENT", key, ex);
        return new CacheResult(ex);
    } finally {
        closeConnection(con);
    }
}
 
Example #7
Source File: DefaultRedisCacheWriter.java    From api-gateway-old with Apache License 2.0 6 votes vote down vote up
/**
 * (non-Javadoc)
 *
 * @see org.springframework.data.redis.cache.RedisCacheWriter#put(java.lang.String, byte[], byte[], java.time.Duration)
 */
@Override
public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {

    Assert.notNull(name, "Name must not be null!");
    Assert.notNull(key, "Key must not be null!");
    Assert.notNull(value, "Value must not be null!");

    execute(name, connection -> {

        if (shouldExpireWithin(ttl)) {
            connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
        } else {
            connection.set(key, value);
        }

        return "OK";
    });
}
 
Example #8
Source File: RedisService.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * getLock(分布式锁-正确方式)
 *
 * @param key        锁标识
 * @param requestId  请求唯一标识,解锁需要带入
 * @param expireTime 自动释放锁的时间
 */
@RequestMapping("getLock")
public Long getLock(String key, String requestId, long expireTime) {
    Long result = -1L;
    if (StringUtil.isBlank(key)) {
        return result;
    }
    if (StringUtil.isBlank(requestId)) {
        return result;
    }
    RedisConnection conn = getRedisConnection();
    if (conn == null) {
        return result;
    }
    try {
        boolean ret = conn.set(key.getBytes(Charset.forName("UTF-8")), requestId.getBytes(Charset.forName("UTF-8")), Expiration.milliseconds(expireTime), RedisStringCommands.SetOption.SET_IF_ABSENT);
        if (ret) {
            result = 1L;
        }
    } catch (Exception e) {
        logger.error("getRedisLock(取分布式锁-正确方式)异常={}", StringUtil.getExceptionMsg(e));
    }
    return result;
}
 
Example #9
Source File: RedisService.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * saveCache:(设置缓存-带有效期)
 *
 * @param key
 * @param value
 * @param seconds 有效时间 单位(秒)
 * @return
 * @author rufei.cn
 */
@RequestMapping("save")
public long saveCache(String key, String value, long seconds) {
    logger.info("save:(设置缓存-带有效期) 开始 key={},seconds={}", key, seconds);
    long result = -1;
    if (StringUtil.isBlank(key)) {
        return result;
    }
    RedisConnection conn = getRedisConnection();
    if (conn == null) {
        return result;
    }
    try {
        Boolean ret = conn.set(key.getBytes(), value.getBytes(), Expiration.seconds(seconds), RedisStringCommands.SetOption.UPSERT);
        if (ret) {
            result = 1L;
        }
    } catch (Exception e) {
        logger.error("saveCache:" + StringUtil.getExceptionMsg(e));
    }
    logger.info("saveCache:(设置缓存-带有效期) 结束 key={},result={}", key, result);
    return result;
}
 
Example #10
Source File: DefaultRedisCacheWriter.java    From gateway-helper with Apache License 2.0 6 votes vote down vote up
@Override
public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {

    Assert.notNull(name, "Name must not be null!");
    Assert.notNull(key, "Key must not be null!");
    Assert.notNull(value, "Value must not be null!");

    execute(name, connection -> {

        if (shouldExpireWithin(ttl)) {
            connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
        } else {
            connection.set(key, value);
        }

        return "OK";
    });
}
 
Example #11
Source File: RedisDistributedLock.java    From SpringBoot2.0 with Apache License 2.0 6 votes vote down vote up
private boolean setRedis(final String key, final long expire) {
    try {
        boolean status = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            String uuid = UUID.randomUUID().toString();
            lockFlag.set(uuid);
            byte[] keyByte = redisTemplate.getStringSerializer().serialize(key);
            byte[] uuidByte = redisTemplate.getStringSerializer().serialize(uuid);
            boolean result = connection.set(keyByte, uuidByte, Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.ifAbsent());
            return result;
        });
        return status;
    } catch (Exception e) {
        log.error("set redisDistributeLock occured an exception", e);
    }
    return false;
}
 
Example #12
Source File: DefaultRedisCacheWriter.java    From black-shop with Apache License 2.0 6 votes vote down vote up
@Override
public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {

	Assert.notNull(name, "Name must not be null!");
	Assert.notNull(key, "Key must not be null!");
	Assert.notNull(value, "Value must not be null!");

	execute(name, connection -> {

		if (shouldExpireWithin(ttl)) {
			connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
		} else {
			connection.set(key, value);
		}

		return "OK";
	});
}
 
Example #13
Source File: CustomRedisCacheWriter.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
@Override
public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {

    Assert.notNull(name, "Name must not be null!");
    Assert.notNull(key, "Key must not be null!");
    Assert.notNull(value, "Value must not be null!");

    execute(name, connection -> {

        if (shouldExpireWithin(ttl)) {
            connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
        } else {
            connection.set(key, value);
        }

        return "OK";
    });
}
 
Example #14
Source File: RedisDistributedLock.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
private boolean setRedis(final String key, final long expire) {
    try {
        boolean status = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            String uuid = UUID.randomUUID().toString();
            lockFlag.set(uuid);
            byte[] keyByte = redisTemplate.getStringSerializer().serialize(key);
            byte[] uuidByte = redisTemplate.getStringSerializer().serialize(uuid);
            boolean result = connection.set(keyByte, uuidByte, Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.ifAbsent());
            return result;
        });
        return status;
    } catch (Exception e) {
        log.error("set redisDistributeLock occured an exception", e);
    }
    return false;
}
 
Example #15
Source File: AbstractRedisUtil.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
public boolean setIfAbsent(final String key, Object value, Long expireTime) {
        String json = toJSONString(value);

        Boolean result = redisTemplate.execute(connection ->
                        connection.set(rawStr(formatKey(key)),
                                rawStr(json),
                                Expiration.from(expireTime, TimeUnit.MILLISECONDS),
                                RedisStringCommands.SetOption.SET_IF_ABSENT),
                true);
        return result == null ? false : result;

//        if (redisTemplate.opsForValue().setIfAbsent(formatKey(key), json)) {
//            expire(key, expireTime, TimeUnit.MILLISECONDS);
//            return true;
//        } else {
//            return false;
//        }
    }
 
Example #16
Source File: RedisDistributedMapCacheClientService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> void put(final K key, final V value, final Serializer<K> keySerializer, final Serializer<V> valueSerializer) throws IOException {
    withConnection(redisConnection -> {
        final Tuple<byte[],byte[]> kv = serialize(key, value, keySerializer, valueSerializer);
        redisConnection.set(kv.getKey(), kv.getValue(), Expiration.seconds(ttl), SetOption.upsert());
        return null;
    });
}
 
Example #17
Source File: RedisAuthorizationCodeServices.java    From cloud-service with MIT License 5 votes vote down vote up
/**
 * 存储code到redis,并设置过期时间,10分钟<br>
 * value为OAuth2Authentication序列化后的字节<br>
 * 因为OAuth2Authentication没有无参构造函数<br>
 * redisTemplate.opsForValue().set(key, value, timeout, unit);
 * 这种方式直接存储的话,redisTemplate.opsForValue().get(key)的时候有些问题,
 * 所以这里采用最底层的方式存储,get的时候也用最底层的方式获取
 */
@Override
protected void store(String code, OAuth2Authentication authentication) {
	redisTemplate.execute(new RedisCallback<Long>() {

		@Override
		public Long doInRedis(RedisConnection connection) throws DataAccessException {
			connection.set(codeKey(code).getBytes(), SerializationUtils.serialize(authentication),
					Expiration.from(10, TimeUnit.MINUTES), SetOption.UPSERT);
			return 1L;
		}
	});
}
 
Example #18
Source File: RedissonConnectionTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetExpiration2() {
    assertThat(connection.set("key".getBytes(), "value".getBytes(), Expiration.milliseconds(10), SetOption.SET_IF_ABSENT)).isTrue();
    assertThat(connection.set("key".getBytes(), "value".getBytes(), Expiration.milliseconds(10), SetOption.SET_IF_ABSENT)).isFalse();
    assertThat(connection.set("key".getBytes(), "value".getBytes(), Expiration.milliseconds(10), SetOption.SET_IF_ABSENT)).isFalse();
    assertThat(connection.get("key".getBytes())).isEqualTo("value".getBytes());
}
 
Example #19
Source File: RedissonConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean set(byte[] key, byte[] value, Expiration expiration, SetOption option) {
    if (expiration == null) {
        return set(key, value);
    } else if (expiration.isPersistent()) {
        if (option == null || option == SetOption.UPSERT) {
            return set(key, value);
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "XX");
        }
    } else {
        if (option == null || option == SetOption.UPSERT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds());
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "XX");
        }
    }
    throw new IllegalArgumentException();
}
 
Example #20
Source File: RedissonConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean set(byte[] key, byte[] value, Expiration expiration, SetOption option) {
    if (expiration == null) {
        return set(key, value);
    } else if (expiration.isPersistent()) {
        if (option == null || option == SetOption.UPSERT) {
            return set(key, value);
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "XX");
        }
    } else {
        if (option == null || option == SetOption.UPSERT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds());
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "XX");
        }
    }
    throw new IllegalArgumentException();
}
 
Example #21
Source File: RedissonConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean set(byte[] key, byte[] value, Expiration expiration, SetOption option) {
    if (expiration == null) {
        return set(key, value);
    } else if (expiration.isPersistent()) {
        if (option == null || option == SetOption.UPSERT) {
            return set(key, value);
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "XX");
        }
    } else {
        if (option == null || option == SetOption.UPSERT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds());
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "XX");
        }
    }
    throw new IllegalArgumentException();
}
 
Example #22
Source File: RedissonConnection.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean set(byte[] key, byte[] value, Expiration expiration, SetOption option) {
    if (expiration == null) {
        return set(key, value);
    } else if (expiration.isPersistent()) {
        if (option == null || option == SetOption.UPSERT) {
            return set(key, value);
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "XX");
        }
    } else {
        if (option == null || option == SetOption.UPSERT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds());
        }
        if (option == SetOption.SET_IF_ABSENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "NX");
        }
        if (option == SetOption.SET_IF_PRESENT) {
            return write(key, StringCodec.INSTANCE, SET, key, value, "PX", expiration.getExpirationTimeInMilliseconds(), "XX");
        }
    }
    throw new IllegalArgumentException();
}
 
Example #23
Source File: AbstractRedisLockProviderIntegrationTest.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
private boolean isLocked(String lockName) {
    return redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            byte[] rawKey = buildKey(lockName).getBytes();
            if (!connection.exists(rawKey)) {
                return false;
            }
            Expiration expiration = getExpirationFromValue(connection.get(rawKey));
            return expiration.getExpirationTimeInMilliseconds() > 0;
        });
}
 
Example #24
Source File: RedisLockProvider.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
private static Boolean tryToSetExpiration(StringRedisTemplate template, String key, Expiration expiration, SetOption option) {
    return template.execute(connection -> {
        byte[] serializedKey = ((RedisSerializer<String>) template.getKeySerializer()).serialize(key);
        byte[] serializedValue = ((RedisSerializer<String>) template.getValueSerializer()).serialize(String.format("ADDED:%s@%s", toIsoString(ClockProvider.now()), getHostname()));
        return connection.set(serializedKey, serializedValue, expiration, option);
    }, false);
}
 
Example #25
Source File: RedisLockProvider.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
public void doUnlock() {
    Expiration keepLockFor = getExpiration(lockConfiguration.getLockAtLeastUntil());
    // lock at least until is in the past
    if (keepLockFor.getExpirationTimeInMilliseconds() <= 0) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            throw new LockException("Can not remove node", e);
        }
    } else {
        tryToSetExpiration(this.redisTemplate, key, keepLockFor, SetOption.SET_IF_PRESENT);
    }
}
 
Example #26
Source File: RedisLockProvider.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
    String key = buildKey(lockConfiguration.getName());
    Expiration expiration = getExpiration(lockConfiguration.getLockAtMostUntil());
    if (TRUE.equals(tryToSetExpiration(redisTemplate, key, expiration, SET_IF_ABSENT))) {
        return Optional.of(new RedisLock(key, redisTemplate, lockConfiguration));
    } else {
        return Optional.empty();
    }
}
 
Example #27
Source File: TracingRedisConnectionTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void invokingSetCreatesNewSpan() {
  commandCreatesNewSpan(RedisCommand.SET,
      () -> getConnection().set("key".getBytes(), "val".getBytes()));
  verify(mockRedisConnection()).set("key".getBytes(), "val".getBytes());

  commandCreatesNewSpan(RedisCommand.SET,
      () -> getConnection().set("key".getBytes(), "val".getBytes(),
          Expiration.persistent(), RedisStringCommands.SetOption.ifAbsent()));
  verify(mockRedisConnection())
      .set(eq("key".getBytes()), eq("val".getBytes()), any(Expiration.class),
          eq(RedisStringCommands.SetOption.ifAbsent()));
}
 
Example #28
Source File: TracingRedisConnectionTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void invokingSetCreatesNewSpan() {
  commandCreatesNewSpan(RedisCommand.SET,
      () -> getConnection().set("key".getBytes(), "val".getBytes()));
  verify(mockRedisConnection()).set("key".getBytes(), "val".getBytes());

  commandCreatesNewSpan(RedisCommand.SET,
      () -> getConnection().set("key".getBytes(), "val".getBytes(),
          Expiration.persistent(), RedisStringCommands.SetOption.ifAbsent()));
  verify(mockRedisConnection())
      .set(eq("key".getBytes()), eq("val".getBytes()), any(Expiration.class),
          eq(RedisStringCommands.SetOption.ifAbsent()));
}
 
Example #29
Source File: RedisClusterElection.java    From dew with Apache License 2.0 5 votes vote down vote up
private void doElection() {
    logger.trace("[Election] electing...");
    byte[] rawKey = redisTemplate.getStringSerializer().serialize(key);
    byte[] rawValue = redisTemplate.getStringSerializer().serialize(Cluster.instanceId);
    boolean finish = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
        if (connection.set(rawKey, rawValue, Expiration.seconds(electionPeriodSec * 2 + 2),
                RedisStringCommands.SetOption.ifAbsent())) {
            leader.set(FLAG_LEADER);
            return true;
        }
        byte[] v = connection.get(rawKey);
        if (v == null) {
            return false;
        }
        if (redisTemplate.getStringSerializer().deserialize(v).equals(Cluster.instanceId)) {
            leader.set(FLAG_LEADER);
            // 被调用后续租,2个选举周期过期
            connection.expire(rawKey, electionPeriodSec * 2 + 2);
        } else {
            leader.set(FLAG_FOLLOWER);
        }
        return true;
    });
    if (!finish) {
        doElection();
    }
}
 
Example #30
Source File: RedisLockProvider.java    From ShedLock with Apache License 2.0 4 votes vote down vote up
private static Expiration getExpiration(Instant until) {
    return Expiration.from(getMsUntil(until), TimeUnit.MILLISECONDS);
}