Search in sources :

Example 26 with JedisConnectionException

use of redis.clients.jedis.exceptions.JedisConnectionException in project MSEC by Tencent.

the class JedisHelper method RecoverSet.

//Input ArrayList String: IP:Port(M)
public void RecoverSet(ArrayList<String> ips) throws JedisHelperException {
    Logger logger = Logger.getLogger(JedisHelper.class);
    //1.Check status, replicate, hash slot empty and remove slave first
    HashMap<String, ClusterStatus> cluster_map = CheckStatus();
    try {
        //1. remove fail servers
        for (String node : fail_nodes) {
            for (Map.Entry<String, Jedis> entry : cluster.entrySet()) {
                if (entry.getValue().clusterNodes().contains(node)) {
                    entry.getValue().clusterForget(node);
                    logger.info(String.format("%s|forget|%s", entry.getKey(), node));
                }
            }
        }
        //2. add new ip
        for (String host : ips) {
            String[] ip_pair = host.split(":");
            Jedis jedis = new Jedis(ip_pair[0], Integer.parseInt(ip_pair[1]));
            jedis.connect();
            cluster.put(host, jedis);
            logger.info("clusterMeet|" + ip + ":" + port + "|" + host + "|" + cluster.get(ip + ":" + port));
            cluster.get(ip + ":" + port).clusterMeet(ip_pair[0], Integer.parseInt(ip_pair[1]));
            updateStatus(ip_pair[0], Integer.parseInt(ip_pair[1]), "Cluster meets.");
        }
        //3. waitForClusterReady
        logger.info("waitReady|" + cluster.values().size());
        if (!waitForClusterReady(new ArrayList<Jedis>(cluster.values()))) {
            updateStatus("[ERROR] Cluster meet fails.");
            return;
        }
        //4. clusterReplicate
        String node_id = getNodeId(cluster.get(ip + ":" + port));
        for (String host : ips) {
            cluster.get(host).clusterReplicate(node_id);
            String[] ip_pair = host.split(":");
            updateStatus(ip_pair[0], Integer.parseInt(ip_pair[1]), "Done.");
        }
        CheckStatus();
    } catch (JedisConnectionException e) {
        logger.error("Exception|", e);
        throw e;
    } catch (InterruptedException e) {
        logger.error("Exception|", e);
        for (int i = 0; i < ips.size(); i++) {
            String[] ip_pair = ips.get(i).split(":");
            updateStatus(ip_pair[0], Integer.parseInt(ip_pair[1]), "[ERROR] Interrupted.");
        }
    }
}
Also used : Logger(org.apache.log4j.Logger) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Example 27 with JedisConnectionException

use of redis.clients.jedis.exceptions.JedisConnectionException in project cachecloud by sohutv.

the class Connection method sendCommand.

protected Connection sendCommand(final ProtocolCommand cmd, final byte[]... args) {
    try {
        //统计开始
        UsefulDataModel costModel = UsefulDataModel.getCostModel(threadLocal);
        costModel.setCommand(cmd.toString().toLowerCase());
        costModel.setStartTime(System.currentTimeMillis());
        connect();
        Protocol.sendCommand(outputStream, cmd, args);
        return this;
    } catch (JedisConnectionException ex) {
        UsefulDataCollector.collectException(ex, getHostPort(), System.currentTimeMillis());
        /*
       * When client send request which formed by invalid protocol, Redis send back error message
       * before close connection. We try to read it to provide reason of failure.
       */
        try {
            String errorMessage = Protocol.readErrorLineIfPossible(inputStream);
            if (errorMessage != null && errorMessage.length() > 0) {
                ex = new JedisConnectionException(errorMessage, ex.getCause());
            }
        } catch (Exception e) {
        /*
         * Catch any IOException or JedisConnectionException occurred from InputStream#read and just
         * ignore. This approach is safe because reading error message is optional and connection
         * will eventually be closed.
         */
        }
        // Any other exceptions related to connection?
        broken = true;
        throw ex;
    }
}
Also used : UsefulDataModel(com.sohu.tv.jedis.stat.model.UsefulDataModel) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException) JedisDataException(redis.clients.jedis.exceptions.JedisDataException) IOException(java.io.IOException) SocketException(java.net.SocketException) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Example 28 with JedisConnectionException

use of redis.clients.jedis.exceptions.JedisConnectionException in project cachecloud by sohutv.

the class Connection method connect.

public void connect() {
    if (!isConnected()) {
        try {
            socket = new Socket();
            // ->@wjw_add
            socket.setReuseAddress(true);
            // Will monitor the TCP connection is
            socket.setKeepAlive(true);
            // valid
            // Socket buffer Whetherclosed, to
            socket.setTcpNoDelay(true);
            // ensure timely delivery of data
            // Control calls close () method,
            socket.setSoLinger(true, 0);
            // the underlying socket is closed
            // immediately
            // <-@wjw_add
            socket.connect(new InetSocketAddress(host, port), connectionTimeout);
            socket.setSoTimeout(soTimeout);
            outputStream = new RedisOutputStream(socket.getOutputStream());
            inputStream = new RedisInputStream(socket.getInputStream());
        } catch (IOException ex) {
            UsefulDataCollector.collectException(ex, getHostPort(), System.currentTimeMillis());
            broken = true;
            throw new JedisConnectionException(ex);
        }
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) RedisOutputStream(redis.clients.util.RedisOutputStream) RedisInputStream(redis.clients.util.RedisInputStream) IOException(java.io.IOException) Socket(java.net.Socket) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Example 29 with JedisConnectionException

use of redis.clients.jedis.exceptions.JedisConnectionException in project cachecloud by sohutv.

the class JedisClusterCommand method runWithRetries.

private T runWithRetries(byte[] key, int redirections, boolean tryRandomNode, boolean asking) {
    if (redirections <= 0) {
        JedisClusterMaxRedirectionsException exception = new JedisClusterMaxRedirectionsException("Too many Cluster redirections? key=" + SafeEncoder.encode(key));
        //收集
        UsefulDataCollector.collectException(exception, "", System.currentTimeMillis(), ClientExceptionType.REDIS_CLUSTER);
        throw exception;
    }
    Jedis connection = null;
    try {
        if (asking) {
            // TODO: Pipeline asking with the original command to make it
            // faster....
            connection = askConnection.get();
            connection.asking();
            // if asking success, reset asking flag
            asking = false;
        } else {
            if (tryRandomNode) {
                connection = connectionHandler.getConnection();
            } else {
                connection = connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key));
            }
        }
        return execute(connection);
    } catch (JedisConnectionException jce) {
        if (tryRandomNode) {
            // maybe all connection is down
            throw jce;
        }
        // release current connection before recursion
        releaseConnection(connection);
        connection = null;
        // retry with random connection
        return runWithRetries(key, redirections - 1, true, asking);
    } catch (JedisRedirectionException jre) {
        // if MOVED redirection occurred,
        if (jre instanceof JedisMovedDataException) {
            // it rebuilds cluster's slot cache
            // recommended by Redis cluster specification
            this.connectionHandler.renewSlotCache(connection);
        }
        // release current connection before recursion or renewing
        releaseConnection(connection);
        connection = null;
        if (jre instanceof JedisAskDataException) {
            asking = true;
            askConnection.set(this.connectionHandler.getConnectionFromNode(jre.getTargetNode()));
        } else if (jre instanceof JedisMovedDataException) {
        } else {
            throw new JedisClusterException(jre);
        }
        return runWithRetries(key, redirections - 1, false, asking);
    } finally {
        releaseConnection(connection);
    }
}
Also used : JedisClusterException(redis.clients.jedis.exceptions.JedisClusterException) JedisClusterMaxRedirectionsException(redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException) JedisMovedDataException(redis.clients.jedis.exceptions.JedisMovedDataException) JedisAskDataException(redis.clients.jedis.exceptions.JedisAskDataException) JedisRedirectionException(redis.clients.jedis.exceptions.JedisRedirectionException) JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Example 30 with JedisConnectionException

use of redis.clients.jedis.exceptions.JedisConnectionException in project cachecloud by sohutv.

the class Protocol method processBulkReply.

private static byte[] processBulkReply(final RedisInputStream is) {
    final int len = is.readIntCrLf();
    if (len == -1) {
        return null;
    }
    final byte[] read = new byte[len];
    int offset = 0;
    while (offset < len) {
        final int size = is.read(read, offset, (len - offset));
        if (size == -1)
            throw new JedisConnectionException("It seems like server has closed the connection.");
        offset += size;
    }
    // read 2 more bytes for the command delimiter
    is.readByte();
    is.readByte();
    return read;
}
Also used : JedisConnectionException(redis.clients.jedis.exceptions.JedisConnectionException)

Aggregations

JedisConnectionException (redis.clients.jedis.exceptions.JedisConnectionException)35 Jedis (redis.clients.jedis.Jedis)15 IOException (java.io.IOException)8 Logger (org.apache.log4j.Logger)8 Test (org.junit.Test)7 JedisDataException (redis.clients.jedis.exceptions.JedisDataException)5 URI (java.net.URI)3 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)3 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)3 JedisShardInfo (redis.clients.jedis.JedisShardInfo)3 UsefulDataModel (com.sohu.tv.jedis.stat.model.UsefulDataModel)2 InetSocketAddress (java.net.InetSocketAddress)2 Socket (java.net.Socket)2 SSLParameters (javax.net.ssl.SSLParameters)2 BinaryJedis (redis.clients.jedis.BinaryJedis)2 JedisSentinelPool (redis.clients.jedis.JedisSentinelPool)2 Transaction (redis.clients.jedis.Transaction)2 RedisInputStream (redis.clients.util.RedisInputStream)2 RedisOutputStream (redis.clients.util.RedisOutputStream)2 ServerInfo (beans.dbaccess.ServerInfo)1