5

keycloak~缓存的使用

 2 years ago
source link: https://www.cnblogs.com/lori/p/15476886.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

keycloak缓存的级别,往大了说有realm级的,一个realm是一个缓存,这也是它的生命周期;往小了说,也有user级的,即一个用户一个缓存,当a用户和b用户,它们的缓存是两个。

缓存提供者

InfinispanConnectionProvider是一个接口,主要是对infinispan缓存的规定,有默认的实现DefaultInfinispanConnectionProvider,它内包含了嵌入的infinispan缓存和远程的infinispan,分为两个独立的方法getCache和getRemoteCache,我们根据自己的情况而用。

  • KEYS_CACHE_NAME key的字典缓存
  • REALM_CACHE_NAME 域的数据缓存
  • USER_CACHE_NAME 每个用户的缓存

下面是一个标准的缓存逻辑代码,功能是为域添加一个缓存,叫USER_IP_ADDRESS,存储ip的字典信息

 public static List<GroupAttributeEntity> getIpFromCache(KeycloakSession session) {
    InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);
    // 注意:REALM_CACHE_NAME表示域级别的缓存,USER_CACHE_NAME是用户级别的,咱们这个使用域缓存即可
    if (provider.getCache(REALM_CACHE_NAME) != null) {
      if (!provider.getCache(REALM_CACHE_NAME).containsKey(USER_IP_ADDRESS)) {
        provider.getCache(REALM_CACHE_NAME).put(USER_IP_ADDRESS, getIpListFromDb(session), 24, TimeUnit.HOURS);
      }
      List<GroupAttributeEntity> ipList = (List<GroupAttributeEntity>) provider.getCache(REALM_CACHE_NAME).get(USER_IP_ADDRESS);
      return ipList;
    }
    return getIpListFromDb(session);
  }

之前犯了一个很傻的错误,把REALM_CACHE_NAME写成了USER_CACHE_NAME,导致每个用户都存了一份IP字典,这完全是没有必要的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK