7.10. 用户缓存
当用户对象由 ID、用户名或电子邮件查询加载时,会缓存它。当用户对象被缓存时,它会迭代整个 UserModel 接口,并将这些信息拉取到本地仅内存缓存中。在集群中,这个缓存仍然是本地的,但它成为无效缓存。修改用户对象时,它将被驱除。此驱除事件会被传播到整个集群,以便其他节点的用户缓存也无效。
7.10.1. 管理用户缓存 复制链接链接已复制到粘贴板!
您可以通过调用 KeycloakSession.getProvider (UserCache.class) 来访问用户缓存。
/**
* 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();
}
有方法可以驱除特定用户、特定域中包含的用户或整个缓存。
7.10.2. OnUserCache 回调接口 复制链接链接已复制到粘贴板!
您可能想要缓存特定于您的供应商实现的额外信息。用户存储 SPI 在用户缓存时会有一个回调: org.keycloak.models.cache.OnUserCache。
public interface OnUserCache {
void onCache(RealmModel realm, CachedUserModel user, UserModel delegate);
}
如果您希望此回调,您的供应商类应实施此接口。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();
}
此 CachedUserModel 接口允许您从缓存中驱除用户,并获取供应商 UserModel 实例。getCachedWith () 方法返回一个映射,供您缓存与用户相关的其他信息。例如,凭证不是 UserModel 接口的一部分。如果要在内存中缓存凭证,您将实施 OnUserCache,并使用 getCachedWith () 方法缓存用户的凭证。
7.10.3. 缓存策略 复制链接链接已复制到粘贴板!
在用户存储供应商的管理控制台管理页面中,您可以指定唯一的缓存策略。