shikeyin
2024-01-11 65da8373531677b1c37a98f53eaa30c892f35e5a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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<UserPrincipal<?>> implements UserOnlineProvider {
 
    // 存储用户: key --> 登录过期时间
    private Map<String, Long> 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("启动定时任务,定期清理过期的用户登录信息,但暂未实现。");
    }
}