Compare commits

..

11 Commits

15 changed files with 1517 additions and 10 deletions

View File

@@ -1 +1 @@
# 本地址已停止维护了
# 国瑞药业

View File

@@ -2,8 +2,6 @@
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}

View File

@@ -0,0 +1,63 @@
package top.lidee.taie.security.cache;
/**
* 缓存对象key.
*
* @author lr
* @since 2019-07-30 09:28
*/
public enum CacheKeyEnum {
/**
* 保存5分钟签名防止恶意重复请求
*/
REPEAT_REQUEST_SIGN("system:repeat:sign:","请求签名"),
/**
* 保存用户可权限路径
*/
USER_AUTH("system:user:auth:","用户权限"),
/**
* 用户权限url
*/
USER_URL("system:user:url:","用户权限url"),
/**
* 保存用户角色
*/
USER_ROLE("system:user:role:","用户角色"),
/**
* 登录token
*/
TOKEN_JWT_USER("system:user:token:", "存放用户名及对应的token"),
/**
* 密码错误次数
*/
USER_PASSWORD_ERROR_NUMBER("system:user:password:errorNumber:", "密码错误次数"),
/**
* 保存用户对应的权限
*/
USER_AUTHORITIES("system:user:authorities:", "保存用户对应的权限");
private String key;
private String value;
CacheKeyEnum(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}}

View File

@@ -178,7 +178,7 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/login/**","/logout", "/health", "/user/loginCode/**").permitAll()
.antMatchers("/login/**","/logout","/outlogcas", "/health", "/user/loginCode/**").permitAll()
.mvcMatchers(HttpMethod.GET,"/dict/item/**").permitAll()
.anyRequest().authenticated()
.and()

View File

@@ -106,6 +106,14 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
</dependencies>
<build>

View File

@@ -0,0 +1,327 @@
package top.lidee.taie.cache;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* 缓存帮助类
* @author lr
* @since 2021-01-12
*/
public interface CacheHelper {
/**
* 获取指定key的String类型缓存
* @param key
* @return
*/
default String stringGet(String key) {
return null;
}
default Map<String,String> stringMultiGet(List<String> keys) {
return null;
}
/**
* 获取指定key的String类型缓存
* @param key
* @return
*/
default Boolean setIfAbsent(String key, String value) {
return false;
}
/**
* 增加1
* @param key
* @return
*/
default Long increment(String key) {
return 0L;
}
/**
* 设置失效时间
* @param key
* @param timeUnit
* @param timeout
*/
default void expire(String key, TimeUnit timeUnit, Long timeout) {
}
/**
* 增加1
* @param key
* @return
*/
default Long increment(String key, Long step) {
return 0L;
}
/**
* 是否存在指定KEY
* @param key
* @return
*/
default boolean exist(String key) {
return false;
}
/**
* 模糊匹配
* @param pattern
* @return
*/
default Set<String> keys(String pattern) {
return new HashSet<>();
}
/**
* 设置指定key的String类型缓存
* @param key
* @param value 缓存值
* @return
*/
default void stringSet(String key, String value) {
}
/**
* 设置指定key的String类型缓存包含过期时间
* @param key
* @param value
* @param time
* @param timeUnit 时间单位
*/
default void stringSetExpire(String key, String value, long time, TimeUnit timeUnit) {
}
/**
* 去掉前后空格
* @param key
* @return
*/
default String regKey(String key) {
return key.trim();
//.toLowerCase();
}
/**
* 设置指定key的String类型缓存包含过期时间
* @param key
* @param value
* @param seconds
*/
default void stringSetExpire(String key, String value, long seconds) {
}
/**
* 获取指定key的hash缓存
* @param key
* @return
*/
default Map<String, String> hashGet(String key) {
return new HashMap<>();
}
/***
* 获取指定key的hash中对应的值
*
* @param key
* @param keys
* @return
*/
default List<String> hashMultiGet(String key,Collection<String> keys){
return hashMultiGet(key,keys,false);
}
/***
* 获取指定key的hash中对应的值
*
* @param key
* @param keys
* @param includeDisabled 是否包括已禁用的数据
* @return
*/
default List<String> hashMultiGet(String key,Collection<String> keys,boolean includeDisabled){
return null;
}
/***
* disabled key后缀
* @return
*/
default String getDisabledKey(){
return ":DISABLED";
}
/***
* 批量获取hashSet
* @param key
* @param keys
* @param includeDisabled
* @return
*/
default Map<String,String> multiGet(String key,List<String> keys,boolean includeDisabled){
List<String> list = hashMultiGet(key,keys,includeDisabled);
Map<String,String> ret = new HashMap<>();
for(int i=0; i< keys.size();i++){
if(Objects.isNull(list.get(i))){
continue;
}
ret.put(keys.get(i),list.get(i));
}
return ret;
}
/**
* 获取指定key的hash中对应的值
* @param key
* @param hashKey
* @return
*/
default String hashGetString(String key, String hashKey) {
return null;
}
/**
* 删除Hash中指定key的值
* @param key
* @param hashKey
* @return
*/
default void hashDel(String key, String hashKey) {
}
/**
* 删除Hash中指定key的值
* @param key
* @param hashKeys
* @return
*/
default void hashBatchDel(String key, Set<String> hashKeys) {
hashBatchDel(key,hashKeys,false);
}
/**
* 删除Hash中指定key的值
* @param key
* @param hashKeys
* @param toDisable 删除的数据 key-rename
* @return
*/
default void hashBatchDel(String key, Set<String> hashKeys,boolean toDisable) {
}
/**
* 判断指定key的hash中包含指定hashKey
* @param key
* @param hashKey
* @return
*/
default boolean hashExist(String key, String hashKey) {
return false;
}
/**
* 判断指定key的hash中包含指定hashKeys中任何一个
* @param key
* @param hashKeys
* @return
*/
default boolean hashAnyExist(String key, String[] hashKeys) {
return false;
}
/**
* 设置指定key的hash缓存
* @param key
* @param hashKey
* @param hashValue
* @return
*/
default void hashSet(String key, String hashKey, String hashValue) {
}
/**
* 设置指定key的hash缓存
* @param hash
* @return
*/
default void hashSet(String key, Map<String, String> hash) {
}
default void hashMultiSet(Map<String, String> map){
}
/**
* 删除指定key
* @param key
* @return
*/
default boolean delete(String key) {
return false;
}
/**
* 删除指定key
* @param keys
* @return
*/
default boolean delete(List<String> keys) {
return false;
}
/**
* 向集合中添加
* @param key
* @param values
* @return
*/
default Long setAdd(String key, String[] values) {
return 0L;
}
/**
* 向集合中添加
* @param key
* @param values
* @param clear 是否清空旧数据
* @return
*/
default Long setAdd(String key, String[] values, boolean clear) {
return 0L;
}
/**
* 返回对应key的集合
* @param key
* @return
*/
default Set<String> setMembers(String key) {
return new HashSet<>();
}
/**
* 判断集合中是否有对应的value
* @param key
* @param value
* @return
*/
default Boolean setExist(String key, String value) {
return false;
}
}

View File

@@ -0,0 +1,248 @@
package top.lidee.taie.cache;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import top.lidee.taie.annotation.HashKey;
import top.lidee.taie.annotation.HashValue;
import top.lidee.taie.bean.HashKeyValue;
import top.lidee.taie.constant.BaseOperationEnum;
import top.lidee.taie.utils.ApplicationContextUtils;
import top.lidee.taie.utils.LideeUtils;
import top.lidee.taie.utils.ReflectionUtils;
/**
* 粗粒度的缓存服务重构LideeBaseService
* @author WongBin
* @date 2023/4/11
*/
public interface LideeCacheService {
default String formatKey(String key,String[] replaceArray, Object entity) {
return LideeUtils.formatKey(key,replaceArray,entity);
}
/***
* 单行数据的缓存刷新
* @param entity
* @param opr
*/
default <T> void refreshCacheFields(T entity, BaseOperationEnum opr){
//更新缓存
Field[] declaredFields = ReflectionUtils.getAllFieldsArr(entity);
Map<String,HashKeyValue> cacheMap = new HashMap<>();
for(Field field : declaredFields) {
field.setAccessible(true);
Object value;
if (field.isAnnotationPresent(HashKey.class)) {
try {
value = field.get(entity);
} catch (IllegalAccessException e) {
continue;
}
if (value == null) {
continue;
}
HashKey hashKey = field.getAnnotation(HashKey.class);
String key = hashKey.key();
//判断key是否存在
if (cacheMap.containsKey(key)) {
HashKeyValue hashKeyValue = cacheMap.get(key);
hashKeyValue.setKey(String.valueOf(value));
hashKeyValue.setHashKey(hashKey);
} else {
HashKeyValue hashKeyValue = new HashKeyValue();
hashKeyValue.setKey(String.valueOf(value));
hashKeyValue.setHashKey(hashKey);
cacheMap.put(key, hashKeyValue);
}
}
if (field.isAnnotationPresent(HashValue.class)) {
try {
value = field.get(entity);
} catch (IllegalAccessException e) {
continue;
}
if (value == null) {
continue;
}
HashValue hashValue = field.getAnnotation(HashValue.class);
String key = hashValue.key();
//判断key是否存在
if (cacheMap.containsKey(key)) {
HashKeyValue hashKeyValue = cacheMap.get(key);
hashKeyValue.setValue(String.valueOf(value));
} else {
HashKeyValue hashKeyValue = new HashKeyValue();
hashKeyValue.setValue(String.valueOf(value));
cacheMap.put(key, hashKeyValue);
}
}
}
//缓存操作类
CacheHelper cacheHelper = ApplicationContextUtils.getBean(CacheHelper.class);
if (BaseOperationEnum.DELETE == opr || BaseOperationEnum.DELETE_BATCH == opr) {
//删除缓存
cacheMap.entrySet().stream().filter(entry -> entry.getValue().nonNull()).forEach(entry -> {
String k = formatKey(entry.getKey(),entry.getValue().getHashKey().replace(), entity);
cacheHelper.hashDel(k, entry.getValue().getKey());
});
}
if(BaseOperationEnum.INSERT == opr || BaseOperationEnum.UPDATE == opr){
//刷新缓存过滤掉HashKeyValue中key为null或者value为null的情况
cacheMap.entrySet().stream().filter(entry -> entry.getValue().nonNull()).forEach(entry -> {
String k = formatKey(entry.getKey(),entry.getValue().getHashKey().replace(), entity);
cacheHelper.hashSet(k, entry.getValue().getKey(), entry.getValue().getValue());
});
}
if(BaseOperationEnum.DELETE_INSERT == opr){
//刷新缓存过滤掉HashKeyValue中key为null或者value为null的情况
cacheMap.entrySet().stream().filter(entry -> entry.getValue().nonNull()).forEach(entry -> {
String k = formatKey(entry.getKey(),entry.getValue().getHashKey().replace(), entity);
cacheHelper.hashDel(k, entry.getValue().getKey());
cacheHelper.hashSet(k, entry.getValue().getKey(), entry.getValue().getValue());
});
}
if(BaseOperationEnum.MERGE == opr){
//刷新缓存不过滤HashKeyValue中key为null或者value为null的情况
cacheMap.entrySet().stream().forEach(entry -> {
String k = formatKey(entry.getKey(),entry.getValue().getHashKey().replace(), entity);
//cacheHelper.hashDel(k, entry.getValue().getKey());
cacheHelper.hashSet(k, entry.getValue().getKey(), entry.getValue().getValue());
});
}
}
/***
* 批量数据同步缓存
* @param entities
* @param opr
*/
@SuppressWarnings("unchecked")
default <T> void refreshCacheFieldsBatch(List<T> entities, BaseOperationEnum opr){
if(CollectionUtils.isEmpty(entities)){
return;
}
T entity = entities.get(0);
Field[] declaredFields = ReflectionUtils.getAllFieldsArr(entity);
//缓存操作类
CacheHelper cacheHelper = ApplicationContextUtils.getBean(CacheHelper.class);
Map<String,Set<HashKeyValue>> cacheMap = new HashMap<>();
for(T t : entities) {
// 先遍历一遍 hash-key
String namePrefix = "";
String k = "";
for (Field field : declaredFields) {
field.setAccessible(true);
Object value;
if (field.isAnnotationPresent(HashKey.class)) {
try {
value = field.get(t);
} catch (IllegalAccessException ex) {
continue;
}
if (value == null) {
continue;
}
HashKey hashKey = field.getAnnotation(HashKey.class);
String key = hashKey.key();
namePrefix = formatKey(key, hashKey.replace(), t);
k = value+"";
if (cacheMap.containsKey(key)) {
Set<HashKeyValue> list = cacheMap.get(key);
HashKeyValue r = new HashKeyValue();
r.setKey(String.valueOf(value));
r.setHashKey(hashKey);
r.setName(namePrefix);
list.add(r);
} else {
HashKeyValue kv = new HashKeyValue();
kv.setKey(String.valueOf(value));
kv.setHashKey(hashKey);
kv.setName(namePrefix);
Set<HashKeyValue> list = new HashSet<>();
list.add(kv);
cacheMap.put(key, list);
}
}
}
for (Field field : declaredFields) {
field.setAccessible(true);
Object value;
if (field.isAnnotationPresent(HashValue.class)) {
try {
value = field.get(t);
} catch (IllegalAccessException e) {
continue;
}
if (value == null) {
continue;
}
HashValue hashValue = field.getAnnotation(HashValue.class);
String key = hashValue.key();
if (cacheMap.containsKey(key)) {
Set<HashKeyValue> list = cacheMap.get(key);
final String k1 = k;
final String ns = namePrefix;
list.stream().filter(f->f.getKey().equals(k1) && f.getName().equals(ns))
.findFirst().get().setValue(String.valueOf(value));
}
}
}
}
if (BaseOperationEnum.DELETE == opr || BaseOperationEnum.DELETE_BATCH == opr) {
cacheMap.entrySet().stream().filter(entry -> !CollectionUtils.isEmpty(entry.getValue())).forEach(entry -> {
Map<String,List<HashKeyValue>> map = entry.getValue().stream().collect(Collectors.groupingBy(t->t.getName()));
map.entrySet().forEach(kv->{
cacheHelper.hashBatchDel(kv.getKey(),kv.getValue().stream().map(HashKeyValue::getKey).collect(Collectors.toSet()));
});
});
}
if(BaseOperationEnum.INSERT == opr || BaseOperationEnum.UPDATE == opr){
cacheMap.entrySet().stream().filter(entry -> !CollectionUtils.isEmpty(entry.getValue())).forEach(entry -> {
Map<String,List<HashKeyValue>> map = entry.getValue().stream().collect(Collectors.groupingBy(t->t.getName()));
map.entrySet().forEach(kv->{
cacheHelper.hashSet(kv.getKey(),kv.getValue().stream()
.collect(Collectors.toMap(HashKeyValue::getKey,HashKeyValue::getValue,(v1,v2)->v2)));
});
});
}
if(BaseOperationEnum.DELETE_INSERT == opr){
cacheMap.entrySet().stream().filter(entry -> !CollectionUtils.isEmpty(entry.getValue())).forEach(entry -> {
Map<String,List<HashKeyValue>> map = entry.getValue().stream().collect(Collectors.groupingBy(t->t.getName()));
map.entrySet().forEach(kv->{
cacheHelper.hashBatchDel(kv.getKey(),kv.getValue().stream().map(HashKeyValue::getKey).collect(Collectors.toSet()));
cacheHelper.hashSet(kv.getKey(),kv.getValue().stream()
.collect(Collectors.toMap(t->t.getKey(),t->t.getValue(),(v1,v2)->v2)));
});
});
}
if(BaseOperationEnum.MERGE == opr){
cacheMap.entrySet().stream()/*.filter(entry -> !CollectionUtils.isEmpty(entry.getValue()))*/.forEach(entry -> {
Map<String,List<HashKeyValue>> map = entry.getValue().stream().collect(Collectors.groupingBy(t->t.getName()));
map.entrySet().forEach(kv->{
cacheHelper.hashSet(kv.getKey(),kv.getValue().stream()
.filter(e->!StringUtils.isEmpty(e.getKey()))
.collect(Collectors.toMap(t->t.getKey(),
t->Optional.ofNullable(t.getValue()).orElse(""),(v1,v2)->v2)));
});
});
}
}
}

View File

@@ -0,0 +1,539 @@
package top.lidee.taie.cache;
import top.lidee.taie.constant.LideeConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.ConvertingCursor;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @author lr
* @since 2021-06-22
*/
public class RedisCacheHelper implements CacheHelper {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 获取指定key的String类型缓存
*
* @param key
* @return
*/
@Override
public String stringGet(String key) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return "";
}
BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(regKey);
return operations.get();
}
@Override
public Map<String,String> stringMultiGet(List<String> keys) {
if(CollectionUtils.isEmpty(keys)){
return Collections.emptyMap();
}
List<String> ret = stringRedisTemplate.opsForValue().multiGet(keys);
if(!CollectionUtils.isEmpty(ret)){
Map<String,String> map = new HashMap<>();
for(int i=0;i<keys.size();i++){
if(Objects.isNull(ret.get(i))) continue;
map.put(keys.get(i),ret.get(i));
}
return map;
}
return Collections.emptyMap();
}
/**
* 获取指定key的String类型缓存
*
* @param key
* @return
*/
@Override
public Boolean setIfAbsent(String key, String value) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return false;
}
BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(regKey);
return operations.setIfAbsent(value);
}
/**
* 增加1
*
* @param key
* @return
*/
@Override
public Long increment(String key) {
String regKey = regKey(key);
BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(regKey);
return operations.increment();
}
/**
* 设置失效时间
*
* @param key
* @param timeUnit
* @param timeout
*/
@Override
public void expire(String key, TimeUnit timeUnit, Long timeout) {
String regKey = regKey(key);
stringRedisTemplate.expire(regKey, timeout, timeUnit);
}
/**
* 增加1
*
* @param key
* @return
*/
@Override
public Long increment(String key, Long step) {
BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(regKey(key));
return operations.increment(step);
}
/**
* 是否存在指定KEY
*
* @param key
* @return
*/
@Override
public boolean exist(String key) {
return stringRedisTemplate.hasKey(regKey(key));
}
/**
* 模糊匹配,
*
* @param pattern
* @return
*/
@Override
public Set<String> keys(String pattern) {
// 危险操作,线上可能会禁用该指令
// return stringRedisTemplate.keys(pattern);
ScanOptions options = ScanOptions.scanOptions().count(1000).match(pattern).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) stringRedisTemplate.getKeySerializer();
Set<String> result = new HashSet<>();
try (Cursor cursor = stringRedisTemplate.executeWithStickyConnection(
redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize))) {
while (cursor.hasNext()) {
result.add(cursor.next().toString());
}
} catch (Exception ex) {
}
return result;
}
/**
* 设置指定key的String类型缓存
*
* @param key
* @param value 缓存值
* @return
*/
@Override
public void stringSet(String key, String value) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return;
}
BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(regKey);
operations.set(value);
}
/**
* 设置指定key的String类型缓存包含过期时间
*
* @param key
* @param value
* @param time
* @param timeUnit 时间单位
*/
@Override
public void stringSetExpire(String key, String value, long time, TimeUnit timeUnit) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return;
}
BoundValueOperations<String, String> operations = stringRedisTemplate.boundValueOps(regKey);
operations.set(value, time, timeUnit);
}
/**
* 设置指定key的String类型缓存包含过期时间
*
* @param key
* @param value
* @param seconds
*/
@Override
public void stringSetExpire(String key, String value, long seconds) {
stringSetExpire(regKey(key), value, seconds, TimeUnit.SECONDS);
}
/**
* 获取指定key的hash缓存
*
* @param key
* @return
*/
@Override
public Map<String, String> hashGet(String key) {
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey(key));
return operations.entries();
}
@Override
public List<String> hashMultiGet(String key, Collection<String> keys, boolean includeDisabled) {
if (Objects.isNull(key) || CollectionUtils.isEmpty(keys)) {
return Arrays.asList("");
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey(key));
List<String> itemKeys = keys.stream().map(t -> regKey(t)).collect(Collectors.toList());
List<String> list = operations.multiGet(itemKeys);
for (int i = 0; i < list.size(); i++) {
list.set(i, Optional.ofNullable(list.get(i)).orElse(""));
}
if (includeDisabled) {
//list = list.stream().filter(i->StringUtils.isEmpty(i)).collect(Collectors.toList());
Map<Integer, String> nullKeys = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
if (StringUtils.isEmpty(list.get(i))) {
nullKeys.put(i, itemKeys.get(i));
}
}
if (nullKeys.isEmpty()) {
return list;
}
// 查询禁用的数据
BoundHashOperations<String, String, String> d =
stringRedisTemplate.boundHashOps(regKey(key).concat(getDisabledKey()));
List<String> nullItemKeys = new ArrayList<>(nullKeys.values());
List<String> disabledVals = d.multiGet(nullItemKeys);
if (!CollectionUtils.isEmpty(disabledVals)) {
Map<String, String> dis = new HashMap<>();
for (int i = 0; i < disabledVals.size(); i++) {
dis.put(nullItemKeys.get(i), Optional.ofNullable(disabledVals.get(i)).orElse(""));
}
// 替换为禁用的数据
for (Entry<Integer, String> src : nullKeys.entrySet()) {
list.set(src.getKey(), dis.get(src.getValue()));
}
}
}
return list;
}
/**
* 获取指定key的hash中对应的值
*
* @param key
* @param hashKey
* @return
*/
@Override
public String hashGetString(String key, String hashKey) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return "";
}
String regHashKey = regKey(hashKey);
if (StringUtils.isBlank(regHashKey)) {
return "";
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
if (hashKey.contains(LideeConstant.SPLIT)) {
String[] split = hashKey.split(LideeConstant.SPLIT);
String reduce = Arrays.stream(split).reduce("", (all, item) -> {
if (StringUtils.isBlank(all)) {
all = operations.get(item);
} else {
all = all + "," + operations.get(item);
}
return all;
});
return reduce;
}
return operations.entries().get(regHashKey);
}
/**
* 删除Hash中指定key的值
*
* @param key
* @param hashKey
* @return
*/
@Override
public void hashDel(String key, String hashKey) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return;
}
String regHashKey = regKey(hashKey);
if (StringUtils.isBlank(regHashKey)) {
return;
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
operations.delete(regHashKey);
}
/**
* 删除Hash中指定key的值
*
* @param key
* @param hashKeys
* @return
*/
@Override
public void hashBatchDel(String key, Set<String> hashKeys, boolean toDisable) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey) || CollectionUtils.isEmpty(hashKeys)) {
return;
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
if (toDisable) {
BoundHashOperations<String, String, String> disableOpt = stringRedisTemplate.boundHashOps(regKey.concat(getDisabledKey()));
List<String> keys = hashKeys.stream().collect(Collectors.toList());
List<String> dels = operations.multiGet(hashKeys);
for (int i = 0; i < keys.size(); i++) {
disableOpt.put(keys.get(i), Optional.ofNullable(dels.get(i)).orElse(""));
}
}
operations.delete(hashKeys.toArray(new String[0]));
}
/**
* 判断指定key的hash中包含指定hashKey
*
* @param key
* @param hashKey
* @return
*/
@Override
public boolean hashExist(String key, String hashKey) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return false;
}
String regHashKey = regKey(hashKey);
if (StringUtils.isBlank(regHashKey)) {
return false;
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
return operations.hasKey(regHashKey);
}
/**
* 判断指定key的hash中包含指定hashKeys中任何一个
*
* @param key
* @param hashKeys
* @return
*/
@Override
public boolean hashAnyExist(String key, String[] hashKeys) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return false;
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
for (String hashKey : hashKeys) {
if (operations.hasKey(regKey(hashKey))) {
return true;
}
}
return false;
}
/**
* 设置指定key的hash缓存
*
* @param key
* @param hashKey
* @param hashValue
* @return
*/
@Override
public void hashSet(String key, String hashKey, String hashValue) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey) || StringUtils.isBlank(hashKey)) {
return;
}
String regHashKey = regKey(hashKey);
if (StringUtils.isBlank(regHashKey) || StringUtils.isBlank(hashValue)) {
return;
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
operations.put(regHashKey, hashValue);
}
/**
* 设置指定key的hash缓存
*
* @param hash
* @return
*/
@Override
public void hashSet(String key, Map<String, String> hash) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return;
}
if (CollectionUtils.isEmpty(hash)) {
return;
}
BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(regKey);
operations.putAll(hash);
}
@Override
public void hashMultiSet(Map<String, String> map) {
if(Objects.isNull(map) || map.isEmpty()){
return;
}
stringRedisTemplate.opsForValue().multiSet(map);
}
/**
* 删除指定key
*
* @param key
* @return
*/
@Override
public boolean delete(String key) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return false;
}
return stringRedisTemplate.delete(regKey);
}
/**
* 删除指定key
*
* @param keys
* @return
*/
@Override
public boolean delete(List<String> keys) {
if (CollectionUtils.isEmpty(keys)) {
return false;
}
Long count = stringRedisTemplate.delete(keys.stream().map(t -> regKey(t)).collect(Collectors.toList()));
return count > 0;
}
/**
* 向集合中添加
*
* @param key
* @param values
* @return
*/
@Override
public Long setAdd(String key, String[] values) {
return setAdd(regKey(key), values, false);
}
/**
* 向集合中添加
*
* @param key
* @param values
* @param clear 是否清空旧数据
* @return
*/
@Override
public Long setAdd(String key, String[] values, boolean clear) {
String regKey = regKey(key);
if (clear) {
stringRedisTemplate.delete(regKey);
}
if (values != null && values.length == 0) {
return 0L;
}
BoundSetOperations<String, String> setOperations = stringRedisTemplate.boundSetOps(regKey);
return setOperations.add(values);
}
/**
* 返回对应key的集合
*
* @param key
* @return
*/
@Override
public Set<String> setMembers(String key) {
BoundSetOperations<String, String> setOperations = stringRedisTemplate.boundSetOps(regKey(key));
return setOperations.members();
}
/**
* 判断集合中是否有对应的value
*
* @param key
* @param value
* @return
*/
@Override
public Boolean setExist(String key, String value) {
String regKey = regKey(key);
if (StringUtils.isBlank(regKey)) {
return false;
}
BoundSetOperations<String, String> setOperations = stringRedisTemplate.boundSetOps(regKey);
return setOperations.isMember(value);
}
}

View File

@@ -1,6 +1,12 @@
package top.lidee.taie.http;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import top.lidee.taie.http.ssl.SslSocketClient;
import okhttp3.*;
@@ -135,4 +141,40 @@ public class HttpClientUtils {
Request request = new Request.Builder().url(url).headers(headers).delete().build();
httpClient.newCall(request).enqueue(callback);
}
public static String getPost(String url,String Token)
{
try {
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建POST请求
HttpPost httpPost = new HttpPost(url);
// 设置请求体
StringEntity params = new StringEntity("refreshToken="+Token);
httpPost.setEntity(params);
httpPost.setHeader("Authorization",Token);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 获取响应状态码
System.out.println(response.getStatusLine().getStatusCode());
// 获取响应体内容
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
return result;
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}

View File

@@ -8,7 +8,7 @@
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.14</version>
<!--<version>2.3.5.RELEASE</version>-->
<relativePath/> <!-- lookup parent from repository -->
<relativePath/>
</parent>
<groupId>top.lidee.taie</groupId>
<artifactId>lidee-common</artifactId>

View File

@@ -0,0 +1,150 @@
package top.lidee.taie.business.cache;
import top.lidee.taie.cache.CacheHelper;
import com.google.common.collect.Maps;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ReportCacheHelper implements CacheHelper, ApplicationContextAware {
@Autowired
private Cache cache;
@Override
public String stringGet(String key) {
Cache.ValueWrapper valueWrapper = cache.get(key);
if (valueWrapper != null) {
return (String) valueWrapper.get();
}
return CacheHelper.super.stringGet(key);
}
@Override
public Boolean setIfAbsent(String key, String value) {
cache.putIfAbsent(key, value);
return true;
}
@Override
public boolean exist(String key) {
String cacheHoldTime = stringGet(key + "_HoldTime");
if (cacheHoldTime != null && Long.parseLong(cacheHoldTime) > 0) {
if (Long.parseLong(cacheHoldTime) < System.currentTimeMillis()) {
delete(key + "_HoldTime");
delete(key);
return false;
}
}
return cache.get(key) != null;
}
@Override
public void stringSet(String key, String value) {
cache.put(key, value);
}
@Override
public String regKey(String key) {
return CacheHelper.super.regKey(key);
}
@Override
public void stringSetExpire(String key, String value, long seconds) {
stringSet(key, value);
if (seconds > 0) {
//缓存失效时间
stringSet(key + "_HoldTime", String.valueOf(System.currentTimeMillis() + seconds * 1000));
}
}
@Override
public Map<String, String> hashGet(String key) {
Cache.ValueWrapper t = cache.get(key);
if (t != null) {
return (Map<String, String>) t.get();
}
return Maps.newHashMap();
}
@Override
public String hashGetString(String key, String hashKey) {
Map<String, String> stringStringMap = hashGet(key);
return stringStringMap.get(hashKey);
}
@Override
public void hashDel(String key, String hashKey) {
Map<String, String> stringStringMap = hashGet(key);
stringStringMap.remove(hashKey);
}
@Override
public void hashBatchDel(String key, Set<String> hashKeys) {
Map<String, String> stringStringMap = hashGet(key);
hashKeys.forEach(stringStringMap::remove);
}
@Override
public boolean hashExist(String key, String hashKey) {
if (exist(key)) {
Map<String, String> map = hashGet(key);
return map.containsKey(hashKey);
}
return false;
}
@Override
public boolean hashAnyExist(String key, String[] hashKeys) {
return CacheHelper.super.hashAnyExist(key, hashKeys);
}
@Override
public void hashSet(String key, String hashKey, String hashValue) {
Map<String, String> map;
if (exist(key)) {
map = hashGet(key);
} else {
map = new HashMap<>();
}
map.put(hashKey, hashValue);
hashSet(key, map);
}
@Override
public void hashSet(String key, Map<String, String> hash) {
cache.put(key, hash);
}
@Override
public boolean delete(String key) {
if (exist(key)) {
cache.evict(key);
}
return true;
}
@Override
public boolean delete(List<String> keys) {
keys.forEach(this::delete);
return true;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
/*基于内存的本地缓存*/
cache = (Cache) applicationContext.getBean("ehCacheCache");
}
}

View File

@@ -21,6 +21,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.io.IOException;
import java.util.Map;
/**
@@ -98,6 +99,21 @@ public class AccessUserController extends LideeBaseController<AccessUserParam, A
return responseSuccessWithData(accessUserService.login(dto));
}
@PostMapping({"/logincas"})
public ResponseBean logincas(@RequestBody @Validated LideeUserDto dto) throws IOException {
return responseSuccessWithData(accessUserService.logincas(dto));
}
@PostMapping({"/outlogcas"})
public ResponseBean outlogcas(@RequestBody @Validated LideeUserDto dto){
Boolean data =accessUserService.outlogincas(dto);
return responseSuccessWithData(data);
}
/**
* 修改自己的密码
* @param dto

View File

@@ -8,6 +8,7 @@ import top.lidee.taie.business.modules.accessuser.dao.entity.AccessUser;
import top.lidee.taie.business.modules.accessuser.controller.param.AccessUserParam;
import top.lidee.taie.curd.service.LideeBaseService;
import java.io.IOException;
import java.util.Map;
/**
@@ -43,6 +44,11 @@ public interface AccessUserService extends LideeBaseService<AccessUserParam, Acc
*/
LideeUserDto login(LideeUserDto lideeUserDto);
LideeUserDto logincas(LideeUserDto lideeUserDto) throws IOException;
Boolean outlogincas(LideeUserDto lideeUserDto);
/**
* 修改密码
* @param dto

View File

@@ -10,6 +10,7 @@ import top.lidee.taie.exception.BusinessException;
import top.lidee.taie.exception.BusinessExceptionBuilder;
import top.lidee.taie.curd.mapper.LideeBaseMapper;
import top.lidee.taie.holder.UserContentHolder;
import top.lidee.taie.http.HttpClientUtils;
import top.lidee.taie.utils.LideeUtils;
import top.lidee.taie.utils.JwtBean;
import top.lidee.taie.business.code.ResponseCode;
@@ -34,6 +35,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@@ -71,6 +73,14 @@ public class AccessUserServiceImpl implements AccessUserService {
@Autowired
private CacheHelper cacheHelper;
@Value("${cas.loginurl:}")
private String casLoginUrl;
@Value("${cas.outlogouturl:}")
private String casoutlogouturl;
@Override
public Map getRoleTree(String loginName, String operator) {
Map<String, Object> result = new HashMap<String, Object>();
@@ -146,7 +156,7 @@ public class AccessUserServiceImpl implements AccessUserService {
throw BusinessExceptionBuilder.build("用户不存在");
}
//默认密码
accessUser.setPassword(MD5Util.encrypt(MD5Util.encrypt(defaultPassword.concat("lidee@123"))));
accessUser.setPassword(MD5Util.encrypt(MD5Util.encrypt(defaultPassword.concat("Lidee@654!"))));
accessUserMapper.updateById(accessUser);
return true;
}
@@ -217,6 +227,98 @@ public class AccessUserServiceImpl implements AccessUserService {
return lduser;
}
@Override
public LideeUserDto logincas(LideeUserDto lideeUserDto) {
String loginName="";
String url = casLoginUrl+"?refreshToken="+ lideeUserDto.getLoginName();
String response = HttpClientUtils.getPost(url, lideeUserDto.getLoginName());
JSONObject jsonObject = null;
jsonObject= JSONObject.parseObject(response);
if(Integer.parseInt(jsonObject.getString("code"))==0)
{
loginName=jsonObject.getJSONObject("data").getString("username");
}
String password ="Lidee@654!";
// 1.判断用户是否存在
LambdaQueryWrapper<AccessUser> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUser::getLoginName, loginName);
AccessUser accessUser = accessUserMapper.selectOne(wrapper);
if (null == accessUser) {
throw BusinessExceptionBuilder.build(ResponseCode.LOGIN_ERROR);
}
// 2.密码错误
String sss=MD5Util.encrypt(password);
// if (!accessUser.getPassword().equals(MD5Util.encrypt(password))) {
// throw BusinessExceptionBuilder.build(ResponseCode.USER_PASSWORD_ERROR);
// }
// 3.如果该用户登录未过期,这里允许一个用户在多个终端登录
String tokenKey = String.format(BusinessConstant.LIDEE_SECURITY_LOGIN_TOKEN, loginName);
String token = "";
LideeUserDto lduser = new LideeUserDto();
if (cacheHelper.exist(tokenKey)) {
token = cacheHelper.stringGet(tokenKey);
} else {
// 生成用户token
String uuid = LideeUtils.UUID();
token = jwtBean.createToken(loginName, uuid, 0, LideeConstant.TENANT_CODE);
cacheHelper.stringSetExpire(tokenKey, token, 3600);
}
// 4.读取用户最新人权限主信息
String userKey = String.format(BusinessConstant.LIDEE_SECURITY_LOGIN_USER, loginName);
//为了兼容底层其他数据库不再写自定义sql
// List<String> authorities = accessUserMapper.queryAuthoritiesByLoginName(loginName);
//当前用户的roleCode集合
LambdaQueryWrapper<AccessUserRole> accessUserWrapper = Wrappers.lambdaQuery();
accessUserWrapper.select(AccessUserRole::getRoleCode);
accessUserWrapper.eq(AccessUserRole::getLoginName, loginName);
List<AccessUserRole> accessUserRoles = accessUserRoleMapper.selectList(accessUserWrapper);
Set<String> roleCodeSet = accessUserRoles.stream().map(AccessUserRole::getRoleCode).collect(Collectors.toSet());
if (roleCodeSet.size() < 1) {
lduser.setAuthorities(new ArrayList<>());
}else {
LambdaQueryWrapper<AccessRoleAuthority> accessRoleAuthorityWrapper = Wrappers.lambdaQuery();
accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction);
accessRoleAuthorityWrapper.in(AccessRoleAuthority::getRoleCode, roleCodeSet);
List<AccessRoleAuthority> accessRoleAuthorities = accessRoleAuthorityMapper.selectList(accessRoleAuthorityWrapper);
List<String> authorities = accessRoleAuthorities.stream()
.map(accessRoleAuthority -> accessRoleAuthority.getTarget().concat(":").concat(accessRoleAuthority.getAction())).distinct().collect(Collectors.toList());
lduser.setAuthorities(authorities);
}
lduser.setLoginName(loginName);
lduser.setRealName(accessUser.getRealName());
lduser.setToken(token);
String ldUserStr = JSONObject.toJSONString(lduser);
cacheHelper.stringSetExpire(userKey, ldUserStr, 3600);
cacheHelper.stringSetExpire(loginName+"_cas", lideeUserDto.getLoginName(), 360000);
// String ss= cacheHelper.stringGet(loginName+"_cas");
return lduser;
}
@Override
public Boolean outlogincas(LideeUserDto lideeUserDto) {
String token= cacheHelper.stringGet(lideeUserDto.getLoginName()+"_cas");
String url = casoutlogouturl+"?refreshToken="+ token;
String response = HttpClientUtils.getPost(url, token);
return true;
}
/**
* 修改密码
*
@@ -263,7 +365,7 @@ public class AccessUserServiceImpl implements AccessUserService {
switch (operationEnum) {
case INSERT:
//lidee是为了和前端加密保持一致
entity.setPassword(MD5Util.encrypt(MD5Util.encrypt(defaultPassword.concat("lidee"))));
entity.setPassword(MD5Util.encrypt(MD5Util.encrypt(defaultPassword.concat("Lidee@654!"))));
break;
case UPDATE:
//更新用户不允许修改密码
@@ -275,4 +377,7 @@ public class AccessUserServiceImpl implements AccessUserService {
}
}
}

View File

@@ -34,8 +34,8 @@ spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/lidee_report?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
# password: gryy@8888
# password: root
password: gryy@8888
# url: jdbc:mysql://127.0.0.1:3306/lidee_report?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
# username: root
# password: Lidee@654!
@@ -144,4 +144,9 @@ customer:
user:
##新增用户默认密码
default:
password: 123456
password: Lidee@654!
cas:
# loginurl: http://127.0.0.1:48080/admin-api/system/auth/user-info
# outlogouturl: http://127.0.0.1:48080/admin-api/system/auth/logout-client
loginurl: http://192.168.1.241/admin-api/system/auth/user-info
outlogouturl: http://192.168.1.241/admin-api/system/auth/logout-client