国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

「旁門右道」CURL持久連接技巧

dongfangyiyu / 3363人閱讀

摘要:支持多路復用支持對和已建立連接的復用,如果舊連接已失效則主動關閉舊連接,如果連接有效則嘗試使用已有連接傳輸數據。

背景

對于同一服務可能存在多次調用的情況,然而每次調用都需要建立一次tcp連接導致大量重復工作的同時還增加了連接超時或連接錯誤的概率,為了減少tcp連接次數最大限度的提高連接利用率,需要能夠重復利用每個tcp連接。

原理

HTTP1.1與HTTP2.0支持對于一次TCP連接建立的通道重復使用。

HTTP2.0支持多路復用

CURL支持對HTTP1.1和HTTP2.0已建立連接的復用,如果舊連接已失效則主動關閉舊連接,如果連接有效則嘗試使用已有連接傳輸數據。關鍵代碼如下:

// php/ext/url/interface.c
/* {{{ proto bool curl_exec(resource ch)
   Perform a cURL session */
PHP_FUNCTION(curl_exec)
{
    CURLcode    error;
    zval        *zid;
    php_curl    *ch;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zid) == FAILURE) {
        return;
    }

    ZEND_FETCH_RESOURCE(ch, php_curl *, &zid, -1, le_curl_name, le_curl);

    _php_curl_verify_handlers(ch, 1 TSRMLS_CC);

    _php_curl_cleanup_handle(ch);

   // 調用CURL方法
    error = curl_easy_perform(ch->cp);
    SAVE_CURL_ERROR(ch, error);
    /* CURLE_PARTIAL_FILE is returned by HEAD requests */
    if (error != CURLE_OK && error != CURLE_PARTIAL_FILE) {
        if (ch->handlers->write->buf.len > 0) {
            smart_str_free(&ch->handlers->write->buf);
        }
        RETURN_FALSE;
    }

    if (ch->handlers->std_err) {
        php_stream  *stream;
        stream = (php_stream*)zend_fetch_resource(&ch->handlers->std_err TSRMLS_CC, -1, NULL, NULL, 2, php_file_le_stream(), php_file_le_pstream());
        if (stream) {
            php_stream_flush(stream);
        }
    }

    if (ch->handlers->write->method == PHP_CURL_RETURN && ch->handlers->write->buf.len > 0) {
        smart_str_0(&ch->handlers->write->buf);
        RETURN_STRINGL(ch->handlers->write->buf.c, ch->handlers->write->buf.len, 1);
    }

    /* flush the file handle, so any remaining data is synched to disk */
    if (ch->handlers->write->method == PHP_CURL_FILE && ch->handlers->write->fp) {
        fflush(ch->handlers->write->fp);
    }
    if (ch->handlers->write_header->method == PHP_CURL_FILE && ch->handlers->write_header->fp) {
        fflush(ch->handlers->write_header->fp);
    }

    if (ch->handlers->write->method == PHP_CURL_RETURN) {
        RETURN_EMPTY_STRING();
    } else {
        RETURN_TRUE;
    }
}
/* }}} */


// curl/lib/url.c line 4328

  // 主動關閉已失效的連接
  prune_dead_connections(data);

  /*************************************************************
   * Check the current list of connections to see if we can
   * re-use an already existing one or if we have to create a
   * new one.
   *************************************************************/

  /* reuse_fresh is TRUE if we are told to use a new connection by force, but
     we only acknowledge this option if this is not a re-used connection
     already (which happens due to follow-location or during a HTTP
     authentication phase). */
  if(data->set.reuse_fresh && !data->state.this_is_a_follow)
    reuse = FALSE;
  else
    // 從已存在的鏈接中查找出可以復用的連接(如果是不支持多路復用且正在使用中的連接會被忽略)
    reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);

  /* If we found a reusable connection, we may still want to
     open a new connection if we are pipelining. */
  if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
    size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size;
    if(pipelen > 0) {
      infof(data, "Found connection %ld, with requests in the pipe (%zu)
",
            conn_temp->connection_id, pipelen);

      if(conn_temp->bundle->num_connections < max_host_connections &&
         data->state.conn_cache->num_connections < max_total_connections) {
        /* We want a new connection anyway */
        reuse = FALSE;

        infof(data, "We can reuse, but we want a new connection anyway
");
      }
    }
  }

  if(reuse) {
    /*
     * We already have a connection for this, we got the former connection
     * in the conn_temp variable and thus we need to cleanup the one we
     * just allocated before we can move along and use the previously
     * existing one.
     */
    conn_temp->inuse = TRUE; /* mark this as being in use so that no other
                                handle in a multi stack may nick it */
    reuse_conn(conn, conn_temp);
    free(conn);          /* we don"t need this anymore */
    conn = conn_temp;
    *in_connect = conn;

    infof(data, "Re-using existing connection! (#%ld) with %s %s
",
          conn->connection_id,
          conn->bits.proxy?"proxy":"host",
          conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
          conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
                                       conn->host.dispname);
  }
  else {
    /* We have decided that we want a new connection. However, we may not
       be able to do that if we have reached the limit of how many
       connections we are allowed to open. */
    struct connectbundle *bundle = NULL;

    if(conn->handler->flags & PROTOPT_ALPN_NPN) {
      /* The protocol wants it, so set the bits if enabled in the easy handle
         (default) */
      if(data->set.ssl_enable_alpn)
        conn->bits.tls_enable_alpn = TRUE;
      if(data->set.ssl_enable_npn)
        conn->bits.tls_enable_npn = TRUE;
    }

    if(waitpipe)
      /* There is a connection that *might* become usable for pipelining
         "soon", and we wait for that */
      connections_available = FALSE;
    else
      bundle = Curl_conncache_find_bundle(conn, data->state.conn_cache);

    if(max_host_connections > 0 && bundle &&
       (bundle->num_connections >= max_host_connections)) {
      struct connectdata *conn_candidate;

      /* The bundle is full. Let"s see if we can kill a connection. */
      conn_candidate = find_oldest_idle_connection_in_bundle(data, bundle);

      if(conn_candidate) {
        /* Set the connection"s owner correctly, then kill it */
        conn_candidate->data = data;
        (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
      }
      else {
        infof(data, "No more connections allowed to host: %d
",
              max_host_connections);
        connections_available = FALSE;
      }
    }

    if(connections_available &&
       (max_total_connections > 0) &&
       (data->state.conn_cache->num_connections >= max_total_connections)) {
      struct connectdata *conn_candidate;

      /* The cache is full. Let"s see if we can kill a connection. */
      conn_candidate = Curl_conncache_oldest_idle(data);

      if(conn_candidate) {
        /* Set the connection"s owner correctly, then kill it */
        conn_candidate->data = data;
        (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
      }
      else {
        infof(data, "No connections available in cache
");
        connections_available = FALSE;
      }
    }

    if(!connections_available) {
      infof(data, "No connections available.
");

      conn_free(conn);
      *in_connect = NULL;

      result = CURLE_NO_CONNECTION_AVAILABLE;
      goto out;
    }
    else {
      /*
       * This is a brand new connection, so let"s store it in the connection
       * cache of ours!
       */
      Curl_conncache_add_conn(data->state.conn_cache, conn);
    }

#if defined(USE_NTLM)
    /* If NTLM is requested in a part of this connection, make sure we don"t
       assume the state is fine as this is a fresh connection and NTLM is
       connection based. */
    if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
       data->state.authhost.done) {
      infof(data, "NTLM picked AND auth done set, clear picked!
");
      data->state.authhost.picked = CURLAUTH_NONE;
      data->state.authhost.done = FALSE;
    }

    if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
       data->state.authproxy.done) {
      infof(data, "NTLM-proxy picked AND auth done set, clear picked!
");
      data->state.authproxy.picked = CURLAUTH_NONE;
      data->state.authproxy.done = FALSE;
    }
#endif
  }

// curl/lib/multi.c
/*
 * This function scans the connection cache for half-open/dead connections,
 * closes and removes them.
 * The cleanup is done at most once per second.
 */
static void prune_dead_connections(struct Curl_easy *data)
{
  struct curltime now = Curl_now();
  time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup);

  if(elapsed >= 1000L) {
    Curl_conncache_foreach(data, data->state.conn_cache, data,
                           call_disconnect_if_dead);
    data->state.conn_cache->last_cleanup = now;
  }
}
PHP實現
class Curl
{
    protected $ch = null;
    protected $errorCode = 0;
    protected $errorMsg = "";
    protected $curlInfo = array();
    protected $verbose = null;
    private static $instance = null;

    public function getLastErrorCode()
    {
        return $this->errorCode;
    }

    public function getLastErrorMsg()
    {
        return $this->errorMsg;
    }

    public function getLastCurlInfo()
    {
        return $this->curlInfo;
    }

    private function __construct()
    {
        $this->ch = curl_init();
    }

    /*
     * 單例模式防止被clone
     */
    private function __clone(){
        throw new CurlException("The Curl library can"t be cloned");
    }

    /*
     * 使用單例模式調用
     */
    public static function getInstance(){
        if(!self::$instance instanceof self){
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * curl以get的方式訪問
     * @param $url
     * @param int $timeout
     * @param array $params get請求的參數,可以在url中直接帶參數,也可以在這里傳
     * @param array $headers 支持["Accept" => "application/json"]和["Accept: application/json"]兩種方式
     * @return mixed
     */
    public function get($url, $timeout = 3, $params = [], $headers = [])
    {
        $url = $this->buildQuery($url,$params);
        $this->setGeneralOption($url,$timeout,$headers);
        $result = $this->execute();
        return $result;
    }

    /**
     * curl以post的方式訪問
     * @param $url
     * @param array $params
     * @param array $headers 支持["Accept" => "application/json"]和["Accept: application/json"]兩種方式
     * @param bool $withHttpBuildQuery
     * @param int $timeout
     * @return mixed
     */
    public function post($url, $params = [], $headers = [], $withHttpBuildQuery = true, $timeout=3)
    {
        if ($withHttpBuildQuery) {
            if (!is_array($params)) {
                $params = [$params];
            }
            $params = http_build_query($params);
        }
        
        curl_setopt($this->ch, CURLOPT_POST, 1);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
        $this->setGeneralOption($url,$timeout,$headers);
        $result = $this->execute();
        return $result;
    }

    /**
     * curl以HTTP2.0 get的方式訪問
     * @param string $url 請求URL
     * @param int $timeout 超時時間,單位秒
     * @param array $params get請求的參數,可以在url中直接帶參數,也可以在這里傳
     * @param array $headers 支持["Accept" => "application/json"]和["Accept: application/json"]兩種方式
     * @return mixed
     */
    public function get2($url, $timeout = 3, $params = [], $headers = [])
    {
        $url = $this->buildQuery($url,$params);
        $this->setGeneralOption($url,$timeout,$headers,CURL_HTTP_VERSION_2_0);
        $result = $this->execute();
        return $result;
    }

    /**
     * curl以HTTP2.0 post的方式訪問
     * @param string $url 請求URL
     * @param array $params
     * @param array $headers 支持["Accept" => "application/json"]和["Accept: application/json"]兩種方式
     * @param bool $withHttpBuildQuery
     * @param int $timeout 超時時間,單位秒
     * @return mixed
     */
    public function post2($url, $params = [], $headers = [], $withHttpBuildQuery = true, $timeout=3)
    {
        if ($withHttpBuildQuery) {
            if (!is_array($params)) {
                $params = [$params];
            }
            $params = http_build_query($params);
        }

        curl_setopt($this->ch, CURLOPT_POST, 1);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params);
        $this->setGeneralOption($url,$timeout,$headers,CURL_HTTP_VERSION_2_0);
        $result = $this->execute();
        return $result;
    }

    /**
     * 實例銷毀前主動關閉所有連接
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * 關閉所有連接
     * Description: 這一步在php-fpm中可以省略,實例結束后php-fpm的垃圾回收機制會關閉
     */
    public function close()
    {
        if (is_resource($this->ch)) {
            curl_close($this->ch);
            $this->ch = null;
        }
    }

    /**
     * 拼接請求URL
     * @param string $url 請求URL
     * @param array $params 待拼接參數
     * @return string
     */
    protected function buildQuery($url,$params)
    {
        if (!$params) {
            return $url;
        }

        if (strpos($url, "?") === false) {
            $url .= "?";
        } else {
            $url .= "&";
        }

        $url .= http_build_query($params);
        return $url;
    }

    /**
     * 設置通用curl配置
     * @param string $url 請求URL
     * @param int $timeout 超時時間,單位秒
     * @param array $headers 請求header
     * @param int $httpVersion 使用的http協議,默認為1.1
     */
    protected function setGeneralOption($url,$timeout,$headers=array(),$httpVersion=CURL_HTTP_VERSION_1_1)
    {
        curl_setopt($this->ch, CURLOPT_URL, $url);
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, true); //讓CURL支持HTTPS訪問
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($this->ch, CURLOPT_HTTP_VERSION, $httpVersion);
        // 啟用debug獲取更詳細的連接信息,與CURLOPT_HEADER互斥
        curl_setopt($this->ch, CURLOPT_VERBOSE, 1);
        $this->verbose = fopen("php://temp", "w+");
        curl_setopt($this->ch, CURLOPT_STDERR, $this->verbose);

        if ($headers && is_array($headers)) {
            $realHeader = [];
            foreach ($headers as $key => $val) {
                if (is_string($key)) {
                    $realHeader[] = $key. ": ". $val;
                } else {
                    $realHeader[] = $val;
                }
            }
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $realHeader);
        }
    }

    /**
     * 執行請求
     * @return mixed
     */
    protected function execute()
    {
        $result = curl_exec($this->ch);

        // 記錄詳細的debug信息
        $this->curlInfo = curl_getinfo($this->ch);
        rewind($this->verbose);
        $this->curlInfo["verbose"] = stream_get_contents($this->verbose);
        $this->verbose = null;

        if ($result === false) {
            $this->errorCode = curl_errno($this->ch);
            $this->errorMsg = curl_error($this->ch);
            $this->curlInfo["error_code"] = $this->errorCode;
            $this->curlInfo["error_message"] = $this->errorMsg;
        }

        curl_reset($this->ch);
        return $result;
    }
}

class CurlException extends Exception {}
拓展

由于PHP-FPM的回收機制,一次請求結束后CURL的資源將會被回收,這意味著這次請求建立的TCP連接將會被關閉,在這種情況下就無法達到垮請求復用的目的。因此可以利用獨立進程的方式來維護已建立的TCP連接專門負責CURL的請求。

對于HTTP2.0而言,由于支持多路復用,因此對于一個域名的請求建立一次tcp連接后可以支持同時多個請求的處理(HTTP1.1一個tcp連接同時只支持一個請求,如果第二個請求同時到達則CURL將建立新的tcp連接以便完成請求),利用這一特性使用獨立進程配合協程可以達到對于單一場景的curl高并發的支撐。

同理除PHP外可擴展到其他語言。

源地址?By佐柱

轉載請注明出處,也歡迎偶爾逛逛我的小站,謝謝 :)

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/26307.html

相關文章

  • 有必要參加SEO培訓嗎?自學可以嗎?

    摘要:所以,我強烈建議新人要舍得投資自己的大腦,至少要參加一個系統的培訓班,系統地學習,避免自學浪費寶貴的時間,沒有建站技術能學好嗎答這個問題要看情況,曾慶平在前面也講了,不會建站技術的很大程度上是屬于第一層次的。 SEO人員在職場上總會碰上一些難解的問題,很多人也不懂得自己學習SEO該往...

    不知名網友 評論0 收藏0
  • Lumen 初體驗(二)

    摘要:的現狀目前是版本,是基于開發。入口文件啟動文件和配置文件框架的入口文件是。在路由中指定控制器類必須寫全命名空間,不然會提示找不到類。目前支持四種數據庫系統以及。使用時發生錯誤,因為在文件中,的默認驅動是。 最近使用 Lumen 做了 2 個業余項目,特此記錄和分享一下。 Lumen 的介紹 在使用一項新的技術時,了解其應用場景是首要的事情。 Lumen 的口號:為速度而生的 La...

    Cheriselalala 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<