From 5ebc282bf96950789e1ccaf9f6721c4856fdfc1a Mon Sep 17 00:00:00 2001 From: NatureFreshMilk Date: Fri, 11 Jan 2019 09:07:31 +0100 Subject: [PATCH] accessor cache --- go.mod | 1 + go.sum | 2 ++ mapblockaccessor/mapblockaccessor.go | 28 ++++++++++++++++++++++++++-- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 545d048..115778f 100644 --- a/go.mod +++ b/go.mod @@ -2,5 +2,6 @@ module mapserver require ( github.com/mattn/go-sqlite3 v1.10.0 + github.com/patrickmn/go-cache v2.1.0+incompatible github.com/sirupsen/logrus v1.3.0 ) diff --git a/go.sum b/go.sum index 84060a0..a10de16 100644 --- a/go.sum +++ b/go.sum @@ -3,6 +3,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o= github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= diff --git a/mapblockaccessor/mapblockaccessor.go b/mapblockaccessor/mapblockaccessor.go index 28947a6..5afb7fe 100644 --- a/mapblockaccessor/mapblockaccessor.go +++ b/mapblockaccessor/mapblockaccessor.go @@ -4,30 +4,54 @@ import ( "mapserver/coords" "mapserver/db" "mapserver/mapblockparser" + "github.com/patrickmn/go-cache" + "time" + "fmt" ) type MapBlockAccessor struct { accessor db.DBAccessor + c *cache.Cache +} + +func getKey(pos coords.MapBlockCoords) string { + return fmt.Sprintf("Coord %d/%d/%d", pos.X, pos.Y, pos.Z) } func NewMapBlockAccessor(accessor db.DBAccessor) *MapBlockAccessor { - return &MapBlockAccessor{accessor: accessor} + c := cache.New(5*time.Minute, 10*time.Minute) + + return &MapBlockAccessor{accessor: accessor, c: c} } func (a *MapBlockAccessor) Update(pos coords.MapBlockCoords, mb *mapblockparser.MapBlock) { - //TODO: cache + key := getKey(pos) + a.c.Set(key, mb, cache.DefaultExpiration) } func (a *MapBlockAccessor) GetMapBlock(pos coords.MapBlockCoords) (*mapblockparser.MapBlock, error) { + key := getKey(pos) + + cachedblock, found := a.c.Get(key) + if found { + return cachedblock.(*mapblockparser.MapBlock), nil + } + block, err := a.accessor.GetBlock(pos) if err != nil { return nil, err } + if block == nil { + return nil, nil + } + mapblock, err := mapblockparser.Parse(block.Data) if err != nil { return nil, err } + a.c.Set(key, mapblock, cache.DefaultExpiration) + return mapblock, nil }