org.springframework.data.redis.connection.RedisStringCommands Java Examples

The following examples show how to use org.springframework.data.redis.connection.RedisStringCommands. 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: 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 #2
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 #3
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 #4
Source File: DataService.java    From MyCommunity with Apache License 2.0 6 votes vote down vote up
public long calculateDAU(Date start, Date end) {
    if (start == null || end == null) {
        throw new IllegalArgumentException("参数不能为空!");
    }

    // 整理该日期范围内的key
    List<byte[]> keyList = new ArrayList<>();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(start);
    while (!calendar.getTime().after(end)) {
        String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
        keyList.add(key.getBytes());
        calendar.add(Calendar.DATE, 1);
    }

    // 进行OR运算
    return (long) redisTemplate.execute(new RedisCallback() {
        @Override
        public Object doInRedis(RedisConnection connection) throws DataAccessException {
            String redisKey = RedisKeyUtil.getDAUKey(df.format(start), df.format(end));
            connection.bitOp(RedisStringCommands.BitOperation.OR,
                    redisKey.getBytes(), keyList.toArray(new byte[0][0]));
            return connection.bitCount(redisKey.getBytes());
        }
    });
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: TracingRedisConnectionTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void invokingBitOpCreatesNewSpan() {
  commandCreatesNewSpan(RedisCommand.BITOP,
      () -> getConnection().bitOp(RedisStringCommands.BitOperation.OR,
          "dst".getBytes(), "key".getBytes()));
  verify(mockRedisConnection()).bitOp(RedisStringCommands.BitOperation.OR,
      "dst".getBytes(), "key".getBytes());
}
 
Example #16
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 #17
Source File: TracingRedisConnectionTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void invokingBitOpCreatesNewSpan() {
  commandCreatesNewSpan(RedisCommand.BITOP,
      () -> getConnection().bitOp(RedisStringCommands.BitOperation.OR,
          "dst".getBytes(), "key".getBytes()));
  verify(mockRedisConnection()).bitOp(RedisStringCommands.BitOperation.OR,
      "dst".getBytes(), "key".getBytes());
}
 
Example #18
Source File: TracingRedisConnection.java    From java-redis-client with Apache License 2.0 4 votes vote down vote up
@Override
public RedisStringCommands stringCommands() {
  return connection.stringCommands();
}