7.9. 用户缓存


当用户对象由 ID、用户名或电子邮件查询被缓存时。当用户对象被缓存时,它会迭代整个 UserModel 接口,并将这些信息拉取到一个本地只读缓存。在集群中,这个缓存仍然是本地的,但它会变为无效的缓存。修改用户对象时,它将被驱除。这个驱除事件会传播到整个集群,以便其他节点的用户缓存也无效。

7.9.1. 管理用户缓存

您可以通过调用 KeycloakSession.userCache () 来访问用户缓存。

/**
 * All these methods effect an entire cluster of Keycloak instances.
 *
 * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
 * @version $Revision: 1 $
 */
public interface UserCache extends UserProvider {
    /**
     * Evict user from cache.
     *
     * @param user
     */
    void evict(RealmModel realm, UserModel user);

    /**
     * Evict users of a specific realm
     *
     * @param realm
     */
    void evict(RealmModel realm);

    /**
     * Clear cache entirely.
     *
     */
    void clear();
}
Copy to Clipboard Toggle word wrap

有方法可以驱除特定用户、特定域或整个缓存中包含的用户。

7.9.2. OnUserCache 回调接口

您可能需要缓存特定于供应商的实现的额外信息。每当缓存用户时,User Storage SPI 具有回调: org.keycloak.models.cache.OnUserCache

public interface OnUserCache {
    void onCache(RealmModel realm, CachedUserModel user, UserModel delegate);
}
Copy to Clipboard Toggle word wrap

如果您的供应商类应该实现这个接口(如果它想要这个回调)。UserModel delegate 参数是您的供应商返回的 UserModel 实例。CachedUserModel 是一个展开的 UserModel 接口。这是在本地本地存储中缓存的实例。

public interface CachedUserModel extends UserModel {

    /**
     * Invalidates the cache for this user and returns a delegate that represents the actual data provider
     *
     * @return
     */
    UserModel getDelegateForUpdate();

    boolean isMarkedForEviction();

    /**
     * Invalidate the cache for this model
     *
     */
    void invalidate();

    /**
     * When was the model was loaded from database.
     *
     * @return
     */
    long getCacheTimestamp();

    /**
     * Returns a map that contains custom things that are cached along with this model.  You can write to this map.
     *
     * @return
     */
    ConcurrentHashMap getCachedWith();
}
Copy to Clipboard Toggle word wrap

这个 CachedUserModel 接口允许您从缓存中驱除用户并获取提供程序 UserModel 实例。getCachedWith () 方法返回一个映射,允许您缓存与用户相关的其他信息。例如,凭证不是 UserModel 接口的一部分。如果要在内存中缓存凭据,您要使用 getCachedWith () 方法实施 OnUserCache 和缓存用户凭证。

7.9.3. 缓存策略

在用户存储供应商的管理控制台管理页面中,您可以指定唯一的缓存策略。

返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat