redis.clients.jedis.exceptions.JedisConnectionException Java Examples

The following examples show how to use redis.clients.jedis.exceptions.JedisConnectionException. 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: JedisUtil.java    From newblog with Apache License 2.0 7 votes vote down vote up
public void mset(Map<String, String> map) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                if (map != null) {
                    int len = map.size();
                    if (len > 0) {
                        String[] keys = map.keySet().toArray(new String[0]);
                        String[] strings = new String[len * 2];

                        for (int i = 0; i < len; i++) {
                            strings[2 * i] = keys[i];
                            strings[2 * i + 1] = map.get(keys[i]);
                        }
//						logger.info(Arrays.toString(strings));
                        jedis.mset(strings);
                    }
                }
            } else {
                logger.error("mset opt connection null error!");
            }
        } catch (JedisConnectionException e) {
            if (jedis != null) {
                jedis.close();
                jedis = null;
            }
            logger.error("mset connect error:", e);
        } finally {
            returnJedisResource(jedis);
        }
    }
 
Example #2
Source File: ToxiproxyTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Test
public void testConnectionCut() {
    final ToxiproxyContainer.ContainerProxy proxy = toxiproxy.getProxy(redis, 6379);
    final Jedis jedis = createJedis(proxy.getContainerIpAddress(), proxy.getProxyPort());
    jedis.set("somekey", "somevalue");

    assertEquals("access to the container works OK before cutting the connection", "somevalue", jedis.get("somekey"));

    // disableProxy {
    proxy.setConnectionCut(true);

    // for example, expect failure when the connection is cut
    assertThrows("calls fail when the connection is cut",
        JedisConnectionException.class, () -> {
            jedis.get("somekey");
        });

    proxy.setConnectionCut(false);

    // and with the connection re-established, expect success
    assertEquals("access to the container works OK after re-establishing the connection", "somevalue", jedis.get("somekey"));
    // }
}
 
Example #3
Source File: DynoJedisPipeline.java    From dyno with Apache License 2.0 6 votes vote down vote up
public List<Object> syncAndReturnAll() {
    long startTime = System.nanoTime() / 1000;
    try {
        List<Object> result = jedisPipeline.syncAndReturnAll();
        opMonitor.recordPipelineSync();
        return result;
    } catch (JedisConnectionException jce) {
        String msg = "Failed syncAndReturnAll() to host: " + getHostInfo();
        pipelineEx.set(new FatalConnectionException(msg, jce).
                setHost(connection == null ? Host.NO_HOST : connection.getHost()));
        cpMonitor.incOperationFailure(connection == null ? null : connection.getHost(), jce);
        throw jce;
    } finally {
        long duration = System.nanoTime() / 1000 - startTime;
        opMonitor.recordLatency(duration, TimeUnit.MICROSECONDS);
        discardPipeline(false);
        releaseConnection();
    }
}
 
Example #4
Source File: JedisConnectionPool.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized void close(Jedis resource) {		// koushik: removed static, added code to increase robustness
      if (jedisPool != null) {
	try {
		if (resource != null) {
			jedisPool.returnResource(resource);
			resource = null;
		}
	} catch (JedisConnectionException e) {
		jedisPool.returnBrokenResource(resource);
		resource = null;
	} finally {
		if (resource != null) 
			jedisPool.returnResource(resource);
			resource = null;
	}
}
  }
 
Example #5
Source File: RedisSinkTest.java    From bahir-flink with Apache License 2.0 6 votes vote down vote up
private void testDownBehavior(FlinkJedisConfigBase config) throws Exception {
    RedisSink<Tuple2<String, String>> redisSink = new RedisSink<>(config,
        new RedisSinkITCase.RedisCommandMapper(RedisCommand.SADD));

    try {
        redisSink.open(new Configuration());
    } catch (Exception e) {

        // search for nested JedisConnectionExceptions
        // because this is the expected behavior

        Throwable t = e;
        int depth = 0;
        while (!(t instanceof JedisConnectionException)) {
            t = t.getCause();
            if (t == null || depth++ == 20) {
                throw e;
            }
        }
    }
}
 
Example #6
Source File: ConnectionTest.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
@Test
public void getErrorAfterConnectionReset() throws Exception {
  class TestConnection extends Connection {
    public TestConnection() {
      super("localhost", 6379);
    }

    @Override
    protected Connection sendCommand(ProtocolCommand cmd, byte[]... args) {
      return super.sendCommand(cmd, args);
    }
  }

  TestConnection conn = new TestConnection();

  try {
    conn.sendCommand(Command.HMSET, new byte[1024 * 1024 + 1][0]);
    fail("Should throw exception");
  } catch (JedisConnectionException jce) {
    assertEquals("ERR Protocol error: invalid multibulk length", jce.getMessage());
  }
}
 
Example #7
Source File: EnhancedJedisClusterCommand.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public T execute(Jedis connection) {
	try {
		return doExecute(connection);
	} catch (JedisException e) {
		/**
		 * {@link redis.clients.jedis.JedisClusterCommand#runWithRetries}
		 */
		if ((e instanceof JedisRedirectionException) || (e instanceof JedisNoReachableClusterNodeException)) {
			throw e;
		}
		// Print details errors.
		String node = connection.getClient().getHost() + ":" + connection.getClient().getPort();
		String errmsg = format("Couldn't execution jedis command of node: %s", node);
		if (e instanceof JedisConnectionException) {
			throw new JedisConnectionException(errmsg, e);
		}
		throw new JedisException(errmsg, e);
	}
}
 
Example #8
Source File: TestServicesUtils.java    From simpleci with MIT License 6 votes vote down vote up
public static boolean testRedis(String host, int port) {
    final int tryCount = 10;
    for (int i = 1; i <= tryCount; i++) {
        logger.info(String.format("redis: connecting to %s:%s, try %d of %d",   host, port, i, tryCount));
        try {
            Jedis connection = new Jedis(host, port);
            connection.connect();
            connection.close();
            logger.info("Connection to redis established successfully");
            return true;
        } catch (JedisConnectionException e) {
            logger.info("Failed to connect: " + e.getMessage());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                logger.error("", e);
            }
        }
    }
    logger.info(String.format("Failed connect to redis on %s:%d", host, port));
    return false;
}
 
Example #9
Source File: RedisCallable.java    From RedisBungee with Eclipse Public License 1.0 6 votes vote down vote up
private T run(boolean retry) {
    try (Jedis jedis = plugin.getPool().getResource()) {
        return call(jedis);
    } catch (JedisConnectionException e) {
        plugin.getLogger().log(Level.SEVERE, "Unable to get connection", e);

        if (!retry) {
            // Wait one second before retrying the task
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                throw new RuntimeException("task failed to run", e1);
            }
            return run(true);
        }
    }

    throw new RuntimeException("task failed to run");
}
 
Example #10
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getHash(String key) {
    Jedis jedis = null;
    Map<String, String> result = null;
    try {
        jedis = getJedis();
        if (jedis != null) {
            result = jedis.hgetAll(key);
        } else {
            logger.error("hgetall opt connection null error!");
        }
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
            jedis = null;
        }
        logger.error("hgetall value connect error:", e);
    } finally {
        returnJedisResource(jedis);
    }
    return result;
}
 
Example #11
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public void del(String key) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis != null) {
            jedis.del(key);
        } else {
            logger.error("del opt connection null error!");
        }
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
            jedis = null;
        }
        logger.error("delete connect error:", e);
    } finally {
        returnJedisResource(jedis);
    }
}
 
Example #12
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public long increame(String key) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis != null) {
            return jedis.incr(key);
        } else {
            logger.error("increame opt connection null error!");
        }
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
            jedis = null;
        }
        logger.error("increame connect error:", e);
    } finally {
        returnJedisResource(jedis);
    }
    return 0L;
}
 
Example #13
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public void lpush(String key, String ele) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis == null) {
            logger.error("get jedis failed.");
        }
        jedis.lpush(key, ele);
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
            jedis = null;
        }
        logger.error("increame connect error:", e);
    } finally {
        returnJedisResource(jedis);
    }
}
 
Example #14
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessage(String key, String msg) {
    if (logger.isInfoEnabled()) {
        logger.info("redis event: " + key + " = " + msg);
    }
    if (msg.equals(Constants.REGISTER)
            || msg.equals(Constants.UNREGISTER)) {
        try {
            Jedis jedis = jedisPool.getResource();
            boolean isBroken = false;
            try {
                doNotify(jedis, key);
            } catch (JedisConnectionException e){
                isBroken = true;
            } finally {
                if(isBroken){
                    jedisPool.returnBrokenResource(jedis);
                } else {
                    jedisPool.returnResource(jedis);
                }
            }
        } catch (Throwable t) { // TODO 通知失败没有恢复机制保障
            logger.error(t.getMessage(), t);
        }
    }
}
 
Example #15
Source File: JedisClusterConnectionHandler.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
private void initializeSlotsCache(Set<HostAndPort> startNodes, GenericObjectPoolConfig poolConfig) {
  for (HostAndPort hostAndPort : startNodes) {
    Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort());
    try {
      cache.discoverClusterNodesAndSlots(jedis);
      break;
    } catch (JedisConnectionException e) {
      // try next nodes
    } finally {
      if (jedis != null) {
        jedis.close();
      }
    }
  }

  for (HostAndPort node : startNodes) {
    cache.setNodeIfNotExist(node);
  }
}
 
Example #16
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public void zadd(String key, double score, String member) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis == null) {
            logger.error("get jedis fail");
        }
        jedis.zadd(key, score, member);
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
        }
    } finally {
        returnJedisResource(jedis);
    }
}
 
Example #17
Source File: JedisUtil.java    From newblog with Apache License 2.0 6 votes vote down vote up
public void zrem(String key, String member) {
    Jedis jedis = null;
    try {
        jedis = getJedis();
        if (jedis == null) {
            logger.error("get jedis fail");
        }
        jedis.zrem(key, member);
    } catch (JedisConnectionException e) {
        if (jedis != null) {
            jedis.close();
        }
    } finally {
        returnJedisResource(jedis);
    }
}
 
Example #18
Source File: JedisConnectionObject.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns to the Jedis pool a specific instance of allocated Jedis connection resource
 * @param jedisInstance a Jedis instance borrowed from the Jedis Pool
 */
public void returnJedis(Jedis jedisInstance) {
	if (JedisConnectionObject.pool != null) {
		try {
			if (null != jedisInstance && jedisInstance.isConnected()) {
				if (allotedJedis != null) allotedJedis.remove(jedisInstance);
				logger.info("[returnJedis] Returned jedis resource: " + jedisInstance);
				jedisInstance.close();
				jedisInstance = null;
				//JedisConnectionObject.pool.returnResource(jedisInstance);
				connectionSetup = false;
			}
		} catch (JedisConnectionException e) {
			logger.error("JedisConnectionException occurred...");
			if (jedisInstance != null && jedisInstance.isConnected()) jedisInstance.close();
			jedisInstance = null;
			//JedisConnectionObject.pool.returnBrokenResource(jedisInstance);
			connectionSetup = false;
		} 
	}
}
 
Example #19
Source File: DynoJedisPipeline.java    From dyno with Apache License 2.0 6 votes vote down vote up
public void sync() {
    long startTime = System.nanoTime() / 1000;
    try {
        jedisPipeline.sync();
        opMonitor.recordPipelineSync();
    } catch (JedisConnectionException jce) {
        String msg = "Failed sync() to host: " + getHostInfo();
        pipelineEx.set(new FatalConnectionException(msg, jce).
                setHost(connection == null ? Host.NO_HOST : connection.getHost()));
        cpMonitor.incOperationFailure(connection == null ? null : connection.getHost(), jce);
        throw jce;
    } finally {
        long duration = System.nanoTime() / 1000 - startTime;
        opMonitor.recordLatency(duration, TimeUnit.MICROSECONDS);
        discardPipeline(false);
        releaseConnection();
    }
}
 
Example #20
Source File: UCJedisLoader.java    From UltimateChat with GNU General Public License v3.0 6 votes vote down vote up
private boolean connectPool() {
    if (this.pool == null || this.pool.isClosed()) {
        if (auth.isEmpty()) {
            this.pool = new JedisPool(poolCfg, ip, port, 0);
        } else {
            this.pool = new JedisPool(poolCfg, ip, port, 0, auth);
        }

        Jedis jedis = null;
        try {
            jedis = this.pool.getResource();
            jedis.exists(String.valueOf(System.currentTimeMillis()));
            return true;
        } catch (JedisConnectionException e) {
            UChat.get().getLogger().warning("REDIS not connected! Try again with /chat reload, or check the status of your Redis server.");
            pool.destroy();
            pool = null;
            e.printStackTrace();
        }
        return false;
    }
    return true;
}
 
Example #21
Source File: Protocol.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
private static Object process(final RedisInputStream is) {

    final byte b = is.readByte();
    if (b == PLUS_BYTE) {
      return processStatusCodeReply(is);
    } else if (b == DOLLAR_BYTE) {
      return processBulkReply(is);
    } else if (b == ASTERISK_BYTE) {
      return processMultiBulkReply(is);
    } else if (b == COLON_BYTE) {
      return processInteger(is);
    } else if (b == MINUS_BYTE) {
      processError(is);
      return null;
    } else {
      throw new JedisConnectionException("Unknown reply: " + (char) b);
    }
  }
 
Example #22
Source File: JedisConnectionObject.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns to the Jedis pool a specific instance of allocated Jedis connection resource
 * @param jedisInstance a Jedis instance borrowed from the Jedis Pool
 */
public void returnJedis(Jedis jedisInstance) {
	if (JedisConnectionObject.pool != null) {
		try {
			if (null != jedisInstance && jedisInstance.isConnected()) {
				if (allotedJedis != null) allotedJedis.remove(jedisInstance);
				logger.info("[returnJedis] Returned jedis resource: " + jedisInstance);
				jedisInstance.close();
				jedisInstance = null;
				//JedisConnectionObject.pool.returnResource(jedisInstance);
				connectionSetup = false;
			}
		} catch (JedisConnectionException e) {
			logger.error("JedisConnectionException occurred...");
			if (jedisInstance != null && jedisInstance.isConnected()) jedisInstance.close();
			jedisInstance = null;
			//JedisConnectionObject.pool.returnBrokenResource(jedisInstance);
			connectionSetup = false;
		} 
	}
}
 
Example #23
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public boolean isAvailable() {
    for (JedisPool jedisPool : jedisPools.values()) {
        Jedis jedis = jedisPool.getResource();
        boolean isBroken = false;
        try {
            if (jedis.isConnected()) {
                return true; // 至少需单台机器可用
            }
        } catch (JedisConnectionException e) {
            isBroken = true;
        } finally {
            if (isBroken) {
                jedisPool.returnBrokenResource(jedis);
            } else {
                jedisPool.returnResource(jedis);
            }
        }
    }
    return false;
}
 
Example #24
Source File: RedisSinkBolt.java    From jstorm with Apache License 2.0 6 votes vote down vote up
private String retrySet(byte[] key, byte[] value) {
    int retry = 0;
    String ret;
    while (true) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            ret = jedis.set(key, value);
            return ret;
        } catch (JedisConnectionException e) {
            if (jedis != null) {
                pool.returnBrokenResource(jedis);
                jedis = null;
            }
            if (retry > retryLimit) {
                throw e;
            }
            retry++;
        } finally {
            if (jedis != null) {
                pool.returnResource(jedis);
            }
        }
        
    }
}
 
Example #25
Source File: Protocol.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
private static void sendCommand(final RedisOutputStream os, final byte[] command,
    final byte[]... args) {
  try {
    os.write(ASTERISK_BYTE);
    os.writeIntCrLf(args.length + 1);
    os.write(DOLLAR_BYTE);
    os.writeIntCrLf(command.length);
    os.write(command);
    os.writeCrLf();

    for (final byte[] arg : args) {
      os.write(DOLLAR_BYTE);
      os.writeIntCrLf(arg.length);
      os.write(arg);
      os.writeCrLf();
    }
  } catch (IOException e) {
    throw new JedisConnectionException(e);
  }
}
 
Example #26
Source File: RedisTokenstore.java    From spring-security-otp with Apache License 2.0 6 votes vote down vote up
@Override
public void putToken(String username, String token) {
	// Authenticate if we aren't already
	if (!authenticated) {
		if (!authenticate()) {
			throw new OtpAuthenticationException("Error adding token.");
		}
	}
	
	// Setup and execute transaction
	try {
		jedis.setex(username, maxLifetime, token);
		logger.debug("Token, '{}' added to Redis server.", token);
	} catch (JedisConnectionException e) {
		logger.error("Error connecting to Redis.  Exception message was: "
				+ e.getMessage());
		throw new OtpAuthenticationException("Error adding token.", e);
	}
}
 
Example #27
Source File: RedisStore.java    From session-managers with Apache License 2.0 6 votes vote down vote up
@Override
public String[] keys() {
    return this.lockTemplate.withReadLock(new LockTemplate.LockedOperation<String[]>() {

        @Override
        public String[] invoke() {
            try {
                Set<String> sessions = RedisStore.this.jedisClient.getSessions(getSessionKeyPrefix());
                return sessions.toArray(new String[sessions.size()]);
            } catch (JedisConnectionException e) {
                RedisStore.this.logger.error("Unable to get the keys of persisted sessions", e);
                return new String[0];
            }
        }
    });
}
 
Example #28
Source File: ShardedJedisPoolStream.java    From RedisDirectory with Apache License 2.0 5 votes vote down vote up
@Override
public List<byte[]> loadFileOnce(String fileDataKey, String fileName, long blockSize) {
    ShardedJedis shardedJedis = getShardedJedis();
    ShardedJedisPipeline pipelined = shardedJedis.pipelined();
    List<byte[]> res = new ArrayList<>();
    List<Response<byte[]>> temps = new ArrayList<>();
    int temp = 0;
    //如果不分批次sync容易read time out和Java heap space
    while (temp < blockSize) {
        Response<byte[]> data = pipelined.hget(fileDataKey.getBytes(), getBlockName(fileName, temp));
        temps.add(data);
        if (temp % Constants.SYNC_COUNT == 0) {
            pipelined.sync();
            res.addAll(temps.stream().map(response -> uncompressFilter(response.get())).collect(Collectors.toList()));
            temps.clear();
            pipelined = shardedJedis.pipelined();
        }
        temp++;
    }
    try {
        pipelined.sync();
    } catch (JedisConnectionException e) {
        log.error("pipelined = {}, blockSize = {}!", pipelined.toString(), blockSize);
        log.error("", e);
    } finally {
        shardedJedis.close();
    }
    res.addAll(temps.stream().map(response -> uncompressFilter(response.get())).collect(Collectors.toList()));
    temps.clear();
    return res;
}
 
Example #29
Source File: JedisPubSub.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
public void subscribe(String... channels) {
  if (client == null) {
    throw new JedisConnectionException("JedisPubSub is not subscribed to a Jedis instance.");
  }
  client.subscribe(channels);
  client.flush();
}
 
Example #30
Source File: JedisPubSub.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
public void unsubscribe(String... channels) {
  if (client == null) {
    throw new JedisConnectionException("JedisPubSub is not subscribed to a Jedis instance.");
  }
  client.unsubscribe(channels);
  client.flush();
}