1.0
xin
2025-04-15 e718afd02965c6a4018506acb1ae99baca0c5645
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
package com.oying.modules.security.service;
 
import cn.hutool.core.util.RandomUtil;
import com.oying.modules.security.service.dto.JwtUserDto;
import com.oying.modules.security.config.LoginProperties;
import com.oying.utils.RedisUtils;
import com.oying.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
 
/**
 * @author Z
 * @description 用户缓存管理
 * @date 2022-05-26
 **/
@Component
public class UserCacheManager {
 
    @Resource
    private RedisUtils redisUtils;
    @Value("${login.user-cache.idle-time}")
    private long idleTime;
 
    /**
     * 返回用户缓存
     * @param userName 用户名
     * @return JwtUserDto
     */
    public JwtUserDto getUserCache(String userName) {
        // 转小写
        userName = StringUtils.lowerCase(userName);
        if (StringUtils.isNotEmpty(userName)) {
            // 获取数据
            return redisUtils.get(LoginProperties.cacheKey + userName, JwtUserDto.class);
        }
        return null;
    }
 
    /**
     *  添加缓存到Redis
     * @param userName 用户名
     */
    @Async
    public void addUserCache(String userName, JwtUserDto user) {
        // 转小写
        userName = StringUtils.lowerCase(userName);
        if (StringUtils.isNotEmpty(userName)) {
            // 添加数据, 避免数据同时过期
            long time = idleTime + RandomUtil.randomInt(900, 1800);
            redisUtils.set(LoginProperties.cacheKey + userName, user, time);
        }
    }
 
    /**
     * 清理用户缓存信息
     * 用户信息变更时
     * @param userName 用户名
     */
    @Async
    public void cleanUserCache(String userName) {
        // 转小写
        userName = StringUtils.lowerCase(userName);
        if (StringUtils.isNotEmpty(userName)) {
            // 清除数据
            redisUtils.del(LoginProperties.cacheKey + userName);
        }
    }
}