zoukankan      html  css  js  c++  java
  • okhttp——3. 连接池复用

    Connection

    首先看一下okhttp如何定义连接,Connection接口可略知一二

    public interface Connection {
      /** Returns the route used by this connection. */
      Route route();
    
      /**
       * Returns the socket that this connection is using. Returns an {@linkplain
       * javax.net.ssl.SSLSocket SSL socket} if this connection is HTTPS. If this is an HTTP/2
       * connection the socket may be shared by multiple concurrent calls.
       */
      Socket socket();
    
      /**
       * Returns the TLS handshake used to establish this connection, or null if the connection is not
       * HTTPS.
       */
      @Nullable Handshake handshake();
    
      /**
       * Returns the protocol negotiated by this connection, or {@link Protocol#HTTP_1_1} if no protocol
       * has been negotiated. This method returns {@link Protocol#HTTP_1_1} even if the remote peer is
       * using {@link Protocol#HTTP_1_0}.
       */
      Protocol protocol();
    }
    

    在okhttp中实现了Connection接口的类是RealConnection, 里面涉及到了如何建立一次连接。

    ConnectionPool

    该类用于管理所有网络请求的连接,对于满足特定条件的连接进行复用。

    1. 构造函数:
    // maxIdleConnections: 单个url最大的连接数 
    // keepAliveDuration: 单个连接的有效期  timeUnit: 有效期的时间单位
    
    public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
        this.maxIdleConnections = maxIdleConnections;
        this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration);
    
        // Put a floor on the keep alive duration, otherwise cleanup will spin loop.
        if (keepAliveDuration <= 0) {
          throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration);
        }
      }
    
      // okhttp 使用如下默认值
      public ConnectionPool() {
        this(5, 5, TimeUnit.MINUTES);
      }
    

    ConnectionPool 的构造只会在OkhttpClient的Builder里面创建一次,其它所有类持有的ConnectionPool都是通过参数传递过去的。

    重要成员:

    // 用于存放连接的双向队列
    private final Deque<RealConnection> connections = new ArrayDeque<>();
    

    获取可重用的连接

     /**
       * Returns a recycled connection to {@code address}, or null if no such connection exists. The
       * route is null if the address has not yet been routed.
       */
      @Nullable RealConnection get(Address address, StreamAllocation streamAllocation, Route route) {
        assert (Thread.holdsLock(this));
        for (RealConnection connection : connections) {
          if (connection.isEligible(address, route)) {
            streamAllocation.acquire(connection);
            return connection;
          }
        }
        return null;
      }
    
    梦想不是浮躁,而是沉淀和积累
  • 相关阅读:
    博客园安卓客户端合仔茶版本V4.0震撼发布
    提示功能的检索框
    .net 玩自动化浏览器
    《表单篇》DataBase之大数据量经验总结
    自定义表主键
    一次网络程序Debug过程
    关于.NET下开源及商业图像处理(PSD)组件
    利用反射从程序集dll中动态调用方法
    Linux内核源码分析方法
    wcf基础教程之 契约(合同)Contract
  • 原文地址:https://www.cnblogs.com/NeilZhang/p/12744156.html
Copyright © 2011-2022 走看看