Connection.java 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
package redis.clients.jedis;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import com.sun.org.apache.bcel.internal.generic.Select;
import redis.clients.jedis.Protocol.Command;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.nio.NioTcpComponent;
import redis.clients.jedis.nio.Operation;
import redis.clients.jedis.nio.RedisNioOutputStream;
import redis.clients.util.IOUtils;
import redis.clients.util.RedisInputStream;
import redis.clients.util.RedisOutputStream;
import redis.clients.util.SafeEncoder;

public class Connection implements Closeable {

    private static final byte[][] EMPTY_ARGS = new byte[0][];

    private String host = Protocol.DEFAULT_HOST;
    private int port = Protocol.DEFAULT_PORT;
    private Socket socket;
    private RedisOutputStream outputStream;
    private RedisInputStream inputStream;
    private int pipelinedCommands = 0;
    private int connectionTimeout = Protocol.DEFAULT_TIMEOUT;
    private int soTimeout = Protocol.DEFAULT_TIMEOUT;
    private boolean broken = false;
    private boolean ssl;
    private SSLSocketFactory sslSocketFactory;
    private SSLParameters sslParameters;
    private HostnameVerifier hostnameVerifier;


    /**
     * nio >>------相关修改 ------ jie.pang
     **/

    private ByteBuffer rBf = ByteBuffer.allocate(1024);


    //写的队列
    private LinkedBlockingQueue<Operation> writeQueue = new LinkedBlockingQueue<Operation>();

    //等待读取的队列  (写出成功之后,移入到待读取的队列)
    private LinkedBlockingQueue<Operation> readQueue = new LinkedBlockingQueue<Operation>();

    //读取成功之后放入结果的队列
    private LinkedBlockingQueue<Operation>  resQueue = new LinkedBlockingQueue<Operation>();


//    private


    private volatile boolean nioConnection = false;

    private ReentrantLock nioConnectInitLock = new ReentrantLock();

    private NioTcpComponent tcpComponent;

    private SocketChannel channel;

    private SelectionKey selectionKey;


    /**
     * 初始化Nio connection
     */
    public void nioConnect() {

        if (nioConnection) {
            return;
        }

        try {
            //加锁防止并发执行初始化
            nioConnectInitLock.lock();
            tcpComponent = NioTcpComponent.instance();
            this.channel = tcpComponent.registChannel(this);
            nioConnection = true;
        } finally {
            nioConnectInitLock.unlock();
        }

    }


    public Connection sendNioCommand(final Command cmd, final byte[]... args) throws IOException {

        //连接
        nioConnect();

        //发送命令
        RedisNioOutputStream redisNioOutputStream = new RedisNioOutputStream();
        Protocol.sendCommand(redisNioOutputStream, cmd, args);
        //命令
        byte[] fullCommand = redisNioOutputStream.toBytes();

        Operation operation = new Operation(fullCommand);
        //放入队列成功
        if (writeQueue.offer(operation)) {
            //通知写数据
            tcpComponent.notifyWrite(channel, this);
        }

        return this;
    }

    //循环去写
    public void callBack2Write(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();

        Operation operation = writeQueue.peek();
        while (operation != null) {
            ByteBuffer wBf = operation.getByteBuffer();
            channel.write(wBf);
            if (wBf.hasRemaining()) {
                int write = channel.write(wBf);
                if (write == 0) {
                    wBf.compact();
                    return;
                }
            }

            //写完之后移除并放入待读取队列
            readQueue.offer(writeQueue.poll());
            operation = writeQueue.peek();
        }

        //移除写的事件监听
        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    }


    //循环去读取
    public void callBack2Read(SelectionKey key) throws IOException {

        //没有待读取的 opreation
        Operation operation = readQueue.peek();
        if (operation == null) {
            return;
        }

        int read = channel.read(rBf);
        //循环读取
        while (read > 0) {
            rBf.flip();
            while (rBf.hasRemaining()) {
                byte b = rBf.get();
//                System.out.print((char)b);
                boolean over = operation.processResult(b);
//                System.out.println("==="+operation.hashCode());
                if (over) {
//                    readQueue.poll();
                    resQueue.offer(readQueue.poll());
                    operation = readQueue.peek();
                }
            }
            rBf.clear();
            read = channel.read(rBf);
        }
    }


    public void callBackSetSelectionKey(SelectionKey key) {
        if (this.selectionKey == null) {
            this.selectionKey = key;
        }
    }

    /**
     * <<------nio 相关修改 ---------- jie.pang
     **/
    public Connection() {
    }

    public Connection(final String host) {
        this.host = host;
    }

    public Connection(final String host, final int port) {
        this.host = host;
        this.port = port;
    }

    public Connection(final String host, final int port, final boolean ssl) {
        this.host = host;
        this.port = port;
        this.ssl = ssl;
    }

    public Connection(final String host, final int port, final boolean ssl,
                      SSLSocketFactory sslSocketFactory, SSLParameters sslParameters,
                      HostnameVerifier hostnameVerifier) {
        this.host = host;
        this.port = port;
        this.ssl = ssl;
        this.sslSocketFactory = sslSocketFactory;
        this.sslParameters = sslParameters;
        this.hostnameVerifier = hostnameVerifier;
    }

    public Socket getSocket() {
        return socket;
    }

    public int getConnectionTimeout() {
        return connectionTimeout;
    }

    public int getSoTimeout() {
        return soTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public void setSoTimeout(int soTimeout) {
        this.soTimeout = soTimeout;
    }

    public void setTimeoutInfinite() {
        try {
//            if (!isConnected()) {
//                connect();
//            }
            connect();
            channel.socket().setSoTimeout(0);
        } catch (SocketException ex) {
            broken = true;
            throw new JedisConnectionException(ex);
        }
    }

    public void rollbackTimeout() {
        try {
            socket.setSoTimeout(soTimeout);
        } catch (SocketException ex) {
            broken = true;
            throw new JedisConnectionException(ex);
        }
    }

    protected Connection sendCommand(final Command cmd, final String... args) {
        final byte[][] bargs = new byte[args.length][];
        for (int i = 0; i < args.length; i++) {
            bargs[i] = SafeEncoder.encode(args[i]);
        }
        return sendCommand(cmd, bargs);
    }

    protected Connection sendCommand(final Command cmd) {
        return sendCommand(cmd, EMPTY_ARGS);
    }

    protected Connection sendCommand(final Command cmd, final byte[]... args) {
        try {
            /*connect();
            Protocol.sendCommand(outputStream, cmd, args);*/

            pipelinedCommands++;
            return sendNioCommand(cmd, args);
        } catch (IOException ex) {
      /*
       * 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.
         */
//            }
            broken = true;
            throw new JedisConnectionException(ex);
            // Any other exceptions related to connection?
        }
    }

    public String getHost() {
        return host;
    }

    public void setHost(final String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(final int port) {
        this.port = port;
    }

    public void connect() {
         nioConnect();
//        if (!isConnected()) {
//            try {
//                socket = new Socket();
//                // ->@wjw_add
//                socket.setReuseAddress(true);
//                socket.setKeepAlive(true); // Will monitor the TCP connection is
//                // valid
//                socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
//                // ensure timely delivery of data
//                socket.setSoLinger(true, 0); // Control calls close () method,
//                // the underlying socket is closed
//                // immediately
//                // <-@wjw_add
//
//                socket.connect(new InetSocketAddress(host, port), connectionTimeout);
//                socket.setSoTimeout(soTimeout);
//
//                if (ssl) {
//                    if (null == sslSocketFactory) {
//                        sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
//                    }
//                    socket = (SSLSocket) sslSocketFactory.createSocket(socket, host, port, true);
//                    if (null != sslParameters) {
//                        ((SSLSocket) socket).setSSLParameters(sslParameters);
//                    }
//                    if ((null != hostnameVerifier) &&
//                            (!hostnameVerifier.verify(host, ((SSLSocket) socket).getSession()))) {
//                        String message = String.format(
//                                "The connection to '%s' failed ssl/tls hostname verification.", host);
//                        throw new JedisConnectionException(message);
//                    }
//                }
//
//                outputStream = new RedisOutputStream(socket.getOutputStream());
//                inputStream = new RedisInputStream(socket.getInputStream());
//            } catch (IOException ex) {
//                broken = true;
//                throw new JedisConnectionException(ex);
//            }
//        }
    }


    @Override
    public void close() {
        disconnect();
    }

    public void disconnect() {

        if (channel != null) {
            IOUtils.closeQuietly(channel);
        }

        if (selectionKey != null) {
            selectionKey.cancel();
        }


//        if (isConnected()) {
//            try {
//                outputStream.flush();
//                socket.close();
//            } catch (IOException ex) {
//                broken = true;
//                throw new JedisConnectionException(ex);
//            } finally {
//                IOUtils.closeQuietly(socket);
//            }
//        }
    }

    public boolean isConnected() {

        return channel!=null;

//        return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()
//                && !socket.isInputShutdown() && !socket.isOutputShutdown();
    }

    public String getStatusCodeReply() {
//        flush();
        pipelinedCommands--;

        try {
            Operation operation = resQueue.take();
            byte[] resp = (byte[]) operation.getOperationFuture().get();
            return SafeEncoder.encode(resp);
        } catch (InterruptedException e) {
            throw new JedisConnectionException(e);
        } catch (ExecutionException e) {
            throw new JedisConnectionException(e);
        }

//        final byte[] resp = (byte[]) readProtocolWithCheckingBroken();
//        if (null == resp) {
//            return null;
//        } else {
//            return SafeEncoder.encode(resp);
//        }
    }

    public String getBulkReply() {

        final byte[] result = getBinaryBulkReply();
        if (null != result) {
            return SafeEncoder.encode(result);
        } else {
            return null;
        }
    }

    public byte[] getBinaryBulkReply() {
        flush();
        pipelinedCommands--;
        return (byte[]) readProtocolWithCheckingBroken();
    }

    public Long getIntegerReply() {
        flush();
        pipelinedCommands--;
        return (Long) readProtocolWithCheckingBroken();
    }

    public List<String> getMultiBulkReply() {
        return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply());
    }

    @SuppressWarnings("unchecked")
    public List<byte[]> getBinaryMultiBulkReply() {
        flush();
        pipelinedCommands--;
        return (List<byte[]>) readProtocolWithCheckingBroken();
    }

    public void resetPipelinedCount() {
        pipelinedCommands = 0;
    }

    @SuppressWarnings("unchecked")
    public List<Object> getRawObjectMultiBulkReply() {
        return (List<Object>) readProtocolWithCheckingBroken();
    }

    public List<Object> getObjectMultiBulkReply() {
        flush();
        pipelinedCommands--;
        return getRawObjectMultiBulkReply();
    }

    @SuppressWarnings("unchecked")
    public List<Long> getIntegerMultiBulkReply() {
        flush();
        pipelinedCommands--;
        return (List<Long>) readProtocolWithCheckingBroken();
    }

    public List<Object> getAll() {
        return getAll(0);
    }

    public List<Object> getAll(int except) {
        List<Object> all = new ArrayList<Object>();
        flush();
        while (pipelinedCommands > except) {
            try {
                all.add(readProtocolWithCheckingBroken());
            } catch (JedisDataException e) {
                all.add(e);
            }
            pipelinedCommands--;
        }
        return all;
    }

    public Object getOne() {
        flush();
        pipelinedCommands--;
        return readProtocolWithCheckingBroken();
    }

    public boolean isBroken() {
        return broken;
    }

    protected void flush() {
//        try {
//            outputStream.flush();
//        } catch (IOException ex) {
//            broken = true;
//            throw new JedisConnectionException(ex);
//        }
    }

    protected Object readProtocolWithCheckingBroken() {

        Operation operation = null;
        try {
            operation = resQueue.take();
            Object o = operation.getOperationFuture().get();
            return o;
        } catch (InterruptedException e) {
            throw new JedisConnectionException(e);
        } catch (ExecutionException e) {
            throw new JedisConnectionException(e);
        }
//        try {
//            return Protocol.read(inputStream);
//        } catch (JedisConnectionException exc) {
//            broken = true;
//            throw exc;
//        }
    }
}