缓存使用

# 缓存使用

# 1. 缓存规范

为了不过多依赖第三方中间件,也能正常启动,默认采用了map内存缓存,但是Snowy的缓存是以接口为单位使用的,非常方便拓展。

所有的缓存类都实现了CacheOperator接口

所有的基于内存的缓存都继承AbstractMemoryCacheOperator类。

所有的基于redis的缓存都继承AbstractRedisCacheOperator类。

# 2. 本地缓存

首先编写自定义类继承AbstractMemoryCacheOperator类,我们以用户缓存为例如下:

public class UserCache extends AbstractMemoryCacheOperator<SysLoginUser> {

    /**
     * 登录用户缓存前缀
     */
    public static final String LOGIN_USER_CACHE_PREFIX = "LOGIN_USER_";

    public UserCache(TimedCache<String, SysLoginUser> timedCache) {
        super(timedCache);
    }

    @Override
    public String getCommonKeyPrefix() {
        return LOGIN_USER_CACHE_PREFIX;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
复制代码

编写过程中,只需要override一个getCommonKeyPrefix方法就行,这个方法用来标识这个缓存集的前缀。

另外要加一个构造函数,构造函数的参数值是TimedCache,我们的本地缓存用的hutool的本地缓存工具https://www.hutool.cn/docs/#/cache/%E6%A6%82%E8%BF%B0 (opens new window)

编写完成后要加一个@Component注解放到spring容器中,但是我们推荐用@Bean的方式添加到CacheConfig类中,这样可以清晰的看到现在系统有哪些缓存。

之后就可以用这个缓存了,在别的类中注入这个UserCache就可以用了。

# 3. redis缓存

由于默认没有启用redis,所以要先引入pom,检查snowy-system的pom文件,检查是否引入了redis的依赖,如果带有optional标签就去掉这一行。

第二步,在yml中配置redis的服务器和端口和密码信息如下:

第三步,新建RedisTemplate类,因为在自定义缓存中要用redisTemplate来进行操作缓存,所以在spring容器中要装载一个RedisTemplate类。

@Bean
public RedisTemplate<String, SysLoginUser> redisTemplate(RedisConnectionFactory factory) {
    RedisTemplate<String, SysLoginUser> userRedisTemplate = new RedisTemplate<>();
    userRedisTemplate.setConnectionFactory(factory);
    userRedisTemplate.setKeySerializer(new StringRedisSerializer());
    userRedisTemplate.setValueSerializer(new FastJson2JsonRedisSerializer<>(SysLoginUser.class));
    userRedisTemplate.afterPropertiesSet();
    return userRedisTemplate;
}
1
2
3
4
5
6
7
8
9
复制代码

接下来您可以直接用RedisTemplate来操作缓存了,但是一般不建议这么用,这样不适合做拓展。

第四步,配置替换缓存操作类vip.xiaonuo.sys.core.cache.UserCache,为如下:

public class UserCache extends AbstractRedisCacheOperator<SysLoginUser> {

    /**
     * 登录用户缓存前缀
     */
    public static final String LOGIN_USER_CACHE_PREFIX = "LOGIN_USER_";

    public UserCache(RedisTemplate<String, SysLoginUser> redisTemplate) {
        super(redisTemplate);
    }

    @Override
    public String getCommonKeyPrefix() {
        return LOGIN_USER_CACHE_PREFIX;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
复制代码

第五步,装配缓存操作类到vip.xiaonuo.sys.config.CacheConfig类中,或者直接在UserCache类上加@Component注解:

@Bean
public UserCache userCache(RedisTemplate<String, SysLoginUser> redisTemplate) {
    return new UserCache(redisTemplate);
}
1
2
3
4
复制代码
Last Updated: Invalid Date