package com.iplatform.base.cache; import com.iplatform.base.Constants; import com.iplatform.base.VariableConstants; import com.iplatform.base.util.TokenUtils; import com.walker.cache.AbstractCacheProvider; import com.walker.cache.Cache; import com.walker.web.UserOnlineProvider; import com.walker.web.UserPrincipal; import java.util.HashMap; import java.util.Map; /** * 基于内存实现的在线用户提供者实现。 * @author 时克英 * @date 2022-11-01 */ public class LocalUserOnlineProvider extends AbstractCacheProvider> implements UserOnlineProvider { // 存储用户: key --> 登录过期时间 private Map captchaKeyExpiredMap = new HashMap<>(); public LocalUserOnlineProvider(){ this.runClearDirtyCacheTask(); } @Override protected int loadDataToCache(Cache cache) { // 内存无法持久化,因此这里无需启动时加载已有缓存 return 0; } @Override public String getProviderName() { return Constants.CACHE_NAME_ONLINE_USER; } @Override public Class getProviderType() { return UserPrincipal.class; } @Override public UserPrincipal getUserPrincipal(String token) { UserPrincipal userPrincipal = this.getCacheData(token); if(userPrincipal == null){ logger.warn("UserOnlineProvider 缓存用户不存在, token = " + token); } return userPrincipal; } @Override public boolean cacheUserPrincipal(String token, UserPrincipal userPrincipal) { logger.debug("写入用户登录缓存: " + token + ", " + userPrincipal.getUserName()); this.putCacheData(token, userPrincipal, TokenUtils.acquireCacheUserExpiredSeconds(VariableConstants.DEFAULT_TOKEN_EXPIRED_MINUTES)); return true; } @Override public boolean cacheUserPrincipal(String token, UserPrincipal userPrincipal, long expiredMinutes) { return this.cacheUserPrincipal(token, userPrincipal); } @Override public boolean updateUserPrincipalTimeStamp(String token) { return false; } @Override public boolean removeUserPrincipal(String token) { this.removeCacheData(token); this.captchaKeyExpiredMap.remove(token); return true; } @Override public void putCacheData(String key, UserPrincipal userPrincipal, long expiredSeconds){ this.putCacheData(key, userPrincipal); this.captchaKeyExpiredMap.put(key, expiredSeconds); } private void runClearDirtyCacheTask(){ logger.info("启动定时任务,定期清理过期的用户登录信息,但暂未实现。"); } }