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

The following examples show how to use org.springframework.data.redis.connection.RedisStringCommands. These examples are extracted from open source projects. 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 Project: MyCommunity   Source File: DataService.java    License: 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 2
Source Project: beihu-boot   Source File: AbstractRedisUtil.java    License: 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 3
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 4
Source Project: spring-microservice-exam   Source File: CustomRedisCacheWriter.java    License: 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 5
Source Project: black-shop   Source File: DefaultRedisCacheWriter.java    License: 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 6
Source Project: SpringBoot2.0   Source File: RedisDistributedLock.java    License: 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 7
Source Project: gateway-helper   Source File: DefaultRedisCacheWriter.java    License: 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 Project: xmfcn-spring-cloud   Source File: RedisService.java    License: 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 9
Source Project: xmfcn-spring-cloud   Source File: RedisService.java    License: 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 10
Source Project: api-gateway-old   Source File: DefaultRedisCacheWriter.java    License: 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 11
Source Project: jetcache   Source File: RedisSpringDataCache.java    License: 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 12
Source Project: AutoLoadCache   Source File: SpringRedisLock.java    License: 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 13
Source Project: dew   Source File: RedisClusterElection.java    License: 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
@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
@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
@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
@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 Project: java-redis-client   Source File: TracingRedisConnection.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public RedisStringCommands stringCommands() {
  return connection.stringCommands();
}