package com.iplatform.base.cache;
|
|
import com.iplatform.base.Constants;
|
import com.iplatform.base.UserCacheProvider;
|
import com.iplatform.base.service.UserServiceImpl;
|
import com.iplatform.model.po.S_user_core;
|
import com.walker.cache.Cache;
|
import com.walker.infrastructure.utils.StringUtils;
|
import com.walker.support.redis.cache.RedisCacheProvider;
|
|
import java.util.List;
|
|
/**
|
* Redis实现的用户缓存提供者。
|
* @author 时克英
|
* @date 2022-11-06
|
*/
|
public class RedisUserCacheProvider extends RedisCacheProvider<S_user_core> implements UserCacheProvider {
|
|
private UserServiceImpl userService = null;
|
|
private boolean allowInitCache = true;
|
|
/**
|
* 设置是否允许初始化加载用户到缓存。
|
* @param allowInitCache
|
* @date 2023-07-17
|
*/
|
public void setAllowInitCache(boolean allowInitCache) {
|
this.allowInitCache = allowInitCache;
|
}
|
|
public void setUserService(UserServiceImpl userService) {
|
this.userService = userService;
|
}
|
|
public RedisUserCacheProvider(){
|
this.setUseRedis(true);
|
this.setLoadPage(false);
|
}
|
|
@Override
|
public String getProviderName() {
|
return Constants.CACHE_NAME_USER;
|
}
|
|
@Override
|
public Class<?> getProviderType() {
|
return S_user_core.class;
|
}
|
|
@Override
|
protected int loadDataToCache(Cache cache) {
|
if(this.allowInitCache){
|
List<S_user_core> hosts = this.userService.selectAll(new S_user_core());
|
if(!StringUtils.isEmptyList(hosts)){
|
// ------------------------- 切换成普通缓存步骤:3
|
if(this.isUseRedis()){
|
// 如果redis中缓存数量和数据库中不一致(少),则清空redis缓存,重新加载数据库数据到缓存中。
|
long totalCache = cache.getPersistentSize();
|
if(totalCache != hosts.size()){
|
logger.info("redis缓存中用户数量小于实际用户,需要清空缓存重新加载! cache = " + totalCache + ", db = " + hosts.size());
|
cache.clear();
|
|
for(S_user_core h : hosts){
|
cache.put(String.valueOf(h.getId()), h);
|
}
|
}
|
}//------------------------------------------
|
return hosts.size();
|
}
|
} else {
|
logger.info("........由于用户量较大,所以配置:不需要初始化加载用户缓存!");
|
}
|
return 0;
|
}
|
|
@Override
|
public S_user_core getUser(long userId) {
|
S_user_core user_core = this.getCacheData(String.valueOf(userId));
|
if(user_core == null){
|
logger.warn("缓存中未找到用户对象,尝试从数据库加载, userId = " + userId);
|
user_core = this.userService.get(new S_user_core(userId));
|
this.putCacheData(String.valueOf(userId), user_core);
|
}
|
return user_core;
|
}
|
|
@Override
|
public void updateUser(S_user_core user_core) {
|
if(user_core == null){
|
throw new IllegalArgumentException("更新用户缓存错误,user_core = null");
|
}
|
this.updateCacheData(String.valueOf(user_core.getId()), user_core);
|
}
|
|
@Override
|
public void removeUser(long userId) {
|
this.removeCacheData(String.valueOf(userId));
|
}
|
|
@Override
|
public void putUser(S_user_core user_core) {
|
if(user_core == null){
|
throw new IllegalArgumentException("添加用户缓存错误: user_core = null");
|
}
|
this.putCacheData(String.valueOf(user_core.getId()), user_core);
|
}
|
}
|