策略子集加载
一些adapter支持过滤策略管理。 This means that the policy loaded by Casbin is a subset of the policy stored in the database based on a given filter. This allows for efficient policy enforcement in large, multi-tenant environments where parsing the entire policy becomes a performance bottleneck.
要使用支持的adapter处理过滤后的策略,只需调用 LoadFilteredPolicy
方法。 过滤器参数的有效格式取决于所用的适配器。 为了防止意外数据丢失,当策略已经加载, SavePolicy
方法会被禁用。
例如,下面的代码片段使用内置的过滤文件adapter和带有域的RBAC模型。 在本例中,过滤器将策略限制为单个域。 除 "domain1"
以外的任何域策略行被忽略:
import (
"github.com/casbin/casbin/v2"
fileadapter "github.com/casbin/casbin/v2/persist/file-adapter"
)
enforcer, _ := casbin.NewEnforcer()
adapter := fileadapter.NewFilteredAdapter("examples/rbac_with_domains_policy.csv")
enforcer.InitWithAdapter("examples/rbac_with_domains_model.conf", adapter)
filter := &fileadapter.Filter{
P: []string{"", "domain1"},
G: []string{"", "", "domain1"},
}
enforcer.LoadFilteredPolicy(filter)
//加载策略现在只包含与“domain1”相关的条目。
There is another method that supports the subset loading feature: LoadIncrementalFilteredPolicy
. LoadIncrementalFilteredPolicy
is similar to LoadFilteredPolicy
, but it does not clear the previously loaded policy. It only appends the filtered policy to the existing policy.