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

The following examples show how to use org.springframework.data.redis.connection.RedisConnection. 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: redis-admin   Source File: DefaultSetOperations.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Cursor<V> scan(K key, final ScanOptions options) {

	final byte[] rawKey = rawKey(key);
	return execute(new RedisCallback<Cursor<V>>() {

		@Override
		public Cursor<V> doInRedis(RedisConnection connection) throws DataAccessException {
			return new ConvertingCursor<byte[], V>(connection.sScan(rawKey, options), new Converter<byte[], V>() {

				@Override
				public V convert(byte[] source) {
					return deserializeValue(source);
				}
			});
		}
	}, true);

}
 
Example 2
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 3
Source Project: xmfcn-spring-cloud   Source File: RedisService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * getCache(获取缓存数据)
 *
 * @param key
 * @return
 */
@RequestMapping("getCache")
public String getCache(String key) {
    logger.info("getCache(获取缓存数据)redis 开始 " + key);
    String result = null;
    if (StringUtil.isBlank(key)) {
        return result;
    }
    RedisConnection conn = getRedisConnection();
    if (conn == null) {
        return result;
    }
    try {
        byte[] bytes = conn.get(key.getBytes());
        if (bytes != null) {
            result = new String(bytes, "utf-8");
        }
    } catch (Exception e) {
        logger.error("getCache:" + StringUtil.getExceptionMsg(e));
    }
    return result;
}
 
Example 4
Source Project: Auth-service   Source File: CustomRedisTokenStore.java    License: MIT License 6 votes vote down vote up
public void removeRefreshToken(String tokenValue) {
    byte[] refreshKey = serializeKey(REFRESH + tokenValue);
    byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
    byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
    byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
    RedisConnection conn = getConnection();
    try {
        conn.openPipeline();
        conn.del(refreshKey);
        conn.del(refreshAuthKey);
        conn.del(refresh2AccessKey);
        conn.del(access2RefreshKey);
        conn.closePipeline();
    } finally {
        conn.close();
    }
}
 
Example 5
@Override
public UUID findSignUpCodeByUsername(String username) {
    var foundSignUpCodeKey = redisTemplate.execute(new RedisCallback<String>() {
        @Override
        public String doInRedis(RedisConnection connection) throws DataAccessException {
            try (var cursor = connection.scan(ScanOptions.scanOptions().match("signup:signupcode*").build())) {
                while (cursor.hasNext()) {
                    var key = new String(cursor.next(), "UTF-8");
                    var usernameFromRedis = (String) redisTemplate.opsForHash().get(key, "username");
                    if (username.equals(usernameFromRedis)) {
                        return key;
                    }
                }
            } catch (IOException e) {
                throw new FlexPokerException("error in Redis");
            }
            throw new FlexPokerException("could not find username in Redis");
        }
    });

    return UUID.fromString(foundSignUpCodeKey.split(":")[2]);
}
 
Example 6
Source Project: redis-admin   Source File: DefaultValueOperations.java    License: Apache License 2.0 6 votes vote down vote up
public List<V> multiGet(Collection<K> keys) {
	if (keys.isEmpty()) {
		return Collections.emptyList();
	}

	final byte[][] rawKeys = new byte[keys.size()][];

	int counter = 0;
	for (K hashKey : keys) {
		rawKeys[counter++] = rawKey(hashKey);
	}

	List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {

		public List<byte[]> doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			return connection.mGet(rawKeys);
		}
	}, true);

	return deserializeValues(rawValues);
}
 
Example 7
Source Project: jetcache   Source File: RedisSpringDataCache.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected CacheResult do_PUT_ALL(Map<? extends K, ? extends V> map, long expireAfterWrite, TimeUnit timeUnit) {
    RedisConnection con = null;
    try {
        con = connectionFactory.getConnection();
        int failCount = 0;
        for (Map.Entry<? extends K, ? extends V> en : map.entrySet()) {
            CacheValueHolder<V> holder = new CacheValueHolder(en.getValue(), timeUnit.toMillis(expireAfterWrite));
            Boolean result = con.pSetEx(buildKey(en.getKey()),
                    timeUnit.toMillis(expireAfterWrite), valueEncoder.apply(holder));
            if(!Boolean.TRUE.equals(result)){
                failCount++;
            }
        }
        return failCount == 0 ? CacheResult.SUCCESS_WITHOUT_MSG :
                failCount == map.size() ? CacheResult.FAIL_WITHOUT_MSG : CacheResult.PART_SUCCESS_WITHOUT_MSG;
    } catch (Exception ex) {
        logError("PUT_ALL", "map(" + map.size() + ")", ex);
        return new CacheResult(ex);
    } finally {
        closeConnection(con);
    }
}
 
Example 8
Source Project: redisson   Source File: RedissonConnectionFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RedisSentinelConnection getSentinelConnection() {
    if (!redisson.getConfig().isSentinelConfig()) {
        throw new InvalidDataAccessResourceUsageException("Redisson is not in Sentinel mode");
    }
    
    SentinelConnectionManager manager = ((SentinelConnectionManager)((Redisson)redisson).getConnectionManager());
    for (RedisClient client : manager.getSentinels()) {
        org.redisson.client.RedisConnection connection = client.connect();
        try {
            String res = connection.sync(RedisCommands.PING);
            if ("pong".equalsIgnoreCase(res)) {
                return new RedissonSentinelConnection(connection);
            }
        } catch (Exception e) {
            log.warn("Can't connect to " + client, e);
            connection.closeAsync();
        }
    }
    
    throw new InvalidDataAccessResourceUsageException("Sentinels are not found");
}
 
Example 9
Source Project: redis-admin   Source File: DefaultValueOperations.java    License: Apache License 2.0 6 votes vote down vote up
public void multiSet(Map<? extends K, ? extends V> m) {
	if (m.isEmpty()) {
		return;
	}

	final Map<byte[], byte[]> rawKeys = new LinkedHashMap<byte[], byte[]>(m.size());

	for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
		rawKeys.put(rawKey(entry.getKey()), rawValue(entry.getValue()));
	}

	execute(new RedisCallback<Object>() {

		public Object doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			connection.mSet(rawKeys);
			return null;
		}
	}, true);
}
 
Example 10
/**
 * 将随机生成的授权码存到redis中
 *
 * @param code
 * @param authentication
 * @return void
 */
@Override
protected void store(String code, OAuth2Authentication authentication) {
    byte[] serializedKey = serializeKey(AUTHORIZATION_CODE + code);
    byte[] serializedAuthentication = serialize(authentication);
    RedisConnection conn = getConnection();
    try {
        conn.openPipeline();
        conn.set(serializedKey, serializedAuthentication);
        conn.expire(serializedKey,expiration);
        conn.closePipeline();
    } finally {
        conn.close();
    }

}
 
Example 11
Source Project: blog_demos   Source File: RedisClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 更新缓存中的对象,也可以在redis缓存中存入新的对象
 *
 * @param key
 * @param t
 * @param <T>
 */
public <T> void set(String key, T t) {
    byte[] keyBytes = getKey(key);
    RedisSerializer serializer = redisTemplate.getValueSerializer();
    byte[] val = serializer.serialize(t);
    RedisConnection redisConnection = getConnection();

    if(null!=redisConnection){
        try {
            redisConnection.set(keyBytes, val);
        }finally {
            releaseConnection(redisConnection);
        }
    }else{
        logger.error("1. can not get valid connection");
    }
}
 
Example 12
/**
 * 通过key获取
 */
@Override
public UserDTO get(final String keyId) {
	UserDTO result = redisTemplate.execute(new RedisCallback<UserDTO>() {
		@Override
		public UserDTO doInRedis(RedisConnection connection) throws DataAccessException {
			RedisSerializer<String> serializer = getRedisSerializer();
			byte[] key = serializer.serialize(keyId);
			byte[] value = connection.get(key);
			if (value == null) {
				return null;
			}
			String name = serializer.deserialize(value);
			return new UserDTO(keyId, name, null);
		}
	});
	return result;
}
 
Example 13
Source Project: xmfcn-spring-cloud   Source File: RedisService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将 key 中储存的数字值加N
 *
 * @param key
 * @param integer
 * @return
 */
@RequestMapping("incrBy")
public Long incrBy(String key, long integer) {
    Long result = null;
    if (StringUtil.isBlank(key)) {
        return result;
    }
    RedisConnection conn = getRedisConnection();
    if (conn == null) {
        return result;
    }
    try {
        result = conn.incrBy(key.getBytes(), integer);
    } catch (Exception e) {
        logger.error(StringUtil.getExceptionMsg(e));
    }
    return result;
}
 
Example 14
Source Project: gateway-helper   Source File: DefaultRedisCacheWriter.java    License: Apache License 2.0 6 votes vote down vote up
private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {

        if (!isLockingCacheWriter()) {
            return;
        }

        try {

            while (doCheckLock(name, connection)) {
                Thread.sleep(sleepTime.toMillis());
            }
        } catch (InterruptedException ex) {

            // Re-interrupt current thread, to allow other participants to react.
            Thread.currentThread().interrupt();

            throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name),
                    ex);
        }
    }
 
Example 15
Source Project: xmfcn-spring-cloud   Source File: RedisService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * delete(将 key 缓存数据删除)
 *
 * @param key
 * @return
 */
@RequestMapping("delete")
public Long delete(String key) {
    logger.info("delete(将 key 缓存数据删除) 开始 key={}", key);
    Long result = null;
    if (StringUtil.isBlank(key)) {
        return result;
    }
    RedisConnection conn = getRedisConnection();
    if (conn == null) {
        return result;
    }
    try {
        result = conn.del(key.getBytes());
    } catch (Exception e) {
        logger.error("delete_error:" + StringUtil.getExceptionMsg(e));
    }
    logger.info("delete(将 key 缓存数据删除)结束 key={},result={}", key, result);
    return result;
}
 
Example 16
Source Project: redisson   Source File: RedissonConnectionFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RedisSentinelConnection getSentinelConnection() {
    if (!redisson.getConfig().isSentinelConfig()) {
        throw new InvalidDataAccessResourceUsageException("Redisson is not in Sentinel mode");
    }
    
    SentinelConnectionManager manager = ((SentinelConnectionManager)((Redisson)redisson).getConnectionManager());
    for (RedisClient client : manager.getSentinels()) {
        org.redisson.client.RedisConnection connection = client.connect();
        try {
            String res = connection.sync(RedisCommands.PING);
            if ("pong".equalsIgnoreCase(res)) {
                return new RedissonSentinelConnection(connection);
            }
        } catch (Exception e) {
            log.warn("Can't connect to " + client, e);
            connection.closeAsync();
        }
    }
    
    throw new InvalidDataAccessResourceUsageException("Sentinels are not found");
}
 
Example 17
public void config(RedisConnection connection) {
	String notifyOptions = getNotifyOptions(connection);
	String customizedNotifyOptions = notifyOptions;
	if (!customizedNotifyOptions.contains("E")) {
		customizedNotifyOptions += "E";
	}
	boolean A = customizedNotifyOptions.contains("A");
	if (!(A || customizedNotifyOptions.contains("g"))) {
		customizedNotifyOptions += "g";
	}
	if (!(A || customizedNotifyOptions.contains("x"))) {
		customizedNotifyOptions += "x";
	}
	if (!notifyOptions.equals(customizedNotifyOptions)) {
		connection.setConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS, customizedNotifyOptions);
	}
}
 
Example 18
Source Project: redis-admin   Source File: DefaultZSetOperations.java    License: Apache License 2.0 5 votes vote down vote up
public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) {
	final byte[][] rawKeys = rawKeys(key, otherKeys);
	final byte[] rawDestKey = rawKey(destKey);
	return execute(new RedisCallback<Long>() {

		public Long doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			return connection.zUnionStore(rawDestKey, rawKeys);
		}
	}, true);
}
 
Example 19
Source Project: sk-admin   Source File: RedisUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 分页查询 key
 *
 * @param patternKey key
 * @param page       页码
 * @param size       每页数目
 * @return /
 */
public List<String> findKeysForPage(String patternKey, int page, int size) {
    ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();
    RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
    RedisConnection rc = Objects.requireNonNull(factory).getConnection();
    Cursor<byte[]> cursor = rc.scan(options);
    List<String> result = new ArrayList<>(size);
    int tmpIndex = 0;
    int fromIndex = page * size;
    int toIndex = page * size + size;
    while (cursor.hasNext()) {
        if (tmpIndex >= fromIndex && tmpIndex < toIndex) {
            result.add(new String(cursor.next()));
            tmpIndex++;
            continue;
        }
        // 获取到满足条件的数据后,就可以退出了
        if (tmpIndex >= toIndex) {
            break;
        }
        tmpIndex++;
        cursor.next();
    }
    try {
        RedisConnectionUtils.releaseConnection(rc, factory);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 20
Source Project: redis-admin   Source File: DefaultZSetOperations.java    License: Apache License 2.0 5 votes vote down vote up
public Long reverseRank(K key, Object o) {
	final byte[] rawKey = rawKey(key);
	final byte[] rawValue = rawValue(o);

	return execute(new RedisCallback<Long>() {

		public Long doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			Long zRank = connection.zRevRank(rawKey, rawValue);
			return (zRank != null && zRank.longValue() >= 0 ? zRank : null);
		}
	}, true);
}
 
Example 21
private static RedisConnectionFactory mockRedisConnectionFactory() {
	RedisConnectionFactory connectionFactory = mock(RedisConnectionFactory.class);
	RedisConnection connection = mock(RedisConnection.class);
	given(connectionFactory.getConnection()).willReturn(connection);
	given(connection.getConfig(anyString())).willReturn(new Properties());
	return connectionFactory;
}
 
Example 22
Source Project: redis-admin   Source File: DefaultZSetOperations.java    License: Apache License 2.0 5 votes vote down vote up
public Set<TypedTuple<V>> rangeByScoreWithScores(K key, final double min, final double max, final long offset,
		final long count) {
	final byte[] rawKey = rawKey(key);

	Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {

		public Set<Tuple> doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			return connection.zRangeByScoreWithScores(rawKey, min, max, offset, count);
		}
	}, true);

	return deserializeTupleValues(rawValues);
}
 
Example 23
Source Project: redis-admin   Source File: DefaultListOperations.java    License: Apache License 2.0 5 votes vote down vote up
public V rightPopAndLeftPush(K sourceKey, K destinationKey) {
	final byte[] rawDestKey = rawKey(destinationKey);

	return execute(new ValueDeserializingRedisCallback(sourceKey) {

		protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) {
			connection.select(dbIndex);
			return connection.rPopLPush(rawSourceKey, rawDestKey);
		}
	}, true);
}
 
Example 24
Source Project: mykit-delay   Source File: RedisSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * command GETSET key value
 */
public String getSet(final String key, final String value) {
    final org.springframework.data.redis.serializer.RedisSerializer redisSerializer      = template.getKeySerializer();
    final org.springframework.data.redis.serializer.RedisSerializer redisValueSerializer = template.getValueSerializer();
    return template.execute(new RedisCallback<String>() {
        @Override
        public String doInRedis(RedisConnection connection) throws DataAccessException {
            byte[] b = connection.getSet(redisSerializer.serialize(key), redisValueSerializer.serialize(value));
            return template.getStringSerializer().deserialize(b);
        }
    });
}
 
Example 25
Source Project: redis-admin   Source File: DefaultValueOperations.java    License: Apache License 2.0 5 votes vote down vote up
public V getAndSet(K key, V newValue) {
	final byte[] rawValue = rawValue(newValue);
	return execute(new ValueDeserializingRedisCallback(key) {

		protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
			connection.select(dbIndex);
			return connection.getSet(rawKey, rawValue);
		}
	}, true);
}
 
Example 26
@Before
@After
public void setUp() {

	operations.execute((RedisConnection connection) -> {
		connection.flushDb();
		return "OK";
	});
}
 
Example 27
Source Project: sdmq   Source File: RedisSupport.java    License: Apache License 2.0 5 votes vote down vote up
public Boolean setNx(final String key, final String value) {
    final org.springframework.data.redis.serializer.RedisSerializer redisSerializer      = template.getKeySerializer();
    final org.springframework.data.redis.serializer.RedisSerializer redisValueSerializer = template.getValueSerializer();
    return template.execute(new RedisCallback<Boolean>() {
        @Override
        public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            return connection.setNX(redisSerializer.serialize(key), redisValueSerializer.serialize(value));
        }
    });
}
 
Example 28
Source Project: redis-admin   Source File: DefaultValueOperations.java    License: Apache License 2.0 5 votes vote down vote up
public V get(final Object key) {

		return execute(new ValueDeserializingRedisCallback(key) {

			protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
				connection.select(dbIndex);
				return connection.get(rawKey);
			}
		}, true);
	}
 
Example 29
Source Project: redis-admin   Source File: DefaultValueOperations.java    License: Apache License 2.0 5 votes vote down vote up
public String get(K key, final long start, final long end) {
	final byte[] rawKey = rawKey(key);

	byte[] rawReturn = execute(new RedisCallback<byte[]>() {

		public byte[] doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			return connection.getRange(rawKey, start, end);
		}
	}, true);

	return deserializeString(rawReturn);
}
 
Example 30
Source Project: JobX   Source File: RedisCacheManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void put(final Object key, final Object value) {
    if (CommonUtils.isEmpty(key) || CommonUtils.isEmpty(value)) {
        return;
    } else {
        final String finalKey;
        if (key instanceof String) {
            finalKey = (String) key;
        } else {
            finalKey = key.toString();
        }
        if (CommonUtils.notEmpty(finalKey)) {
            final Object finalValue = value;
            redisTemplate.execute(new RedisCallback<Boolean>() {
                @Override
                public Boolean doInRedis(RedisConnection connection) {
                    try {
                        byte[] data = serializer.serialize(finalValue);
                        connection.set(finalKey.getBytes(), data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // 设置超时间
                    connection.expire(finalKey.getBytes(), getExpire());
                    return true;
                }
            });
        }
    }
}