下面列出了org.springframework.boot.actuate.health.HealthIndicator#redis.clients.jedis.Jedis 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testJedisConnFactory_noAuthSuccess() throws Exception {
redisServer = new RedisServer(REDIS_PORT);
redisServer.start();
Host noAuthHost = new HostBuilder().setHostname("localhost").setPort(REDIS_PORT).setRack(REDIS_RACK).setStatus(Status.Up).createHost();
JedisConnectionFactory conFactory =
new JedisConnectionFactory(new DynoOPMonitor("some-application-name"), null);
ConnectionPoolConfiguration cpConfig = new ConnectionPoolConfigurationImpl("some-name");
CountingConnectionPoolMonitor poolMonitor = new CountingConnectionPoolMonitor();
HostConnectionPool<Jedis> hostConnectionPool =
new HostConnectionPoolImpl<>(noAuthHost, conFactory, cpConfig, poolMonitor);
Connection<Jedis> connection = conFactory
.createConnection(hostConnectionPool);
connection.execPing();
}
/**
* @param tableId
* @param key
* @param value
*
* @throws WispProcessorException
*/
@Override
public void put(String tableId, String key, String value) throws WispProcessorException {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String hKey = redisPrefix + tableId;
jedis.hset(hKey, key, value);
} catch (Exception e) {
throw new WispProcessorException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 是否可安全运行,即并发判断
* @return
*/
protected boolean isSafe() {
if (Application.rbvMode() && Application.getCommonCache().isUseRedis()) {
JedisPool pool = Application.getCommonCache().getJedisPool();
String jobKey = getClass().getName() + LOCK_KEY;
try (Jedis jedis = pool.getResource()) {
String tryLock = jedis.set(jobKey, LOCK_KEY, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, LOCK_TIME);
if (tryLock == null) {
LOG.info("The job has been executed by another instance");
return false;
}
}
}
return true;
}
/**
* Remove the specified keys.
*
* @param key
*
* @return false if redis did not execute the option
*/
public boolean delete(String key) {
Jedis jedis = null;
try {
jedis = this.jedisPool.getResource();
jedis.del(SafeEncoder.encode(key));
logger.info("delete key:" + key);
return true;
} catch (Exception e) {
logger.error(e.getMessage(), e);
this.jedisPool.returnBrokenResource(jedis);
} finally {
if (jedis != null) {
this.jedisPool.returnResource(jedis);
}
}
return false;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static String setMap(String key, Map<String, String> value, int cacheSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.hmset(key, value);
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
logger.debug("setMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setMap {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 设置
* @param key
* @param value
* @return
*/
@Override
public boolean setNxString(String key, String value, int seconds) throws Exception{
Jedis jedis = null;
boolean success = true;
boolean result = false;
try {
jedis = jedisPool.getResource();
result = (jedis.setnx(key, value) != 0);
if(seconds > -1){
jedis.expire(key, seconds);
}
} catch (Exception e) {
success = false;
releasBrokenReidsSource(jedis, key, "setNxString", e, false);
throw e;
} finally {
releaseReidsSource(success, jedis);
}
return result;
}
@Override
public void decrByEx(String key, Long value, Integer ttl) {
Jedis jedis = null;
try {
jedis = getInstance();
jedis.decrBy(key, value);
if (ttl != null) {
jedis.expire(key, ttl);
}
} catch (Exception e) {
if (LOG.isErrorEnabled()) {
LOG.error("Cannot send Redis with decrBy command with decrement {} with ttl {} error message {}",
key, value, ttl, e.getMessage());
}
throw e;
} finally {
releaseInstance(jedis);
}
}
private String createRedisKey(String lockId) {
Jedis jedis = null;
boolean broken = false;
try {
String value=lockId+randomId(1);
jedis = jedisPool.getResource();
String luaScript = ""
+ "\nlocal r = tonumber(redis.call('SETNX', KEYS[1],ARGV[1]));"
+ "\nredis.call('PEXPIRE',KEYS[1],ARGV[2]);"
+ "\nreturn r";
List<String> keys = new ArrayList<String>();
keys.add(lockId);
List<String> args = new ArrayList<String>();
args.add(value);
args.add(lockTimeout+"");
Long ret = (Long) jedis.eval(luaScript, keys, args);
if( new Long(1).equals(ret)){
return value;
}
}finally {
if(jedis!=null) jedis.close();
}
return null;
}
/**
*
* @param seckillId
* @param userPhone
* @return 0: 排队中; 1: 秒杀成功; 2: 秒杀失败
*/
@Override
public int isGrab(long seckillId, long userPhone) {
int result = 0 ;
Jedis jedis = jedisPool.getResource();
try {
String boughtKey = RedisKeyPrefix.BOUGHT_USERS + seckillId;
result = jedis.sismember(boughtKey, String.valueOf(userPhone)) ? 1 : 0;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
result = 0;
}
if (result == 0) {
if (!jedis.sismember(RedisKey.QUEUE_PRE_SECKILL, seckillId + "@" + userPhone)) {
result =2;
}
}
return result;
}
public Object hget(String key, String field) {
Jedis jedis = null;
try {
jedis = this.jedisPool.getResource();
byte[] value = jedis.hget(SafeEncoder.encode(key), SafeEncoder.encode(field));
logger.info("hget key:" + key + " field:" + field);
return deserialize(value);
} catch (Exception e) {
logger.error(e.getMessage(), e);
this.jedisPool.returnBrokenResource(jedis);
} finally {
if (jedis != null) {
this.jedisPool.returnResource(jedis);
}
}
return null;
}
public static void main(String[] args) {
//Creating a JedisPool of Jedis connections to localhost Redis server
JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), "localhost");
//Get a Jedis connection from pool
try (Jedis jedis = jedisPool.getResource()) {
String restaurantName = "Kyoto Ramen";
Map<String, String> restaurantInfo = new HashMap<>();
restaurantInfo.put("address", "801 Mission St, San Jose, CA");
restaurantInfo.put("phone", "555-123-6543");
jedis.hmset(restaurantName, restaurantInfo);
jedis.hset(restaurantName, "rating", "5.0");
String rating = jedis.hget(restaurantName, "rating");
System.out.printf("%s rating: %s\n", restaurantName, rating);
//Print out hash
for (Map.Entry<String, String> entry: jedis.hgetAll(restaurantName).entrySet()) {
System.out.printf("%s: %s\n", entry.getKey(), entry.getValue());
}
}
System.exit(0);
}
@Override
public String mset(final String... keysvalues) {
String[] keys = new String[keysvalues.length / 2];
for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) {
keys[keyIdx] = keysvalues[keyIdx * 2];
}
return new EnhancedJedisClusterCommand<String>(connectionHandler, maxAttempts) {
@Override
public String doExecute(Jedis connection) {
return connection.mset(keysvalues);
}
}.run(keys.length, keys);
}
/**
* 尝试获取分布式锁
*
* @param lockKey 锁
* @param requestId 请求标识
* @param expireTime 超期时间
* @return 是否获取成功
*/
private static boolean tryGetDistributedLock(Jedis redis, String lockKey, String requestId, int expireTime) {
String result = redis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
* For a given key prefix this method attempts to break up all the matching keys into N buckets (aka N splits).
*
* @param request
* @param endpoint The redis endpoint to query.
* @param keyPrefix The key prefix to scan.
* @param keyType The KeyType (prefix or zset).
* @param valueType The ValueType, used for mapping the values stored at each key to a result row when the split is processed.
* @return A Set of splits to optionally parallelize reading the values associated with the keyPrefix.
*/
private Set<Split> makeSplits(GetSplitsRequest request, String endpoint, String keyPrefix, KeyType keyType, String valueType)
{
Set<Split> splits = new HashSet<>();
long numberOfKeys = 1;
if (keyType == KeyType.ZSET) {
try (Jedis client = getOrCreateClient(endpoint)) {
numberOfKeys = client.zcount(keyPrefix, "-inf", "+inf");
logger.info("makeSplits: ZCOUNT[{}] found [{}]", keyPrefix, numberOfKeys);
}
}
long stride = (numberOfKeys > REDIS_MAX_SPLITS) ? 1 + (numberOfKeys / REDIS_MAX_SPLITS) : numberOfKeys;
for (long startIndex = 0; startIndex < numberOfKeys; startIndex += stride) {
long endIndex = startIndex + stride - 1;
if (endIndex >= numberOfKeys) {
endIndex = -1;
}
//Every split must have a unique location if we wish to spill to avoid failures
SpillLocation spillLocation = makeSpillLocation(request);
Split split = Split.newBuilder(spillLocation, makeEncryptionKey())
.add(KEY_PREFIX_TABLE_PROP, keyPrefix)
.add(KEY_TYPE, keyType.getId())
.add(VALUE_TYPE_TABLE_PROP, valueType)
.add(REDIS_ENDPOINT_PROP, endpoint)
.add(SPLIT_START_INDEX, String.valueOf(startIndex))
.add(SPLIT_END_INDEX, String.valueOf(endIndex))
.build();
splits.add(split);
logger.info("makeSplits: Split[{}]", split);
}
return splits;
}
/**
* 获取redis实例
*/
private synchronized Jedis getJedis() {
if (jedisPool == null) {
initJedisPool();
}
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
} catch (Exception e) {
logger.error("get resource:", e);
}
return jedis;
}
/**
* Pause job.
*
* @param jobKey the job key
* @param jedis thread-safe redis connection
* @throws JobPersistenceException
*/
private void pauseJob(String jobHashKey, Jedis jedis) throws JobPersistenceException {
if (!jedis.sismember(JOBS_SET, jobHashKey))
throw new JobPersistenceException("job: " + jobHashKey + " des not exist");
String jobTriggerSetkey = createJobTriggersSetKey(jobHashKey.split(":")[1], jobHashKey.split(":")[2]);
List<OperableTrigger> triggers = getTriggersForJob(jobTriggerSetkey, jedis);
for (OperableTrigger trigger : triggers)
pauseTrigger(trigger.getKey(), jedis);
}
public void configure( Hashtable<String,TEDB> intraTEDBs,MultiDomainTEDB multiTED, boolean writeTopology, String host, int port){
this.intraTEDBs=intraTEDBs;
this.writeTopology=writeTopology;
this.multiDomainTEDB=multiTED;
//rdh.setHost(host);
//rdh.setPort(port);
if (writeTopology){
jedis = new Jedis(host,port);
jedis.connect();
}
}
@Override
public Set<Tuple> zrangeWithScores(final byte[] key, final long start, final long end) {
checkArgumentsSpecification(key);
return new EnhancedJedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> doExecute(Jedis connection) {
return connection.zrangeWithScores(key, start, end);
}
}.runBinary(key);
}
/**
* 重设超时间
*
* @param jdi
* @param expireTime
*/
public static void resetExpireTime(String jdi, int expireTime) {
Jedis redis = null;
try {
redis = getJedis();
redis.expire(jdi, expireTime);
} finally {
if (redis != null) {
redis.close();
}
}
}
@Override
public List<String> hvals(String key) {
Jedis jedis = jedisPool.getResource();
List<String> result = jedis.hvals(key);
jedis.close();
return result;
}
private boolean fetchData(String keyString)
{
valueString = null;
valueMap = null;
// Redis connector supports two types of Redis
// values: STRING and HASH
// HASH types requires hash row decoder to
// fill in the columns
// whereas for the STRING type decoders are optional
try (Jedis jedis = jedisPool.getResource()) {
switch (split.getValueDataType()) {
case STRING:
valueString = jedis.get(keyString);
if (valueString == null) {
log.warn("Redis data modified while query was running, string value at key %s deleted", keyString);
return false;
}
break;
case HASH:
valueMap = jedis.hgetAll(keyString);
if (valueMap == null) {
log.warn("Redis data modified while query was running, hash value at key %s deleted", keyString);
return false;
}
break;
default:
log.debug("Redis type for key %s is unsupported", keyString);
return false;
}
}
return true;
}
public static void REGISTER(BridgeEvent event) {
Jedis jedis = null;
try {
JsonObject rawMessage = event.getRawMessage();
String address = rawMessage.getString("address");
jedis = JedisConnectionPool.getJedisConnection(10);
jedis.zincrby(RedisKeyStore.REGIST + ":CHANNELS:" + serverKey, -1, address);
jedis.zincrby(RedisKeyStore.REGIST + ":SERVERS:" + address, -1, serverKey);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null)
JedisConnectionPool.close(jedis);
}
}
/**
* Change the karma of a noun by an integer.
*
* @param noun The noun to change the karma of
* @param mod The amount to change the karma by, may be negative.
*/
public static void modDonorKarma( String noun, int mod )
{
Jedis jedis = pool.getResource();
try
{
jedis.zincrby( keyOfChurchDonorSortedSet, mod, noun );
}
finally
{
pool.returnResource( jedis );
}
}
@Override
protected int doRequest(Jedis jedis, String redisAddress) {
Set<byte[]> fields = jedis.hkeys(key.getBytes());
redisFields[index] = fields;
if (CollectionUtils.isEmpty(fields)) {
String verbose = String.format("get fields [%s] from [%s] is empty", key, redisAddress);
LOGGER.debug(verbose);
return 1;
}
return 0;
}
public List<String> hmget(final String key, final String... fields) {
return execute(new JedisExecutor<List<String>>() {
@Override
List<String> doInJedis(Jedis jedis) {
return jedis.hmget(key, fields);
}
});
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max) {
checkArgumentsSpecification(key);
return new EnhancedJedisClusterCommand<Set<Tuple>>(connectionHandler, maxAttempts) {
@Override
public Set<Tuple> doExecute(Jedis connection) {
return connection.zrangeByScoreWithScores(key, min, max);
}
}.runBinary(key);
}
@Override
public int subscribe(Consumer<Message> subscriber, Runnable subscriptionCallback, Channel... channels) {
JedisListener jedisListener = new JedisListener(subscriber, subscriptionCallback);
subscribers.put(subscriber, jedisListener);
try (Jedis jedis = redis.getResource()) {
jedis.subscribe(jedisListener, stream(channels).map(Enum::name).toArray(String[]::new));
}
return jedisListener.nbMessages.get();
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min) {
checkArgumentsSpecification(key);
return new EnhancedJedisClusterCommand<Set<byte[]>>(connectionHandler, maxAttempts) {
@Override
public Set<byte[]> doExecute(Jedis connection) {
return connection.zrevrangeByScore(key, max, min);
}
}.runBinary(key);
}
@Override
public Boolean sismember(String key, String member) {
Jedis jedis = null;
Boolean res = null;
try {
jedis = pool.getResource();
res = jedis.sismember(key, member);
} catch (Exception e) {
LOGGER.error(e.getMessage());
} finally {
returnResource(pool, jedis);
}
return res;
}
@Override
public Object evalsha(final String script, final String key) {
checkArgumentsSpecification(key);
return new EnhancedJedisClusterCommand<Object>(connectionHandler, maxAttempts) {
@Override
public Object doExecute(Jedis connection) {
return connection.evalsha(script);
}
}.run(key);
}