背景介绍

看最近EdgeOne活动力度很大,忍不住买了一年,准备把博客从CDN换成EdgeOne。

换完后才意识到原博客的CDN缓存刷新插件不支持EdgeOne,毕竟才刚出来没多久,只好自己写一个。

因为我的博客系统是Typecho,它和目前最多人用的博客系统Wordpress用的都是PHP,所以我这次用的是PHP编写。

前置条件

首先当然是要有一个支持边缘函数得EdgeOne套餐,目前来说最低的个人版即可满足要求。

目前新用户有优惠,一年仅需36元。

链接如下:https://cloud.tencent.com/act/pro/edgeone_1year?from=21109

EdgeOne优惠

如果你像我一样是从CDN转过来的话,那么个人版完全够用了,相较于CDN,它多了DDos和CC防护,而且规则配置也比CDN更加灵活。

而且不同于CDN,未备案域名也可接入EdgeOne。

更多的套餐对比可以参考文档:https://cloud.tencent.com/document/product/1552/94165

功能

  • 按URL清除缓存
  • 按目录清除缓存
  • 按Hostname清除缓存
  • 清除整个站点的所有缓存
  • 按Cache-Tag清除缓存
  • 不依赖腾讯云的SDK,单文件可用,更方便部署

代码

<?php

function qcloud_v3_post($SecretId,$SecretKey,$Service,$bodyArray,$headersArray){
    $HTTPRequestMethod = "POST";
    $CanonicalURI = "/";
    $CanonicalQueryString = "";
    // 按 ASCII 升序进行排序
    ksort($headersArray);
    $sortHeadersArray = $headersArray;

    $SignedHeaders = "";
    $CanonicalHeaders = "";

    // 拼接键
    foreach ($sortHeadersArray as $key => $value) {
        $SignedHeaders .= strtolower($key) . ';';
    }
    $SignedHeaders = rtrim($SignedHeaders, ';');

    // 拼接键和值
    foreach ($sortHeadersArray as $key => $value) {
        $CanonicalHeaders .= strtolower($key) . ':' . strtolower($value) . "\n";
    }

    $HashedRequestPayload = hash("SHA256", json_encode($bodyArray));

    $CanonicalRequest =
      $HTTPRequestMethod . "\n" .
      $CanonicalURI . "\n" .
      $CanonicalQueryString . "\n" .
      $CanonicalHeaders . "\n" .
      $SignedHeaders . "\n" .
      $HashedRequestPayload;

    // ------

    // 时间戳
    $RequestTimestamp = time();
    // 获取年月日
    $formattedDate = gmdate("Y-m-d", $RequestTimestamp);
    $Algorithm = "TC3-HMAC-SHA256";
    $CredentialScope = $formattedDate . "/" . $Service . "/tc3_request";
    $HashedCanonicalRequest = hash("SHA256", $CanonicalRequest);
    // echo($RequestTimestamp);
    // ------

    $StringToSign =
      $Algorithm . "\n" .
      $RequestTimestamp . "\n" .
      $CredentialScope . "\n" .
      $HashedCanonicalRequest;

    $SecretDate = hash_hmac("SHA256", $formattedDate, "TC3" . $SecretKey, true);
    $SecretService = hash_hmac("SHA256", $Service, $SecretDate, true);
    $SecretSigning = hash_hmac("SHA256", "tc3_request", $SecretService, true);

    $Signature = hash_hmac("SHA256", $StringToSign, $SecretSigning);

    $Authorization =
      $Algorithm . ' ' .
      'Credential=' . $SecretId . '/' . $CredentialScope . ', ' .
      'SignedHeaders=' . $SignedHeaders . ', ' .
      'Signature=' . $Signature;

    $headersArray["X-TC-Timestamp"] = $RequestTimestamp;
    $headersArray["Authorization"] = $Authorization;

    return $headersArray;
}

function sendRequestJSON($url, $method = 'GET', $postData = null, $headers = null, $timeout = 10) {
    $ch = curl_init();

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);

        if (is_array($postData)) {
            $postData = json_encode($postData);
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }

    if (!empty($headers)) {
        $formattedHeaders = [];
        foreach ($headers as $key => $value) {
            $formattedHeaders[] = $key . ': ' . $value;
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $formattedHeaders);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

    $response = curl_exec($ch);

    if ($response === false) {
        echo 'Curl error: ' . curl_error($ch);
    }

    curl_close($ch);

    return $response;
}

// URL和cache_tag刷新
function purge_url_cachetag_cache($SecretId,$SecretKey,$ZoneId,$Targets,$Type){
    $Service = "teo";
    // api域名
    $host = "teo.tencentcloudapi.com";
    $protocol = "https://";
    $apiurl = $protocol . $host;

    $payload = array(
        "ZoneId" => $ZoneId,
        "Type" => $Type,
        "Targets" => $Targets
    );
    $headersPending = array(
        'Host'=> $host,
        'Content-Type'=> 'application/json',
        'X-TC-Action'=> 'CreatePurgeTask',
        'X-TC-Version'=> '2022-09-01',
        'X-TC-Region'=> 'ap-guangzhou',
    );

    $headersSend = qcloud_v3_post($SecretId,$SecretKey,$Service,$payload,$headersPending);
    return sendRequestJSON($apiurl,"POST",$payload,$headersSend);
}
// URL刷新
function purge_url_cache($SecretId,$SecretKey,$ZoneId,$Targets){
    return purge_prefix_hostname_all_cache($SecretId,$SecretKey,$ZoneId,$Targets,"purge_url");
}
// cache tag刷新
// 仅企业版适用
function purge_cache_tag_cache($SecretId,$SecretKey,$ZoneId,$Targets){
    return purge_prefix_hostname_all_cache($SecretId,$SecretKey,$ZoneId,$Targets,"purge_url_cache");
}

// 目录刷新、Hostname刷新、刷新全部缓存通用模板,用于重载
// $Method为节点缓存清除方法,针对目录刷新、Hostname刷新以及刷新全部缓存 类型有效,取值有:
// invalidate:仅刷新目录下产生了更新的资源;
// delete:无论目录下资源是否更新都刷新节点资源。
function purge_prefix_hostname_all_cache($SecretId,$SecretKey,$ZoneId,$Targets,$Type,$Method="invalidate"){
    $Service = "teo";
    // api域名
    $host = "teo.tencentcloudapi.com";
    $protocol = "https://";
    $apiurl = $protocol . $host;

    $payload = array(
        "ZoneId" => $ZoneId,
        "Type" => $Type,
        "Targets" => $Targets
    );
    $headersPending = array(
        'Host'=> $host,
        'Content-Type'=> 'application/json',
        'X-TC-Action'=> 'CreatePurgeTask',
        'X-TC-Version'=> '2022-09-01',
        'X-TC-Region'=> 'ap-guangzhou',
    );

    $headersSend = qcloud_v3_post($SecretId,$SecretKey,$Service,$payload,$headersPending);
    return sendRequestJSON($apiurl,"POST",$payload,$headersSend);
}
// 目录刷新
function purge_prefix_cache($SecretId,$SecretKey,$ZoneId,$Targets,$Method="invalidate"){
    return purge_prefix_hostname_all_cache($SecretId,$SecretKey,$ZoneId,$Targets,"purge_prefix",$Method);
}
// hostname刷新
function purge_host_cache($SecretId,$SecretKey,$ZoneId,$Targets,$Method="invalidate"){
    return purge_prefix_hostname_all_cache($SecretId,$SecretKey,$ZoneId,$Targets,"purge_host",$Method);
}
// 站点下全部缓存
function purge_all_cache($SecretId,$SecretKey,$ZoneId,$Targets,$Method="invalidate"){
    return purge_prefix_hostname_all_cache($SecretId,$SecretKey,$ZoneId,[],"purge_all",$Method);
}


// 下面是测试代码
$SecretId = "";
$SecretKey = "";



echo(purge_url_cache($SecretId,$SecretKey,"zone-2ken5y3j5658",["http://cache.9kr.cc/123.txt"]));
echo("<br>");
echo(purge_prefix_cache($SecretId,$SecretKey,"zone-2ken5y3j5658",["http://cache.9kr.cc/book/"]));
echo("<br>");
echo(purge_host_cache($SecretId,$SecretKey,"zone-2ken5y3j5658",["cache.9kr.cc"]));
echo("<br>");
echo(purge_all_cache($SecretId,$SecretKey,"zone-2ken5y3j5658",[]));
echo("<br>");
echo(purge_cache_tag_cache($SecretId,$SecretKey,"zone-2ken5y3j5658",["tag1"]));
echo("<br>");

测试效果展示

PHP测试运行结果

PHP测试运行结果

需要注意的是Cache Tag要企业版才支持,所以没法测,文档可以点击这里查看

缓存清除文档

EO后台缓存刷新记录

EO后台缓存刷新记录

最后修改:2023 年 09 月 27 日
如果觉得我的文章对你有用,请随意赞赏