使用Varnish4.1.8搭建HLS直播CDN

varnish4.1.8安装

varnish版本:varnish4.1.8

安装步骤:

  • 安装依赖包:

    yum install -y autoconf automake jemalloc-devel libedit-devel libtool ncurses devel pcre-devel pkgconfig python-docutils python-sphinx graphviz
    
  • /home/work/install里面,下载varnish源码包:wget http://varnish-cache.org/_downloads/varnish-4.1.8.tgz

  • cd /home/work/install/varnish-4.1.8

  • ./authgen.sh

  • ./configure --prefix=/home/work/varnish 默认安装位置指定为/home/work/varnish

  • make && sudo make install

  • ldconfig

启动脚本

  • 启动脚本,在/home/workl/varnish/bin下新建启动脚本start.sh:
#! /bin/bash
# rootpath指定启动脚本和配置文件的根目录
ROOTPATH=/home/work/varnish
${ROOTPATH}/sbin/varnishd -P ${ROOTPATH}/conf/varnish.pid -f ${ROOTPATH}/conf/default.vcl -a 0.0.0.0:8080 -T 0.0.0.0:8081 -t 120 -S ${ROOTPATH}/conf/secret -s malloc,1024MB -F

注意:-a参数指定了varnish监听的IP和端口。varnish4.1.8如果配置成 -a: 6081,启动时候,便会抛错:Address family not supported by protocol。varnish4需要配置成:-a 0.0.0.0:8080,表示接受来自任何IP(0.0.0.0)访问8080端口的请求。而varnish5.1版本,-a参数就可以直接配置成-a :8080。这一点,是varnish4和varnish5的一点小小不同。

配置文件。

该配置文件用于缓存HLS协议的TS视频文件,对于m3u8以及其他文件,不缓存。
新建/home/work/varnish/conf文件夹,其中default.vcl配置如下:

vcl 4.0;
# 指定后端源站
backend default {
    .host = "127.0.0.1";
    .port = "8446";
}
sub vcl_recv {
    if (req.url ~ "^/[^?]+\.(m3u8|ts|jpeg|jpg|png|gif|ico|js|css|txt|zip|html|htm)(\?.*|)$") {
        # 去除 Cookies (静态文件通常不需要处理 Cookies)
        unset req.http.cookie;
        unset req.http.cache-control;
        unset req.http.pragma;
      
    }
    # url提取,去掉query string,优化缓存空间
    set req.url = regsub(req.url, "\?.*$", "");
    # m3u8文件不保存
    if (req.url ~ ".*\.m3u8.*") {
        return(pass);
    }
    # 为发往后端主机的请求添加X-Forward-For首部
    if (req.http.X-Forward-For) {    
        set req.http.X-Forward-For = req.http.X-Forward-For + "," + client.ip;
    } else {
        set req.http.X-Forward-For = client.ip;
    }
    return(hash);
}
sub vcl_hash {
    # 只根据URL获取object的hashkey
    # 注意,不加这句话,源站分发的文件与浏览器获取这个文件,走的不是一个hash key
   hash_data(req.url);
   return(lookup);
}
sub vcl_hit {
    if (obj.ttl >= 0s) {
        return(deliver);
    }
    if (obj.ttl + obj.grace > 0s) {
        return(deliver);
    }
    return(pass);
}
sub vcl_backend_response {
    # 去除backend的set-cookie,防止ts文件不缓存
    if (bereq.url ~ "^/[^?]+\.(m3u8|ts|jpeg|jpg|png|gif|ico|js|css|txt|zip|html|htm)(\?.*|)$") {
        unset beresp.http.set-cookie;
    }
    # m3u8文件不保存,ts文件设置240s缓存时间
    if (bereq.url ~ ".*\.m3u8.*") {
    set beresp.ttl = 240s;
        set beresp.uncacheable = true;
    } else if (bereq.url ~ ".*\.ts.*") {
    set beresp.ttl = 240s;  
    }
}
sub vcl_deliver {
    # 设置response是否varnish命中、以及命中数
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }
    set resp.http.X-Cache-Hits = obj.hits;
    # 跨域的解决
    set resp.http.Access-Control-Allow-Origin = "*";
}

你可能感兴趣的:(使用Varnish4.1.8搭建HLS直播CDN)