1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

Use expirable cache for summaries.

This commit is contained in:
Ferdinand Mütsch 2019-05-21 21:46:23 +02:00
parent 81eea21fd5
commit cdf158e2ac

View File

@ -2,6 +2,7 @@ package routes
import ( import (
"crypto/md5" "crypto/md5"
"fmt"
"net/http" "net/http"
"strconv" "strconv"
"time" "time"
@ -9,6 +10,7 @@ import (
"github.com/n1try/wakapi/models" "github.com/n1try/wakapi/models"
"github.com/n1try/wakapi/services" "github.com/n1try/wakapi/services"
"github.com/n1try/wakapi/utils" "github.com/n1try/wakapi/utils"
cache "github.com/patrickmn/go-cache"
) )
const ( const (
@ -18,10 +20,17 @@ const (
IntervalLastYear string = "year" IntervalLastYear string = "year"
) )
var summaryCache map[string]*models.Summary
type SummaryHandler struct { type SummaryHandler struct {
SummarySrvc *services.SummaryService SummarySrvc *services.SummaryService
Cache *cache.Cache
Initialized bool
}
func (m *SummaryHandler) Init() {
if m.Cache == nil {
m.Cache = cache.New(24*time.Hour, 24*time.Hour)
}
m.Initialized = true
} }
func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) { func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
@ -30,7 +39,9 @@ func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
return return
} }
tryInitCache() if !h.Initialized {
h.Init()
}
user := r.Context().Value(models.UserKey).(*models.User) user := r.Context().Value(models.UserKey).(*models.User)
params := r.URL.Query() params := r.URL.Query()
@ -61,29 +72,25 @@ func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
var summary *models.Summary var summary *models.Summary
cacheKey := getHash([]time.Time{from, to}) cacheKey := getHash([]time.Time{from, to})
if _, ok := summaryCache[cacheKey]; !ok { cachedSummary, ok := h.Cache.Get(cacheKey)
if !ok {
// Cache Miss // Cache Miss
fmt.Println("Cache miss")
summary, err = h.SummarySrvc.GetSummary(from, to, user) // 'to' is always constant summary, err = h.SummarySrvc.GetSummary(from, to, user) // 'to' is always constant
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
if !live { if !live {
summaryCache[cacheKey] = summary h.Cache.Set(cacheKey, summary, cache.DefaultExpiration)
} }
} else { } else {
summary, _ = summaryCache[cacheKey] summary = cachedSummary.(*models.Summary)
} }
utils.RespondJSON(w, http.StatusOK, summary) utils.RespondJSON(w, http.StatusOK, summary)
} }
func tryInitCache() {
if summaryCache == nil {
summaryCache = make(map[string]*models.Summary)
}
}
func getHash(times []time.Time) string { func getHash(times []time.Time) string {
digest := md5.New() digest := md5.New()
for _, t := range times { for _, t := range times {