Speed up latest entry lookup by using the cache if it's not empty

This commit is contained in:
Kelvin Ly 2023-09-27 23:09:29 -04:00
parent 88136304e4
commit c38fbc474c
2 changed files with 27 additions and 0 deletions

View File

@ -12,6 +12,20 @@ type DataCache struct {
start int
}
func (dc *DataCache) LatestTime() int64 {
dc.Lock()
defer dc.Unlock()
if len(dc.data) == 0 {
return -1
}
if dc.start == 0 {
return int64(dc.data[len(dc.data)-1].Time)
} else {
return int64(dc.data[dc.start-1].Time)
}
}
func (dc *DataCache) Add(data *Datapoint) {
dc.Lock()
defer dc.Unlock()

View File

@ -106,6 +106,19 @@ func main() {
dumpSecond := dumpData(db, &state.Cache, 1000)
lastPoint := func(w http.ResponseWriter, _req *http.Request) {
var err error
time := state.Cache.LatestTime()
if time > 0 {
msg, err := json.Marshal(time)
if err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
} else {
w.Write(msg)
}
return
}
msg, err := s.LastTime(db)
if err != nil {
w.WriteHeader(500)