Use hashicorp implementation which mutexes for us

This commit is contained in:
Neil Alexander 2020-04-22 11:01:42 +01:00
parent fc4e82c246
commit 3ca36e1319
2 changed files with 15 additions and 13 deletions

View file

@ -85,11 +85,16 @@ func NewBaseDendrite(cfg *config.Dendrite, componentName string) *BaseDendrite {
kafkaConsumer, kafkaProducer = setupKafka(cfg)
}
cache, err := caching.NewInMemoryLRUCache()
if err != nil {
logrus.WithError(err).Warnf("Failed to create cache")
}
return &BaseDendrite{
componentName: componentName,
tracerCloser: closer,
Cfg: cfg,
Cache: caching.NewInMemoryLRUCache(), // TODO: make configurable
Cache: cache,
APIMux: mux.NewRouter().UseEncodedPath(),
httpClient: &http.Client{Timeout: HTTPClientTimeout},
KafkaConsumer: kafkaConsumer,

View file

@ -1,30 +1,29 @@
package caching
import (
"sync"
"github.com/golang/groupcache/lru"
lru "github.com/hashicorp/golang-lru"
"github.com/matrix-org/gomatrixserverlib"
)
type InMemoryLRUCache struct {
roomVersions *lru.Cache
roomVersionsMutex sync.RWMutex
roomVersions *lru.Cache
}
func NewInMemoryLRUCache() *InMemoryLRUCache {
return &InMemoryLRUCache{
roomVersions: lru.New(128),
func NewInMemoryLRUCache() (*InMemoryLRUCache, error) {
roomVersionCache, rvErr := lru.New(128)
if rvErr != nil {
return nil, rvErr
}
return &InMemoryLRUCache{
roomVersions: roomVersionCache,
}, nil
}
func (c *InMemoryLRUCache) GetRoomVersion(roomID string) (gomatrixserverlib.RoomVersion, bool) {
if c == nil {
return "", false
}
c.roomVersionsMutex.RLock()
val, found := c.roomVersions.Get(roomID)
c.roomVersionsMutex.RUnlock()
if found && val != nil {
if roomVersion, ok := val.(gomatrixserverlib.RoomVersion); ok {
return roomVersion, true
@ -37,7 +36,5 @@ func (c *InMemoryLRUCache) StoreRoomVersion(roomID string, roomVersion gomatrixs
if c == nil {
return
}
c.roomVersionsMutex.Lock()
defer c.roomVersionsMutex.Unlock()
c.roomVersions.Add(roomID, roomVersion)
}