fix(video): fix hls in-memory cache being recreated on every request
This commit is contained in:
parent
42249fbc58
commit
c8985093fb
@ -19,6 +19,11 @@ import (
|
|||||||
"github.com/victorspringer/http-cache/adapter/memory"
|
"github.com/victorspringer/http-cache/adapter/memory"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
cacheAdapter *cache.Adapter
|
||||||
|
hlsResponseCache *cache.Client
|
||||||
|
)
|
||||||
|
|
||||||
type FileServerHandler struct {
|
type FileServerHandler struct {
|
||||||
HLSPath string
|
HLSPath string
|
||||||
}
|
}
|
||||||
@ -35,24 +40,30 @@ func HandleHLSRequest(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
responseCache, err := memory.NewAdapter(
|
if cacheAdapter == nil {
|
||||||
memory.AdapterWithAlgorithm(memory.LRU),
|
ca, err := memory.NewAdapter(
|
||||||
memory.AdapterWithCapacity(20),
|
memory.AdapterWithAlgorithm(memory.LFU),
|
||||||
memory.AdapterWithStorageCapacity(209_715_200),
|
memory.AdapterWithCapacity(50),
|
||||||
)
|
memory.AdapterWithStorageCapacity(104_857_600),
|
||||||
if err != nil {
|
)
|
||||||
log.Warn("unable to create web cache", err)
|
cacheAdapter = &ca
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("unable to create web cache", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Since HLS segments cannot be changed once they're rendered, we can cache
|
// Since HLS segments cannot be changed once they're rendered, we can cache
|
||||||
// individual segments for a long time.
|
// individual segments for a long time.
|
||||||
longTermHLSSegmentCache, err := cache.NewClient(
|
if hlsResponseCache == nil {
|
||||||
cache.ClientWithAdapter(responseCache),
|
rc, err := cache.NewClient(
|
||||||
cache.ClientWithTTL(30*time.Second),
|
cache.ClientWithAdapter(*cacheAdapter),
|
||||||
cache.ClientWithExpiresHeader(),
|
cache.ClientWithTTL(30*time.Second),
|
||||||
)
|
cache.ClientWithExpiresHeader(),
|
||||||
if err != nil {
|
)
|
||||||
log.Warn("unable to create web cache client", err)
|
hlsResponseCache = rc
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("unable to create web cache client", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
requestedPath := r.URL.Path
|
requestedPath := r.URL.Path
|
||||||
@ -82,7 +93,7 @@ func HandleHLSRequest(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(cacheTime))
|
w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(cacheTime))
|
||||||
|
|
||||||
fileServer := &FileServerHandler{HLSPath: fullPath}
|
fileServer := &FileServerHandler{HLSPath: fullPath}
|
||||||
longTermHLSSegmentCache.Middleware(fileServer).ServeHTTP(w, r)
|
hlsResponseCache.Middleware(fileServer).ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user