Java Code Examples for redis.clients.jedis.exceptions.JedisConnectionException

The following examples show how to use redis.clients.jedis.exceptions.JedisConnectionException. 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
@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 2
Source Project: cachecloud   Source File: ConnectionTest.java    License: 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 3
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 4
Source Project: dyno   Source File: DynoJedisPipeline.java    License: 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 5
Source Project: RedisBungee   Source File: RedisCallable.java    License: 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 6
Source Project: newblog   Source File: JedisUtil.java    License: 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 7
Source Project: newblog   Source File: JedisUtil.java    License: 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 8
Source Project: newblog   Source File: JedisUtil.java    License: 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 9
Source Project: session-managers   Source File: RedisStore.java    License: 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 10
Source Project: newblog   Source File: JedisUtil.java    License: 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 11
Source Project: cachecloud   Source File: JedisClusterConnectionHandler.java    License: 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 12
Source Project: newblog   Source File: JedisUtil.java    License: 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 13
Source Project: newblog   Source File: JedisUtil.java    License: 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 14
Source Project: dubbox-hystrix   Source File: RedisRegistry.java    License: 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 15
Source Project: jstorm   Source File: RedisSinkBolt.java    License: 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 16
Source Project: spring-security-otp   Source File: RedisTokenstore.java    License: 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 17
Source Project: testcontainers-java   Source File: ToxiproxyTest.java    License: 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 18
Source Project: cachecloud   Source File: Protocol.java    License: 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 19
/**
 * 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 20
Source Project: cachecloud   Source File: Protocol.java    License: 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 21
Source Project: UltimateChat   Source File: UCJedisLoader.java    License: 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 22
Source Project: dyno   Source File: DynoJedisPipeline.java    License: 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 23
/**
 * 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 24
Source Project: dubbox   Source File: RedisRegistry.java    License: 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 25
Source Project: bahir-flink   Source File: RedisSinkTest.java    License: 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 26
Source Project: simpleci   Source File: TestServicesUtils.java    License: 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 27
Source Project: cachecloud   Source File: JedisClusterConnectionHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void renewSlotCache(Jedis jedis) {
  try {
    cache.discoverClusterSlots(jedis);
  } catch (JedisConnectionException e) {
    renewSlotCache();
  }
}
 
Example 28
Source Project: fastjgame   Source File: RedisEventLoop.java    License: Apache License 2.0 5 votes vote down vote up
private void handleException(Throwable e) {
    if (e instanceof JedisConnectionException) {
        // 关闭当前连接
        closeConnection();

        // 尝试一次恢复连接
        connectSafely();
    }
}
 
Example 29
Source Project: logback-redis   Source File: BufferedJedisRPusherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void dont_send_on_too_many_failures() throws InterruptedException {
    when(pipeline.rpush(anyString(), anyVararg())).thenThrow(new JedisConnectionException(""));
    for (int i = 0; i < DEFAULT_QUEUE_ITEMS; i++) {
        writer.append(mock(DeferredProcessingAware.class));
    }
    verify(client, times(2)).getPipeline();
    verify(client, times(2)).reconnect();
    verify(pipeline, times(2)).rpush(anyString(), anyVararg());
    verify(pipeline, times(0)).sync();
}
 
Example 30
Source Project: RedisBungee   Source File: RedisBungee.java    License: Eclipse Public License 1.0 5 votes vote down vote up
final void sendChannelMessage(String channel, String message) {
    try (Jedis jedis = pool.getResource()) {
        jedis.publish(channel, message);
    } catch (JedisConnectionException e) {
        // Redis server has disappeared!
        getLogger().log(Level.SEVERE, "Unable to get connection from pool - did your Redis server go away?", e);
        throw new RuntimeException("Unable to publish channel message", e);
    }
}