From 80ca431ada92c8f9d03a8277d4af361bb87d74a1 Mon Sep 17 00:00:00 2001 From: heqian <182359041@qq.com> Date: Wed, 11 Dec 2024 16:36:43 +0800 Subject: [PATCH] =?UTF-8?q?Allows=20to=20adjust=20storeInCache=20to=20solv?= =?UTF-8?q?e=20cache=20penetration=20problem=20when=20the=20database=20can?= =?UTF-8?q?not=20find=20the=20data.=20=E5=85=81=E8=AE=B8=E8=B0=83=E6=95=B4?= =?UTF-8?q?=20storeInCache=20=E6=9D=A5=E8=A7=A3=E5=86=B3=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93=E6=89=BE=E4=B8=8D=E5=88=B0=E6=95=B0=E6=8D=AE=E6=97=B6?= =?UTF-8?q?=E7=9A=84=E7=BC=93=E5=AD=98=E7=A9=BF=E9=80=8F=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- caches.go | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/caches.go b/caches.go index 97c1ae7..6f06a56 100644 --- a/caches.go +++ b/caches.go @@ -75,13 +75,11 @@ func (c *Caches) query(db *gorm.DB) { } c.ease(db, identifier) - if db.Error != nil { - return - } - - c.storeInCache(db, identifier) - if db.Error != nil { - return + switch db.Error { + case nil: + c.storeInCache(db, identifier, true) + case gorm.ErrRecordNotFound: // Record not found, we can safely cache it as nil + c.storeInCache(db, identifier, false) } } @@ -153,12 +151,16 @@ func (c *Caches) checkCache(db *gorm.DB, identifier string) bool { return false } -func (c *Caches) storeInCache(db *gorm.DB, identifier string) { +func (c *Caches) storeInCache(db *gorm.DB, identifier string, isFound bool) { if c.Conf.Cacher != nil { - err := c.Conf.Cacher.Store(db.Statement.Context, identifier, &Query[any]{ - Dest: db.Statement.Dest, - RowsAffected: db.Statement.RowsAffected, - }) + var val *Query[any] + if isFound { + val = &Query[any]{ + Dest: db.Statement.Dest, + RowsAffected: db.Statement.RowsAffected, + } + } + err := c.Conf.Cacher.Store(db.Statement.Context, identifier, val) if err != nil { _ = db.AddError(err) }