七牛CDN刷新,预取,获取流量,带宽功能参考实现

潘濬
• 阅读 3682

本文中的代码文件在:https://github.com/qiniudemo/qiniu-lab-java/tree/master/src/com/qiniulab/cdn
该参考实现基于七牛的java sdk,可以从 https//github.com/qiniu/java-sdk 下载。

代码如下:

package com.qiniulab.cdn;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.util.Auth;
import com.qiniu.util.Json;
import com.qiniu.util.StringMap;

/**
 * Fusion Cdn 提供的功能
 * 
 * <ol>
 * <li>刷新链接和目录</li>
 * <li>预取资源</li>
 * <li>获取流量数据</li>
 * <li>获取带宽数据</li>
 * </ol>
 */

public class FusionCdn {
    private Auth auth;

    public FusionCdn(String accessKey, String secretKey) {
        this.auth = Auth.create(accessKey, secretKey);
    }

    /**
     * 刷新目录或者链接列表,注意目录必须以 / 结尾
     * 
     * @param urls
     *            待刷新的链接列表
     * @param dirs
     *            待刷新的目录列表
     * @throws QiniuException
     */

    public CdnRefreshResult refresh(String[] urls, String[] dirs) throws QiniuException {
        CdnRefreshResult refreshResult = null;

        String refreshAPI = "http://fusion.qiniuapi.com/refresh";
        Client client = new Client();
        StringMap map = new StringMap();
        map.put("urls", urls);
        map.put("dirs", dirs);
        String postBody = Json.encode(map);
        String accessToken = String.format("QBox %s", this.auth.signRequest(refreshAPI, null, null));
        StringMap headers = new StringMap();
        headers.put("Authorization", accessToken);
        try {
            Response resp = client.post(refreshAPI, postBody.getBytes("UTF-8"), headers, Client.JsonMime);
            refreshResult = resp.jsonToObject(CdnRefreshResult.class);
        } catch (UnsupportedEncodingException e) {
        }

        return refreshResult;
    }

    /**
     * 根据资源访问外链进行预取操作,不支持预取目录
     * 
     * @param urls
     *            待预取的链接列表
     * @throws QiniuException
     */

    public CdnPrefetchResult prefetch(String[] urls) throws QiniuException {
        CdnPrefetchResult prefetchResult = null;

        String refreshAPI = "http://fusion.qiniuapi.com/prefetch";
        Client client = new Client();
        StringMap map = new StringMap();
        map.put("urls", urls);
        String postBody = Json.encode(map);
        String accessToken = String.format("QBox %s", this.auth.signRequest(refreshAPI, null, null));
        StringMap headers = new StringMap();
        headers.put("Authorization", accessToken);
        try {
            Response resp = client.post(refreshAPI, postBody.getBytes("UTF-8"), headers, Client.JsonMime);
            prefetchResult = resp.jsonToObject(CdnPrefetchResult.class);
        } catch (UnsupportedEncodingException e) {
        }

        return prefetchResult;
    }

    /**
     * @param domain
     *            需要获取带宽的域名
     * @param startTime
     *            起始时间
     * @param endTime
     *            结束时间
     */
    public DomainBandwidthResult getDomainBandwidth(String domain, String startTime, String endTime)
            throws QiniuException {
        DomainBandwidthResult bandwidthResult;
        String reqUrl = null;
        try {
            reqUrl = String.format("http://fusion.qiniuapi.com/domain/bandwidth?domain=%s&startTime=%s&endTime=%s",
                    URLEncoder.encode(domain, "utf-8"), URLEncoder.encode(startTime, "utf-8"),
                    URLEncoder.encode(endTime, "utf-8"));
        } catch (UnsupportedEncodingException e1) {
        }

        Client client = new Client();
        StringMap map = new StringMap();
        map.put("Content-Type", Client.FormMime);
        String accessToken = String.format("QBox %s", this.auth.signRequest(reqUrl, null, null));
        StringMap headers = new StringMap();
        headers.put("Authorization", accessToken);
        Response resp = client.get(reqUrl, headers);
        bandwidthResult = resp.jsonToObject(DomainBandwidthResult.class);
        return bandwidthResult;
    }

    /**
     * @param domain
     *            需要获取流量的域名
     * @param startTime
     *            起始时间
     * @param endTime
     *            结束时间
     */
    public DomainFlowResult getDomainFlow(String domain, String startTime, String endTime) throws QiniuException {
        DomainFlowResult flowResult;
        String reqUrl = null;
        try {
            reqUrl = String.format("http://fusion.qiniuapi.com/domain/traffic?domain=%s&startTime=%s&endTime=%s",
                    URLEncoder.encode(domain, "utf-8"), URLEncoder.encode(startTime, "utf-8"),
                    URLEncoder.encode(endTime, "utf-8"));
        } catch (UnsupportedEncodingException e1) {
        }

        Client client = new Client();
        StringMap map = new StringMap();
        map.put("Content-Type", Client.FormMime);
        String accessToken = String.format("QBox %s", this.auth.signRequest(reqUrl, null, null));
        StringMap headers = new StringMap();
        headers.put("Authorization", accessToken);
        Response resp = client.get(reqUrl, headers);
        flowResult = resp.jsonToObject(DomainFlowResult.class);
        return flowResult;
    }
}

实例调用:

刷新目录或链接

// ak,sk从 https://portal.qiniu.com/user/key 获取
String ak = "";
String sk = "";
FusionCdn cdn = new FusionCdn(ak, sk);

// 刷新例子
String[] urlsToRefresh = new String[] { "http://if-pbl.qiniudn.com/golang.png",
        "http://if-pbl.qiniudn.com/test/golang.png" };
CdnRefreshResult refreshResult;
try {
    refreshResult = cdn.refresh(urlsToRefresh, null);
    System.out.println(refreshResult.getCode() + "," + refreshResult.getError());
} catch (QiniuException e) {
    if (e.response != null) {
        System.err.println(e.response.toString());
    }
}

资源链接预取

//ak,sk从 https://portal.qiniu.com/user/key 获取
String ak = "";
String sk = "";
FusionCdn cdn = new FusionCdn(ak, sk);

// 预取例子
String[] urlsToPrefetch = new String[] { "http://if-pbl.qiniudn.com/golang.png",
        "http://if-pbl.qiniudn.com/test/golang.png" };
CdnPrefetchResult prefetchResult;
try {
    prefetchResult = cdn.prefetch(urlsToPrefetch);
    System.out.println(prefetchResult.getCode() + "," + prefetchResult.getError());
} catch (QiniuException e) {
    if (e.response != null) {
        System.err.println(e.response.toString());
    }
}

获取域名带宽数据

// ak,sk从 https://portal.qiniu.com/user/key 获取
String ak = "";
String sk = "";

String domain = "sc.example.com";
String startTime = "2016-06-30 18:00:00";
String endTime = "2016-06-30 20:00:00";
FusionCdn cdn = new FusionCdn(ak, sk);

try {
    DomainBandwidthResult bandwidthResult = cdn.getDomainBandwidth(domain, startTime, endTime);
    System.out.println(bandwidthResult.getCode());
} catch (QiniuException e) {
    if (e.response != null) {
        System.err.println(e.response.toString());
    }
}    

获取域名流量数据

// ak,sk从 https://portal.qiniu.com/user/key 获取
String ak = "";
String sk = "";

String domain = "sc.example.com";
String startTime = "2016-06-30 18:00:00";
String endTime = "2016-06-30 20:00:00";
FusionCdn cdn = new FusionCdn(ak, sk);

try {
    DomainFlowResult flowResult = cdn.getDomainFlow(domain, startTime, endTime);
    System.out.println(flowResult.getCode());
} catch (QiniuException e) {
    if (e.response != null) {
        System.err.println(e.response.toString());
    }
}    
点赞
收藏
评论区
推荐文章
可莉 可莉
3年前
18个常用 webpack插件,总会有适合你的!
!(https://oscimg.oschina.net/oscnet/71317da0c57a8e8cf5011c00e302a914609.jpg)来源| https://github.com/Michaellzg/myarticle/blob/master/webpack/Plugin何为插
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
Java 调用阿里云小蜜示例代码
!(https://oscimg.oschina.net/oscnet/4cd94e5134efc7375fa40d9372e90603359.jpg)相关代码链接:https://gitee.com/xshuai/ai/tree/master/AIDemo/src/main/java/com/xs/aliet/(https:
Stella981 Stella981
3年前
Spring Boot 2.0实现基于Restful风格的文件上传与下载APIs
!(https://cdn.ramostear.com/20200428032f11940e374e46a68347e06347e980.png)\文件上传与下载在Web应用中是一个比较常见的功能。在本教程中,我将基于Spring2.2.6版本实现一个基于Restful风格的文件上传与下载APIs。基于SpringBoot2.0
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(