Browse Source

Feature: support adding custom cache to mongoc and sqlc (#1313)

* merge

* Feature: support adding custom cache to mongoc and sqlc
MarkJoyMa 3 years ago
parent
commit
3e6c217408
2 changed files with 22 additions and 0 deletions
  1. 10 0
      core/stores/mongoc/cachedmodel.go
  2. 12 0
      core/stores/sqlc/cachedsql.go

+ 10 - 0
core/stores/mongoc/cachedmodel.go

@@ -52,6 +52,16 @@ func NewModel(url, collection string, conf cache.CacheConf, opts ...cache.Option
 	})
 	})
 }
 }
 
 
+// NewModelWithCache returns a Model with a custom cache.
+func NewModelWithCache(url, collection string, c cache.Cache) (*Model, error) {
+	if c == nil {
+		log.Fatal("Invalid cache component")
+	}
+	return createModel(url, collection, c, func(collection mongo.Collection) CachedCollection {
+		return newCollection(collection, c)
+	})
+}
+
 // Count returns the count of given query.
 // Count returns the count of given query.
 func (mm *Model) Count(query interface{}) (int, error) {
 func (mm *Model) Count(query interface{}) (int, error) {
 	return mm.executeInt(func(c CachedCollection) (int, error) {
 	return mm.executeInt(func(c CachedCollection) (int, error) {

+ 12 - 0
core/stores/sqlc/cachedsql.go

@@ -2,6 +2,7 @@ package sqlc
 
 
 import (
 import (
 	"database/sql"
 	"database/sql"
+	"log"
 	"time"
 	"time"
 
 
 	"github.com/tal-tech/go-zero/core/stores/cache"
 	"github.com/tal-tech/go-zero/core/stores/cache"
@@ -55,6 +56,17 @@ func NewConn(db sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) CachedCon
 	}
 	}
 }
 }
 
 
+// NewConnWithCache returns a CachedConn with a custom cache.
+func NewConnWithCache(db sqlx.SqlConn, c cache.Cache) CachedConn {
+	if c == nil {
+		log.Fatal("Invalid cache component")
+	}
+	return CachedConn{
+		db:    db,
+		cache: c,
+	}
+}
+
 // DelCache deletes cache with keys.
 // DelCache deletes cache with keys.
 func (cc CachedConn) DelCache(keys ...string) error {
 func (cc CachedConn) DelCache(keys ...string) error {
 	return cc.cache.Del(keys...)
 	return cc.cache.Del(keys...)