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

The following examples show how to use org.springframework.data.redis.connection.RedisConnection. 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: RedisAuthorizationCodeServices.java    From springcloud-oauth2 with MIT License 6 votes vote down vote up
/**
 * 将随机生成的授权码存到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 #2
Source File: RedisService.java    From xmfcn-spring-cloud with 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 #3
Source File: DefaultRedisCacheWriter.java    From gateway-helper with 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 #4
Source File: RedisSpringDataCache.java    From jetcache with 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 #5
Source File: UserDao.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 通过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 #6
Source File: DefaultValueOperations.java    From redis-admin with 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 File: RedisService.java    From xmfcn-spring-cloud with 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 #8
Source File: RedisClient.java    From blog_demos with 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 #9
Source File: RedissonConnectionFactory.java    From redisson with 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 #10
Source File: RedisSignUpRepository.java    From flex-poker with GNU General Public License v2.0 6 votes vote down vote up
@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 #11
Source File: CustomRedisTokenStore.java    From Auth-service with 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 #12
Source File: RedissonConnectionFactory.java    From redisson with 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 #13
Source File: DefaultValueOperations.java    From redis-admin with 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 #14
Source File: RedisService.java    From xmfcn-spring-cloud with 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 #15
Source File: ConfigureNotifyKeyspaceEventsAction.java    From J2Cache with Apache License 2.0 6 votes vote down vote up
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 #16
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 #17
Source File: DefaultSetOperations.java    From redis-admin with 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 #18
Source File: TracingRedisConnectionFactory.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Override
public RedisConnection getConnection() {
  // support cluster connection
  RedisConnection connection = this.delegate.getConnection();
  if (connection instanceof RedisClusterConnection) {
    return new TracingRedisClusterConnection((RedisClusterConnection) connection,
        tracingConfiguration);
  }
  return new TracingRedisConnection(connection, tracingConfiguration);
}
 
Example #19
Source File: Gh109Tests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Bean
RedisConnectionFactory redisConnectionFactory() {
	RedisConnectionFactory factory = mock(RedisConnectionFactory.class);
	RedisConnection connection = mock(RedisConnection.class);
	given(factory.getConnection()).willReturn(connection);
	given(connection.getConfig(anyString())).willReturn(new Properties());
	return factory;
}
 
Example #20
Source File: DefaultZSetOperations.java    From redis-admin with Apache License 2.0 5 votes vote down vote up
public Long remove(K key, Object... values) {
	final byte[] rawKey = rawKey(key);
	final byte[][] rawValues = rawValues(values);

	return execute(new RedisCallback<Long>() {

		public Long doInRedis(RedisConnection connection) {
			connection.select(dbIndex);
			return connection.zRem(rawKey, rawValues);
		}
	}, true);
}
 
Example #21
Source File: CustomRedisTokenStore.java    From Auth-service with MIT License 5 votes vote down vote up
public void removeAccessToken(String tokenValue) {
    byte[] accessKey = serializeKey(ACCESS + tokenValue);
    byte[] authKey = serializeKey(AUTH + tokenValue);
    byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
    RedisConnection conn = getConnection();
    try {
        conn.openPipeline();
        conn.get(accessKey);
        conn.get(authKey);
        conn.del(accessKey);
        conn.del(accessToRefreshKey);
        // Don't remove the refresh token - it's up to the caller to do that
        conn.del(authKey);
        List<Object> results = conn.closePipeline();
        byte[] access = (byte[]) results.get(0);
        byte[] auth = (byte[]) results.get(1);

        OAuth2Authentication authentication = deserializeAuthentication(auth);
        if (authentication != null) {
            String key = authenticationKeyGenerator.extractKey(authentication);
            byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
            byte[] unameKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
            byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
            conn.openPipeline();
            conn.del(authToAccessKey);
            conn.lRem(unameKey, 1, access);
            conn.lRem(clientId, 1, access);
            conn.del(serialize(ACCESS + key));
            conn.closePipeline();
        }
    } finally {
        conn.close();
    }
}
 
Example #22
Source File: ConfigureNotifyKeyspaceEventsAction.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private String getNotifyOptions(RedisConnection connection) {
    try {
        Properties config = connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS);
        if (config.isEmpty()) {
            return "";
        }
        return config.getProperty(config.stringPropertyNames().iterator().next());
    } catch (InvalidDataAccessApiUsageException e) {
        throw new IllegalStateException(
            "Unable to configure Redis to keyspace notifications. See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent",
            e);
    }
}
 
Example #23
Source File: RedisConnectionPoolService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public RedisConnection getConnection() {
    if (connectionFactory == null) {
        synchronized (this) {
            if (connectionFactory == null) {
                connectionFactory = RedisUtils.createConnectionFactory(context, getLogger());
            }
        }
    }

    return connectionFactory.getConnection();
}
 
Example #24
Source File: RedisHashServiceImpl.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public boolean hExists(final String key, final String field) {
	return redisTemplate.execute(new RedisCallback<Boolean>() {
		@Override
		public Boolean doInRedis(RedisConnection connection) {
			return connection.hExists(serializer.serialize(key), hkeySerializer.serialize(field));
		}
	});
}
 
Example #25
Source File: DefaultSetOperations.java    From redis-admin with Apache License 2.0 5 votes vote down vote up
public Long differenceAndStore(final K key, final 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.sDiffStore(rawDestKey, rawKeys);
		}
	}, true);
}
 
Example #26
Source File: DefaultHashOperations.java    From redis-admin with Apache License 2.0 5 votes vote down vote up
@Override
public Cursor<Entry<HK, HV>> scan(K key, final ScanOptions options) {

	final byte[] rawKey = rawKey(key);
	return execute(new RedisCallback<Cursor<Map.Entry<HK, HV>>>() {

		@Override
		public Cursor<Entry<HK, HV>> doInRedis(RedisConnection connection) throws DataAccessException {

			return new ConvertingCursor<Map.Entry<byte[], byte[]>, Map.Entry<HK, HV>>(connection.hScan(rawKey, options),
					new Converter<Map.Entry<byte[], byte[]>, Map.Entry<HK, HV>>() {

						@Override
						public Entry<HK, HV> convert(final Entry<byte[], byte[]> source) {

							return new Map.Entry<HK, HV>() {

								@Override
								public HK getKey() {
									return deserializeHashKey(source.getKey());
								}

								@Override
								public HV getValue() {
									return deserializeHashValue(source.getValue());
								}

								@Override
								public HV setValue(HV value) {
									throw new UnsupportedOperationException("Values cannot be set when scanning through entries.");
								}
							};

						}
					});
		}

	}, true);

}
 
Example #27
Source File: MyRedisTemplate.java    From redis-admin with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(K key) {
	final byte[] rawKey = rawKey(key);

	execute(new RedisCallback<Object>() {

		public Object doInRedis(RedisConnection connection) {
			int dbIndex = RedisApplication.redisConnectionDbIndex.get();
			connection.select(dbIndex);
			connection.del(rawKey);
			return null;
		}
	}, true);
}
 
Example #28
Source File: BaseRedisTest.java    From spring-boot-email-tools with Apache License 2.0 5 votes vote down vote up
@AfterTransaction
public void assertAfterTransaction() {
    if (nonNull(afterTransactionAssertion)) {
        final RedisConnection connection = connectionFactory.getConnection();
        afterTransactionAssertion.assertAfterTransaction(connection);
        connection.close();
    }
}
 
Example #29
Source File: RedisServiceImpl.java    From mySpringBoot with Apache License 2.0 5 votes vote down vote up
@Override
public String get(final String key){
    String result = redisTemplate.execute(new RedisCallback<String>() {
        @Override
        public String doInRedis(RedisConnection connection) throws DataAccessException {
            RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
            byte[] value =  connection.get(serializer.serialize(key));
            return serializer.deserialize(value);
        }
    });
    return result;
}
 
Example #30
Source File: DefaultZSetOperations.java    From redis-admin with 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);
}