From 66315830efb9297541e6a360dde1facda5089a96 Mon Sep 17 00:00:00 2001 From: closetool <4closetool3@gmail.com> Date: Sat, 15 May 2021 13:16:13 +0800 Subject: [PATCH] service/sys_casbin.go: fix casbin runs slowly --- server/service/sys_casbin.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/server/service/sys_casbin.go b/server/service/sys_casbin.go index 457be1b7..effae3b3 100644 --- a/server/service/sys_casbin.go +++ b/server/service/sys_casbin.go @@ -6,6 +6,7 @@ import ( "gin-vue-admin/model" "gin-vue-admin/model/request" "strings" + "sync" "github.com/casbin/casbin/v2" "github.com/casbin/casbin/v2/util" @@ -89,11 +90,18 @@ func ClearCasbin(v int, p ...string) bool { //@description: 持久化到数据库 引入自定义规则 //@return: *casbin.Enforcer +var ( + e *casbin.Enforcer + once sync.Once +) + func Casbin() *casbin.Enforcer { - admin := global.GVA_CONFIG.Mysql - a, _ := gormadapter.NewAdapter(global.GVA_CONFIG.System.DbType, admin.Username+":"+admin.Password+"@("+admin.Path+")/"+admin.Dbname, true) - e, _ := casbin.NewEnforcer(global.GVA_CONFIG.Casbin.ModelPath, a) - e.AddFunction("ParamsMatch", ParamsMatchFunc) + once.Do(func() { + admin := global.GVA_CONFIG.Mysql + a, _ := gormadapter.NewAdapter(global.GVA_CONFIG.System.DbType, admin.Username+":"+admin.Password+"@("+admin.Path+")/"+admin.Dbname, true) + e, _ = casbin.NewEnforcer(global.GVA_CONFIG.Casbin.ModelPath, a) + e.AddFunction("ParamsMatch", ParamsMatchFunc) + }) _ = e.LoadPolicy() return e }