Jedis 源代码阅读一 —— Jedis
这是jedis 源代码文件夹,我们接下来选择性阅读重要的接口以及实现。
└─redis
    └─clients
        ├─jedis
        │  │  BinaryClient.java
        │  │  BinaryJedis.java
        │  │  BinaryJedisCluster.java
        │  │  BinaryJedisPubSub.java
        │  │  BinaryShardedJedis.java
        │  │  BitOP.java
        │  │  BitPosParams.java
        │  │  Builder.java
        │  │  BuilderFactory.java
        │  │  Client.java
        │  │  Connection.java
        │  │  DebugParams.java
        │  │  GeoCoordinate.java
        │  │  GeoRadiusResponse.java
        │  │  GeoUnit.java
        │  │  HostAndPort.java
        │  │  Jedis.java
        │  │  JedisCluster.java
        │  │  JedisClusterCommand.java
        │  │  JedisClusterConnectionHandler.java
        │  │  JedisClusterInfoCache.java
        │  │  JedisFactory.java
        │  │  JedisMonitor.java
        │  │  JedisPool.java
        │  │  JedisPoolAbstract.java
        │  │  JedisPoolConfig.java
        │  │  JedisPubSub.java
        │  │  JedisSentinelPool.java
        │  │  JedisShardInfo.java
        │  │  JedisSlotBasedConnectionHandler.java
        │  │  MultiKeyPipelineBase.java
        │  │  Pipeline.java
        │  │  PipelineBase.java
        │  │  Protocol.java
        │  │  Queable.java
        │  │  Response.java
        │  │  ScanParams.java
        │  │  ScanResult.java
        │  │  ShardedJedis.java
        │  │  ShardedJedisPipeline.java
        │  │  ShardedJedisPool.java
        │  │  SortingParams.java
        │  │  Transaction.java
        │  │  Tuple.java
        │  │  ZParams.java
        │  │
        │  ├─commands
        │  │      AdvancedBinaryJedisCommands.java
        │  │      AdvancedJedisCommands.java
        │  │      BasicCommands.java
        │  │      BasicRedisPipeline.java
        │  │      BinaryJedisClusterCommands.java
        │  │      BinaryJedisCommands.java
        │  │      BinaryRedisPipeline.java
        │  │      BinaryScriptingCommands.java
        │  │      BinaryScriptingCommandsPipeline.java
        │  │      ClusterCommands.java
        │  │      ClusterPipeline.java
        │  │      Commands.java
        │  │      JedisClusterBinaryScriptingCommands.java
        │  │      JedisClusterCommands.java
        │  │      JedisClusterScriptingCommands.java
        │  │      JedisCommands.java
        │  │      MultiKeyBinaryCommands.java
        │  │      MultiKeyBinaryJedisClusterCommands.java
        │  │      MultiKeyBinaryRedisPipeline.java
        │  │      MultiKeyCommands.java
        │  │      MultiKeyCommandsPipeline.java
        │  │      MultiKeyJedisClusterCommands.java
        │  │      ProtocolCommand.java
        │  │      RedisPipeline.java
        │  │      ScriptingCommands.java
        │  │      ScriptingCommandsPipeline.java
        │  │      SentinelCommands.java
        │  │
        │  ├─exceptions
        │  │      InvalidURIException.java
        │  │      JedisAskDataException.java
        │  │      JedisClusterCrossSlotException.java
        │  │      JedisClusterException.java
        │  │      JedisClusterMaxRedirectionsException.java
        │  │      JedisConnectionException.java
        │  │      JedisDataException.java
        │  │      JedisException.java
        │  │      JedisMovedDataException.java
        │  │      JedisRedirectionException.java
        │  │
        │  └─params
        │      │  Params.java
        │      │
        │      ├─geo
        │      │      GeoRadiusParam.java
        │      │
        │      ├─set
        │      │      SetParams.java
        │      │
        │      └─sortedset
        │              ZAddParams.java
        │              ZIncrByParams.java
        │
        └─util
                ClusterNodeInformation.java
                ClusterNodeInformationParser.java
                Hashing.java
                IOUtils.java
                JedisByteHashMap.java
                JedisClusterCRC16.java
                JedisURIHelper.java
                KeyMergeUtil.java
                MurmurHash.java
                Pool.java
                RedisInputStream.java
                RedisOutputStream.java
                SafeEncoder.java
                Sharded.java
                ShardInfo.java
                Slowlog.javaJedis.java
 
我们每次使用jedis都会初始化一个jedis对象,对下面代码肯定不会陌生:
public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands,
    AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands {
  protected JedisPoolAbstract dataSource = null;
  public Jedis() {
    super();
  }
  public Jedis(final String host) {
    super(host);
  }
  public Jedis(final String host, final int port) {
    super(host, port);
  }
............Jedis对象调用父类BinaryJedis构造器:
public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands,
        AdvancedBinaryJedisCommands, BinaryScriptingCommands, Closeable {
    protected Client client = null;
    protected Transaction transaction = null;
    protected Pipeline pipeline = null;
    public BinaryJedis() {
        client = new Client();
    }
    public BinaryJedis(final String host) {
        URI uri = URI.create(host);
        if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
            initializeClientFromURI(uri);
        } else {
            client = new Client(host);
        }
    }
    public BinaryJedis(final String host, final int port) {
        client = new Client(host, port);
    }
    public BinaryJedis(final String host, final int port, final int timeout) {
        client = new Client(host, port);
        client.setConnectionTimeout(timeout);
        client.setSoTimeout(timeout);
    }实际上,new Jedis()的初始化中。最重要的是new Client()这句代码。
Client 继承自 BinaryClient
public class Client extends BinaryClient implements Commands {
  public Client() {
    super();
  }
而BinaryClient又继承自Collection
public class BinaryClient extends Connection {
 ............
  private String password;
  private int db;
  private boolean isInWatch;
............
  public BinaryClient() {
    super();
  }
............接着我们来看Collection代码:
    public class Connection implements Closeable {
    .....
    protected Connection sendCommand(final ProtocolCommand cmd, final String... args) {
        final byte[][] bargs = new byte[args.length][];
        for (int i = 0; i < args.length; i++) {
            // 对cmd判空并返回bytes
            bargs[i] = SafeEncoder.encode(args[i]);
        }
        return sendCommand(cmd, bargs);
    }
    protected Connection sendCommand(final ProtocolCommand cmd) {
        return sendCommand(cmd, EMPTY_ARGS);
    }
    protected Connection sendCommand(final ProtocolCommand cmd, final byte[]... args) {
        try {
            // 1.建立Socket连接
            connect();
            // 2.依照协议完毕IO操作,也就是命令的运行
            Protocol.sendCommand(outputStream, cmd, args);
            return this;
        } catch (JedisConnectionException 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.
                 */
            }
            // Any other exceptions related to connection?
broken = true;
            throw ex;
        }
    }
    ...
    // 建立Sock连接
    public void connect() {
        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);
                outputStream = new RedisOutputStream(socket.getOutputStream());
                inputStream = new RedisInputStream(socket.getInputStream());
            } catch (IOException ex) {
                broken = true;
                throw new JedisConnectionException(ex);
            }
        }
    }
    ...在这里完毕了Socket连接。并返回这个Socket. 
 
每次我们使用Jedis去运行命令。都是这个持有Soket的client去运行的。
比方:
    /**
     * Get the value of the specified key. If the key does not exist null is
     * returned. If the value stored at key is not a string an error is returned
     * because GET can only handle string values.
     * <p>
     * Time complexity: O(1)
     *
     * @param key
     * @return Bulk reply
     */
    @Override
    public String get(final String key) {
        checkIsInMultiOrPipeline();// 检查是否在事物中;检查是否是哟好难过管道技术
        client.sendCommand(Protocol.Command.GET, key);// 使用Socket进行IO操作,运行命令
        return client.getBulkReply();
    }jedis除了继承的BinaryJedis完毕主要的IO操作。还实现了 JedisCommands, MultiKeyCommands, AdvancedJedisCommands,ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands 
这几个可使用的命令的接口。
你能够參考redis自带的 unitTest,更深入的理解。
http://download.csdn.net/detail/lemon89/9407039
关于soTimeout 与 connectionTimeOut
我不多说了,这个链接解释非常清楚。
http://stackoverflow.com/questions/7360520/connectiontimeout-versus-sockettimeout
Jedis 源代码阅读一 —— Jedis的更多相关文章
- Jedis源代码探索
		[连接池实现] [一致性hash实现] [Redis客户端-Jedis源代码探索][http://blog.sina.com.cn/s/blog_6bc4401501018bgh.html] ... 
- Mongodb源代码阅读笔记:Journal机制
		Mongodb源代码阅读笔记:Journal机制 Mongodb源代码阅读笔记:Journal机制 涉及的文件 一些说明 PREPLOGBUFFER WRITETOJOURNAL WRITETODAT ... 
- 【转】Tomcat总体结构(Tomcat源代码阅读系列之二)
		本文是Tomcat源代码阅读系列的第二篇文章,我们在本系列的第一篇文章:在IntelliJ IDEA 和 Eclipse运行tomcat 7源代码一文中介绍了如何在intelliJ IDEA 和 Ec ... 
- 利用doxygen提高源代码阅读效率
		阅读开源项目的源代码是提高自己编程能力的好方法,而有一个好的源代码阅读工具无疑能够让你在阅读源代码时事半功倍.之前找过不少源代码阅读工具,像SourceInsight.sourcenav.scitoo ... 
- CI框架源代码阅读笔记5 基准測试 BenchMark.php
		上一篇博客(CI框架源代码阅读笔记4 引导文件CodeIgniter.php)中.我们已经看到:CI中核心流程的核心功能都是由不同的组件来完毕的.这些组件类似于一个一个单独的模块,不同的模块完毕不同的 ... 
- 淘宝数据库OceanBase SQL编译器部分 源代码阅读--Schema模式
		淘宝数据库OceanBase SQL编译器部分 源代码阅读--Schema模式 什么是Database,什么是Schema,什么是Table,什么是列,什么是行,什么是User?我们能够能够把Data ... 
- CI框架源代码阅读笔记3 全局函数Common.php
		从本篇開始.将深入CI框架的内部.一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说.全局函数具有最高的载入优先权.因此大多数的框架中BootStrap ... 
- [C++ 2011 STL (VS2012 Update4) 源代码阅读系列(2)]熟悉一些宏定义和模版偏特化或叫模版专门化
		[C++ 2011 STL (VS2012 Update4) 源代码阅读系列(2)]熟悉一些宏定义和模版偏特化或叫模版专门化 // point_test.cpp : 知识点练习和测试,用于单步调试,跟 ... 
- 【转】Tomcat源代码阅读系列
		在IntelliJ IDEA 和 Eclipse运行tomcat 7源代码(Tomcat源代码阅读系列之一) Tomcat总体结构(Tomcat源代码阅读系列之二) Tomcat启动过程(Tomcat ... 
随机推荐
- Filebeat-1.3.1安装和设置(图文详解)(多节点的ELK集群安装在一个节点就好)(以Console Output为例)
			前期博客 Filebeat的下载(图文讲解) 前提 Elasticsearch-2.4.3的下载(图文详解) Elasticsearch-2.4.3的单节点安装(多种方式图文详解) Elasticse ... 
- JSP中使用EL表达式
			EL表达式 :EL 全名为Expression Language,就是为了替代<%= %>脚本表达式. EL主要作用: 获取数据: EL表达式主要用于替换JSP页面中的脚本表达式,以从各种 ... 
- JVM 基础知识(GC)
			几年前写过一篇关于JVM调优的文章,前段时间拿出来看了看,又添加了一些东西.突然发现,基础真的很重要.学习的过程是一个由表及里,再由里及表的过程,所谓的"温故而知新".而真正能走完 ... 
- Android 使用AIDL实现进程间的通信
			在Android中,如果我们需要在不同进程间实现通信,就需要用到AIDL技术去完成. AIDL(android Interface Definition Language)是一种接口定义语言,编译器通 ... 
- vim学习3
			可视模式: 
- PatentTips - Method to manage memory in a platform with virtual machines
			BACKGROUND INFORMATION Various mechanisms exist for managing memory in a virtual machine environment ... 
- [NPM] Update published npm packages using np
			When we want to update our package we need to do a few things: pull latest from our git remote, bump ... 
- [Node.js] Serve Static Files with Express
			In this lesson we will find out how to serve static assets (images, css, stylesheets, etc.) with Exp ... 
- RocketMQ(九):消息发送(续)
			匠心零度 转载请注明原创出处,谢谢! RocketMQ网络部署图 NameServer:在系统中是做命名服务,更新和发现 broker服务. Broker-Master:broker 消息主机服务器. ... 
- Android代码模拟物理、屏幕点击事件
			一.应用中模拟物理和屏幕点击事件 例如,模拟对某个view的点击事件 private void simulateClick(View view, float x, float y) { long do ... 
