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) kafkaConsumer, kafkaProducer = setupKafka(cfg)
} }
cache, err := caching.NewInMemoryLRUCache()
if err != nil {
logrus.WithError(err).Warnf("Failed to create cache")
}
return &BaseDendrite{ return &BaseDendrite{
componentName: componentName, componentName: componentName,
tracerCloser: closer, tracerCloser: closer,
Cfg: cfg, Cfg: cfg,
Cache: caching.NewInMemoryLRUCache(), // TODO: make configurable Cache: cache,
APIMux: mux.NewRouter().UseEncodedPath(), APIMux: mux.NewRouter().UseEncodedPath(),
httpClient: &http.Client{Timeout: HTTPClientTimeout}, httpClient: &http.Client{Timeout: HTTPClientTimeout},
KafkaConsumer: kafkaConsumer, KafkaConsumer: kafkaConsumer,

View file

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