阿里云CDN刷新链接接口实践

发布时间:2019-10-29 20:57:28 浏览量:1283 标签: 阿里云 cdn

今天更改了一个线上的css文件,由于项目部署了cdn,需要对缓存进行清理。有两种方式,一、清楚cdn缓存,二、更改页面引入文件地址,如加入版本号。第一种方式需要登录阿里云,然后进行缓存清理操作,比较麻烦,第二种方式如果是涉及的页面数量过多,在更改起来也是非常麻烦的。我们使用的阿里云的cdn产品,记得以往的产品都有api接口,想通过阿里云cdn接口模式对链接进行缓存清楚操作。

1572353826601076.jpg

下面是PHP实例:


一、安装SDK

使用composer进行安装,命令:

composer require alibabacloud/client


二、获取阿里云参数

1、accessKeyId

2、accessSecret

建议使用子秘钥

三、编写代码

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/29 0029
 * Time: 10:10
 */

namespace app\index\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\Controller;
use think\Request;

class Cdn extends Controller
{
    protected $accessKeyId;
    protected $accessSecret;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->accessKeyId  = '123456789';
        $this->accessSecret = '123456789';
    }

    public function index()
    {
        $url = 'http://www.demo.com/css/index.css';
        // Download:https://github.com/aliyun/openapi-sdk-php
        // Usage:https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessSecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Cdn')
                // ->scheme('https') // https | http
                ->version('2018-05-10')
                ->action('RefreshObjectCaches')
                ->method('POST')
                ->host('cdn.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId'   => "cn-hangzhou",
                        'ObjectPath' => $url,
                    ],
                ])
                ->request();
            $res    = $result->toArray();
            if(isset($res['RefreshTaskId'])) {
                echo '刷新成功';
            } else {
                echo '刷新失败';
            }
        }
        catch(ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
        catch(ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }

    }
}


建议在提交刷新后,2分钟后查看效果,注意要清除浏览器缓存哦!


评论
登录后才可以进行评论哦! QQ登录
验证码
评论内容