mirror of
https://gitee.com/orangeform/orange-admin.git
synced 2026-01-18 02:56:30 +08:00
commit:权限模块新增分配详情功能
This commit is contained in:
@@ -3,10 +3,9 @@ package com.orange.demo.common.core.base.client;
|
||||
import com.orange.demo.common.core.object.MyAggregationParam;
|
||||
import com.orange.demo.common.core.object.MyQueryParam;
|
||||
import com.orange.demo.common.core.object.ResponseResult;
|
||||
import com.orange.demo.common.core.object.Tuple2;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 远程调用接口。
|
||||
@@ -52,6 +51,26 @@ public interface BaseClient<D, K> {
|
||||
*/
|
||||
ResponseResult<Boolean> existId(K id);
|
||||
|
||||
/**
|
||||
* 删除主键Id关联的对象。
|
||||
*
|
||||
* @param id 主键Id。
|
||||
* @return 应答结果对象。
|
||||
*/
|
||||
default ResponseResult<Void> delete(K id) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除符合过滤条件的数据。
|
||||
*
|
||||
* @param filter 过滤对象。
|
||||
* @return 应答结果对象,包含删除数量。
|
||||
*/
|
||||
default ResponseResult<Integer> deleteBy(D filter) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取远程主对象中符合查询条件的数据列表。
|
||||
* 缺省实现是因为字典类型的远程调用客户端中,不需要实现该方法,因此尽早抛出异常,用户可自行修改。
|
||||
@@ -106,4 +125,14 @@ public interface BaseClient<D, K> {
|
||||
default ResponseResult<List<Map<String, Object>>> aggregateBy(MyAggregationParam aggregationParam) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据主键Id及其列表数据(not in list)进行过滤,返回给定的数据。返回的对象数据中,仅仅包含实体对象自己的数据,以及配置的字典关联数据。
|
||||
*
|
||||
* @param queryParam 查询参数。
|
||||
* @return 应答结果对象,包含数据列表,以及整个符合条件的数据总量(分页之前)。
|
||||
*/
|
||||
default ResponseResult<Tuple2<List<D>, K>> listByNotInList(MyQueryParam queryParam) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.orange.demo.common.core.base.client;
|
||||
|
||||
import com.orange.demo.common.core.constant.ErrorCodeEnum;
|
||||
import com.orange.demo.common.core.object.MyAggregationParam;
|
||||
import com.orange.demo.common.core.object.MyQueryParam;
|
||||
import com.orange.demo.common.core.object.ResponseResult;
|
||||
import com.orange.demo.common.core.object.Tuple2;
|
||||
import feign.hystrix.FallbackFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* FeignClient 熔断降级处理对象。
|
||||
*
|
||||
* @param <D> 实体对象类型。
|
||||
* @param <K> 主键类型。
|
||||
* @param <T> Feign客户端对象类型。
|
||||
* @author Jerry
|
||||
* @date 2020-08-08
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class BaseFallbackFactory<D, K, T extends BaseClient<D, K>>
|
||||
implements FallbackFactory<T>, BaseClient<D, K> {
|
||||
|
||||
@Override
|
||||
public ResponseResult<List<D>> listByIds(Set<K> idSet, Boolean withDict) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<D> getById(K id, Boolean withDict) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<Boolean> existIds(Set<K> idSet) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<Boolean> existId(K id) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<Void> delete(K id) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<Integer> deleteBy(D filter) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<List<D>> listBy(MyQueryParam queryParam) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<D> getBy(MyQueryParam queryParam) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<List<Map<String, Object>>> listMapBy(MyQueryParam queryParam) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<Integer> countBy(MyQueryParam queryParam) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<List<Map<String, Object>>> aggregateBy(MyAggregationParam aggregationParam) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseResult<Tuple2<List<D>, K>> listByNotInList(MyQueryParam queryParam) {
|
||||
return ResponseResult.error(ErrorCodeEnum.RPC_DATA_ACCESS_FAILED);
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,18 @@ public abstract class BaseController<M, D, K> {
|
||||
!MyCommonUtil.existBlankArgument(id) && service().getById(id) != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除符合过滤条件的数据。
|
||||
*
|
||||
* @param filter 过滤对象。
|
||||
* @param modelMapper 对象映射函数对象。如果为空,则使用MyModelUtil中的缺省转换函数。
|
||||
* @return 删除数量。
|
||||
*/
|
||||
public ResponseResult<Integer> baseDeleteBy(
|
||||
D filter, BaseModelMapper<D, M> modelMapper) throws Exception {
|
||||
return ResponseResult.success(service().removeBy(convertToModel(filter, modelMapper)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义过滤条件、显示字段和排序字段的单表查询。主要用于微服务间远程过程调用。
|
||||
* NOTE: 和baseListMapBy方法的差别只是返回的数据形式不同,该接口以对象列表的形式返回数据。
|
||||
@@ -246,7 +258,7 @@ public abstract class BaseController<M, D, K> {
|
||||
// 完成一些共同性规则的验证。
|
||||
VerifyAggregationInfo verifyInfo = this.verifyAndParseAggregationParam(param);
|
||||
if (!verifyInfo.isSuccess) {
|
||||
return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATAED_FAILED, verifyInfo.errorMsg);
|
||||
return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, verifyInfo.errorMsg);
|
||||
}
|
||||
// 构建SelectList
|
||||
StringBuilder selectList = new StringBuilder(64);
|
||||
@@ -353,6 +365,24 @@ public abstract class BaseController<M, D, K> {
|
||||
return resultDto;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将Dto对象转换为Model实体对象。
|
||||
* 如果Model存在该实体的ModelMapper,就用该ModelMapper转换,否则使用缺省的基于字段反射的copy。
|
||||
*
|
||||
* @param dto Dto对象。
|
||||
* @param modelMapper 从实体对象到Dto对象的映射对象。
|
||||
* @return 转换后的Dto域对象。
|
||||
*/
|
||||
private M convertToModel(D dto, BaseModelMapper<D, M> modelMapper) {
|
||||
M result;
|
||||
if (modelMapper != null) {
|
||||
result = modelMapper.toModel(dto);
|
||||
} else {
|
||||
result = MyModelUtil.copyTo(dto, modelClass);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private VerifyAggregationInfo verifyAndParseAggregationParam(MyAggregationParam param) {
|
||||
VerifyAggregationInfo verifyInfo = new VerifyAggregationInfo();
|
||||
if (!AggregationKind.isValid(param.getAggregationKind())) {
|
||||
|
||||
@@ -191,6 +191,29 @@ public abstract class BaseService<M, D, K> {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据过滤条件删除数据。
|
||||
*
|
||||
* @param filter 过滤对象。
|
||||
* @return 删除数量。
|
||||
*/
|
||||
public Integer removeBy(M filter) throws Exception {
|
||||
if (deletedFlagField == null) {
|
||||
return mapper().delete(filter);
|
||||
}
|
||||
Example e = new Example(modelClass);
|
||||
Example.Criteria c = e.createCriteria();
|
||||
Field[] fields = ReflectUtil.getFields(modelClass);
|
||||
for (Field field : fields) {
|
||||
if (field.getAnnotation(Transient.class) == null) {
|
||||
this.assembleCriteriaByFilter(filter, field, c);
|
||||
}
|
||||
}
|
||||
M deletedObject = modelClass.newInstance();
|
||||
this.setDeletedFlagMethod.invoke(deletedObject, GlobalDeletedFlag.DELETED);
|
||||
return mapper().updateByExampleSelective(deletedObject, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断主键Id关联的数据是否存在。
|
||||
*
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
package com.orange.demo.common.core.cache;
|
||||
|
||||
import com.orange.demo.common.core.exception.MapCacheAccessException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
@@ -11,6 +18,7 @@ import java.util.function.Function;
|
||||
* @author Jerry
|
||||
* @date 2020-08-08
|
||||
*/
|
||||
@Slf4j
|
||||
public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
|
||||
/**
|
||||
@@ -21,6 +29,14 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* 获取字典主键数据的函数对象。
|
||||
*/
|
||||
protected Function<V, K> idGetter;
|
||||
/**
|
||||
* 由于大部分场景是读取操作,所以使用读写锁提高并发的伸缩性。
|
||||
*/
|
||||
protected ReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
/**
|
||||
* 超时时长。单位毫秒。
|
||||
*/
|
||||
protected static final long TIMEOUT = 2000L;
|
||||
|
||||
/**
|
||||
* 当前对象的构造器函数。
|
||||
@@ -52,10 +68,27 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @return 全部字段数据列表。
|
||||
*/
|
||||
@Override
|
||||
public synchronized List<V> getAll() {
|
||||
public List<V> getAll() {
|
||||
List<V> resultList = new LinkedList<>();
|
||||
for (Map.Entry<K, V> entry : dataMap.entrySet()) {
|
||||
resultList.add(entry.getValue());
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
for (Map.Entry<K, V> entry : dataMap.entrySet()) {
|
||||
resultList.add(entry.getValue());
|
||||
}
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
@@ -67,14 +100,31 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @return 对象列表。
|
||||
*/
|
||||
@Override
|
||||
public synchronized List<V> getInList(Set<K> keys) {
|
||||
public List<V> getInList(Set<K> keys) {
|
||||
List<V> resultList = new LinkedList<>();
|
||||
keys.forEach(key -> {
|
||||
V object = dataMap.get(key);
|
||||
if (object != null) {
|
||||
resultList.add(object);
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
keys.forEach(key -> {
|
||||
V object = dataMap.get(key);
|
||||
if (object != null) {
|
||||
resultList.add(object);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
|
||||
@@ -84,14 +134,31 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @param dataList 待缓存的数据列表。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void putAll(List<V> dataList) {
|
||||
public void putAll(List<V> dataList) {
|
||||
if (dataList == null) {
|
||||
return;
|
||||
}
|
||||
dataList.forEach(dataObj -> {
|
||||
K id = idGetter.apply(dataObj);
|
||||
dataMap.put(id, dataObj);
|
||||
});
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
dataList.forEach(dataObj -> {
|
||||
K id = idGetter.apply(dataObj);
|
||||
dataMap.put(id, dataObj);
|
||||
});
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,23 +168,65 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @param force true则强制刷新,如果false,当缓存中存在数据时不刷新。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void reload(List<V> dataList, boolean force) {
|
||||
public void reload(List<V> dataList, boolean force) {
|
||||
if (!force && this.getCount() > 0) {
|
||||
return;
|
||||
}
|
||||
this.invalidateAll();
|
||||
this.putAll(dataList);
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
dataMap.clear();
|
||||
dataList.forEach(dataObj -> {
|
||||
K id = idGetter.apply(dataObj);
|
||||
dataMap.put(id, dataObj);
|
||||
});
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓存中获取指定的数据。
|
||||
*
|
||||
* @param 数据的key。
|
||||
* @param id 数据的key。
|
||||
* @return 获取到的数据,如果没有返回null。
|
||||
*/
|
||||
@Override
|
||||
public synchronized V get(K id) {
|
||||
return id == null ? null : dataMap.get(id);
|
||||
public V get(K id) {
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
V data;
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
data = dataMap.get(id);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,8 +236,25 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @param object 字典数据对象。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void put(K id, V object) {
|
||||
dataMap.put(id, object);
|
||||
public void put(K id, V object) {
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
dataMap.put(id, object);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -137,7 +263,7 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @return 返回缓存的数据数量。
|
||||
*/
|
||||
@Override
|
||||
public synchronized int getCount() {
|
||||
public int getCount() {
|
||||
return dataMap.size();
|
||||
}
|
||||
|
||||
@@ -148,8 +274,30 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @return 返回被删除的对象,如果主键不存在,返回null。
|
||||
*/
|
||||
@Override
|
||||
public synchronized V invalidate(K id) {
|
||||
return id == null ? null : dataMap.remove(id);
|
||||
public V invalidate(K id) {
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
String exceptionMessage;
|
||||
V data;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
data = dataMap.remove(id);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,19 +306,53 @@ public class MapDictionaryCache<K, V> implements DictionaryCache<K, V> {
|
||||
* @param keys 待删除数据的主键集合。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void invalidateSet(Set<K> keys) {
|
||||
keys.forEach(id -> {
|
||||
if (id != null) {
|
||||
dataMap.remove(id);
|
||||
public void invalidateSet(Set<K> keys) {
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
keys.forEach(id -> {
|
||||
if (id != null) {
|
||||
dataMap.remove(id);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空缓存。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void invalidateAll() {
|
||||
dataMap.clear();
|
||||
public void invalidateAll() {
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
dataMap.clear();
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package com.orange.demo.common.core.cache;
|
||||
|
||||
import com.orange.demo.common.core.exception.MapCacheAccessException;
|
||||
import com.google.common.collect.LinkedHashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
@@ -14,6 +18,7 @@ import java.util.function.Function;
|
||||
* @author Jerry
|
||||
* @date 2020-08-08
|
||||
*/
|
||||
@Slf4j
|
||||
public class MapTreeDictionaryCache<K, V> extends MapDictionaryCache<K, V> {
|
||||
|
||||
/**
|
||||
@@ -61,8 +66,27 @@ public class MapTreeDictionaryCache<K, V> extends MapDictionaryCache<K, V> {
|
||||
* @param parentId 父主键Id。
|
||||
* @return 子数据列表。
|
||||
*/
|
||||
public synchronized List<V> getListByParentId(K parentId) {
|
||||
return new LinkedList<>(allTreeMap.get(parentId));
|
||||
public List<V> getListByParentId(K parentId) {
|
||||
List<V> resultList = new LinkedList<>();
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
resultList.addAll(allTreeMap.get(parentId));
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
return resultList;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,16 +95,33 @@ public class MapTreeDictionaryCache<K, V> extends MapDictionaryCache<K, V> {
|
||||
* @param dataList 待缓存的数据列表。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void putAll(List<V> dataList) {
|
||||
public void putAll(List<V> dataList) {
|
||||
if (dataList == null) {
|
||||
return;
|
||||
}
|
||||
super.putAll(dataList);
|
||||
dataList.forEach(data -> {
|
||||
K parentId = parentIdGetter.apply(data);
|
||||
allTreeMap.remove(parentId, data);
|
||||
allTreeMap.put(parentId, data);
|
||||
});
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
super.putAll(dataList);
|
||||
dataList.forEach(data -> {
|
||||
K parentId = parentIdGetter.apply(data);
|
||||
allTreeMap.remove(parentId, data);
|
||||
allTreeMap.put(parentId, data);
|
||||
});
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,11 +131,28 @@ public class MapTreeDictionaryCache<K, V> extends MapDictionaryCache<K, V> {
|
||||
* @param data 字典数据对象。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void put(K id, V data) {
|
||||
super.put(id, data);
|
||||
K parentId = parentIdGetter.apply(data);
|
||||
allTreeMap.remove(parentId, data);
|
||||
allTreeMap.put(parentId, data);
|
||||
public void put(K id, V data) {
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
super.put(id, data);
|
||||
K parentId = parentIdGetter.apply(data);
|
||||
allTreeMap.remove(parentId, data);
|
||||
allTreeMap.put(parentId, data);
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,11 +162,29 @@ public class MapTreeDictionaryCache<K, V> extends MapDictionaryCache<K, V> {
|
||||
* @return 返回被删除的对象,如果主键不存在,返回null。
|
||||
*/
|
||||
@Override
|
||||
public synchronized V invalidate(K id) {
|
||||
V v = super.invalidate(id);
|
||||
if (v != null) {
|
||||
K parentId = parentIdGetter.apply(v);
|
||||
allTreeMap.remove(parentId, v);
|
||||
public V invalidate(K id) {
|
||||
V v;
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
v = super.invalidate(id);
|
||||
if (v != null) {
|
||||
K parentId = parentIdGetter.apply(v);
|
||||
allTreeMap.remove(parentId, v);
|
||||
}
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
@@ -119,24 +195,58 @@ public class MapTreeDictionaryCache<K, V> extends MapDictionaryCache<K, V> {
|
||||
* @param keys 待删除数据的主键集合。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void invalidateSet(Set<K> keys) {
|
||||
keys.forEach(id -> {
|
||||
if (id != null) {
|
||||
V data = dataMap.remove(id);
|
||||
if (data != null) {
|
||||
K parentId = parentIdGetter.apply(data);
|
||||
allTreeMap.remove(parentId, data);
|
||||
public void invalidateSet(Set<K> keys) {
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
keys.forEach(id -> {
|
||||
if (id != null) {
|
||||
V data = dataMap.remove(id);
|
||||
if (data != null) {
|
||||
K parentId = parentIdGetter.apply(data);
|
||||
allTreeMap.remove(parentId, data);
|
||||
}
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空缓存。
|
||||
*/
|
||||
@Override
|
||||
public synchronized void invalidateAll() {
|
||||
super.invalidateAll();
|
||||
allTreeMap.clear();
|
||||
public void invalidateAll() {
|
||||
String exceptionMessage;
|
||||
try {
|
||||
if (lock.readLock().tryLock(TIMEOUT, TimeUnit.MILLISECONDS)) {
|
||||
try {
|
||||
super.invalidateAll();
|
||||
allTreeMap.clear();
|
||||
} finally {
|
||||
lock.readLock().unlock();
|
||||
}
|
||||
} else {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
exceptionMessage = String.format(
|
||||
"LOCK Operation of [MapDictionaryCache::getInList] encountered EXCEPTION [%s] for DICT.",
|
||||
e.getClass().getSimpleName());
|
||||
log.warn(exceptionMessage);
|
||||
throw new MapCacheAccessException(exceptionMessage, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,10 @@ package com.orange.demo.common.core.constant;
|
||||
*/
|
||||
public final class ApplicationConstant {
|
||||
|
||||
/**
|
||||
* 为字典表数据缓存时,缓存名称的固定后缀。
|
||||
*/
|
||||
public static final String DICT_CACHE_NAME_SUFFIX = "-DICT";
|
||||
/**
|
||||
* 图片文件上传的父目录。
|
||||
*/
|
||||
|
||||
@@ -37,7 +37,7 @@ public enum ErrorCodeEnum {
|
||||
INVALID_USER_STATUS("用户状态错误,请刷新后重试!"),
|
||||
|
||||
HAS_CHILDREN_DATA("数据验证失败,子数据存在,请刷新后重试!"),
|
||||
DATA_VALIDATAED_FAILED("数据验证失败,请核对!"),
|
||||
DATA_VALIDATED_FAILED("数据验证失败,请核对!"),
|
||||
UPLOAD_FILE_FAILED("文件上传失败,请联系管理员!"),
|
||||
DATA_SAVE_FAILED("数据保存失败,请联系管理员!"),
|
||||
DATA_ACCESS_FAILED("数据访问失败,请联系管理员!"),
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.orange.demo.common.core.exception;
|
||||
|
||||
/**
|
||||
* 内存缓存访问失败。比如:获取分布式数据锁超时、等待线程中断等。
|
||||
*
|
||||
* @author Jerry
|
||||
* @date 2020-08-08
|
||||
*/
|
||||
public class MapCacheAccessException extends RuntimeException {
|
||||
|
||||
/**
|
||||
* 构造函数。
|
||||
*
|
||||
* @param msg 错误信息。
|
||||
* @param cause 原始异常。
|
||||
*/
|
||||
public MapCacheAccessException(String msg, Throwable cause) {
|
||||
super(msg, cause);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
@@ -45,6 +46,7 @@ public class MyRequestArgumentResolver implements HandlerMethodArgumentResolver
|
||||
classSet.add(Double.class);
|
||||
classSet.add(Boolean.class);
|
||||
classSet.add(Byte.class);
|
||||
classSet.add(BigDecimal.class);
|
||||
classSet.add(Character.class);
|
||||
}
|
||||
|
||||
@@ -100,7 +102,7 @@ public class MyRequestArgumentResolver implements HandlerMethodArgumentResolver
|
||||
}
|
||||
// 获取参数类型。
|
||||
Class<?> parameterType = parameter.getParameterType();
|
||||
//基本类型
|
||||
// 基本类型
|
||||
if (parameterType.isPrimitive()) {
|
||||
return parsePrimitive(parameterType.getName(), value);
|
||||
}
|
||||
@@ -196,6 +198,12 @@ public class MyRequestArgumentResolver implements HandlerMethodArgumentResolver
|
||||
return number.doubleValue();
|
||||
} else if (parameterType == Byte.class) {
|
||||
return number.byteValue();
|
||||
} else if (parameterType == BigDecimal.class) {
|
||||
if (value instanceof Double || value instanceof Float) {
|
||||
return BigDecimal.valueOf(number.doubleValue());
|
||||
} else {
|
||||
return BigDecimal.valueOf(number.longValue());
|
||||
}
|
||||
}
|
||||
} else if (parameterType == Boolean.class) {
|
||||
return value.toString();
|
||||
|
||||
@@ -76,6 +76,9 @@ public class MyGroupParam extends ArrayList<MyGroupParam.GroupInfo> {
|
||||
|
||||
private static GroupBaseData parseGroupBaseData(GroupInfo groupInfo, Class<?> modelClazz) {
|
||||
GroupBaseData baseData = new GroupBaseData();
|
||||
if (StringUtils.isBlank(groupInfo.fieldName)) {
|
||||
throw new IllegalArgumentException("GroupInfo.fieldName can't be EMPTY");
|
||||
}
|
||||
String[] stringArray = StringUtils.split(groupInfo.fieldName,'.');
|
||||
if (stringArray.length == 1) {
|
||||
baseData.modelName = modelClazz.getSimpleName();
|
||||
|
||||
@@ -110,11 +110,11 @@ public class LocalUpDownloader extends BaseUpDownloader {
|
||||
try {
|
||||
byte[] bytes = uploadFile.getBytes();
|
||||
Path path = Paths.get(uploadPath + responseInfo.getFilename());
|
||||
//如果没有files文件夹,则创建
|
||||
// 如果没有files文件夹,则创建
|
||||
if (!Files.isWritable(path)) {
|
||||
Files.createDirectories(Paths.get(uploadPath));
|
||||
}
|
||||
//文件写入指定路径
|
||||
// 文件写入指定路径
|
||||
Files.write(path, bytes);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to write uploaded file [" + uploadFile.getOriginalFilename() + " ].", e);
|
||||
|
||||
@@ -6,6 +6,9 @@ import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Spring 系统启动应用感知对象,主要用于获取Spring Bean的上下文对象,后续的代码中可以直接查找系统中加载的Bean对象。
|
||||
*
|
||||
@@ -62,6 +65,19 @@ public class ApplicationContextHolder implements ApplicationContextAware {
|
||||
return applicationContext.getBean(beanType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据Bean的ClassType,获取Bean对象列表。
|
||||
*
|
||||
* @param beanType Bean的Class类型。。
|
||||
* @param <T> 返回的Bean类型。
|
||||
* @return Bean对象列表。
|
||||
*/
|
||||
public static <T> Collection<T> getBeanListOfType(Class<T> beanType) {
|
||||
assertApplicationContext();
|
||||
Map<String, T> beanMap = applicationContext.getBeansOfType(beanType);
|
||||
return beanMap == null ? null : beanMap.values();
|
||||
}
|
||||
|
||||
private static void assertApplicationContext() {
|
||||
if (ApplicationContextHolder.applicationContext == null) {
|
||||
throw new MyRuntimeException("applicaitonContext属性为null,请检查是否注入了ApplicationContextHolder!");
|
||||
|
||||
@@ -32,29 +32,29 @@ public class IpUtil {
|
||||
*/
|
||||
public static String getRemoteIpAddress(HttpServletRequest request) {
|
||||
String ip = null;
|
||||
//X-Forwarded-For:Squid 服务代理
|
||||
// X-Forwarded-For:Squid 服务代理
|
||||
String ipAddresses = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//Proxy-Client-IP:apache 服务代理
|
||||
// Proxy-Client-IP:apache 服务代理
|
||||
ipAddresses = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//WL-Proxy-Client-IP:weblogic 服务代理
|
||||
// WL-Proxy-Client-IP:weblogic 服务代理
|
||||
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//HTTP_CLIENT_IP:有些代理服务器
|
||||
// HTTP_CLIENT_IP:有些代理服务器
|
||||
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//X-Real-IP:nginx服务代理
|
||||
// X-Real-IP:nginx服务代理
|
||||
ipAddresses = request.getHeader("X-Real-IP");
|
||||
}
|
||||
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
|
||||
// 有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
|
||||
if (StringUtils.isNotBlank(ipAddresses)) {
|
||||
ip = ipAddresses.split(",")[0];
|
||||
}
|
||||
//还是不能获取到,最后再通过request.getRemoteAddr();获取
|
||||
// 还是不能获取到,最后再通过request.getRemoteAddr();获取
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
@@ -69,29 +69,29 @@ public class IpUtil {
|
||||
*/
|
||||
public static String getRemoteIpAddress(ServerHttpRequest request) {
|
||||
String ip = null;
|
||||
//X-Forwarded-For:Squid 服务代理
|
||||
// X-Forwarded-For:Squid 服务代理
|
||||
String ipAddresses = request.getHeaders().getFirst("X-Forwarded-For");
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//Proxy-Client-IP:apache 服务代理
|
||||
// Proxy-Client-IP:apache 服务代理
|
||||
ipAddresses = request.getHeaders().getFirst("Proxy-Client-IP");
|
||||
}
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//WL-Proxy-Client-IP:weblogic 服务代理
|
||||
// WL-Proxy-Client-IP:weblogic 服务代理
|
||||
ipAddresses = request.getHeaders().getFirst("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//HTTP_CLIENT_IP:有些代理服务器
|
||||
// HTTP_CLIENT_IP:有些代理服务器
|
||||
ipAddresses = request.getHeaders().getFirst("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
//X-Real-IP:nginx服务代理
|
||||
// X-Real-IP:nginx服务代理
|
||||
ipAddresses = request.getHeaders().getFirst("X-Real-IP");
|
||||
}
|
||||
//有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
|
||||
// 有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP
|
||||
if (StringUtils.isNotBlank(ipAddresses)) {
|
||||
ip = ipAddresses.split(",")[0];
|
||||
}
|
||||
//还是不能获取到,最后再通过request.getRemoteAddr();获取
|
||||
// 还是不能获取到,最后再通过request.getRemoteAddr();获取
|
||||
if (StringUtils.isBlank(ipAddresses) || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
|
||||
ip = request.getRemoteAddress().getAddress().getHostAddress();
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ public class MyCommonUtil {
|
||||
* @param objs 一组参数。
|
||||
* @return 返回是否存在null或空字符串的参数。
|
||||
*/
|
||||
public static boolean existBlankArgument(Object... objs) {
|
||||
public static boolean existBlankArgument(Object...objs) {
|
||||
for (Object obj : objs) {
|
||||
if (MyCommonUtil.isBlankOrNull(obj)) {
|
||||
return true;
|
||||
@@ -68,7 +68,7 @@ public class MyCommonUtil {
|
||||
* @param objs 一组参数。
|
||||
* @return 返回是否存在null或空字符串的参数。
|
||||
*/
|
||||
public static boolean existNotBlankArgument(Object... objs) {
|
||||
public static boolean existNotBlankArgument(Object...objs) {
|
||||
for (Object obj : objs) {
|
||||
if (!MyCommonUtil.isBlankOrNull(obj)) {
|
||||
return true;
|
||||
@@ -107,7 +107,7 @@ public class MyCommonUtil {
|
||||
* @param groups Validate绑定的校验组。
|
||||
* @return 没有错误返回null,否则返回具体的错误信息。
|
||||
*/
|
||||
public static <T> String getModelValidationError(T model, Class<?>... groups) {
|
||||
public static <T> String getModelValidationError(T model, Class<?>...groups) {
|
||||
Set<ConstraintViolation<T>> constraintViolations = validator.validate(model, groups);
|
||||
if (!constraintViolations.isEmpty()) {
|
||||
Iterator<ConstraintViolation<T>> it = constraintViolations.iterator();
|
||||
@@ -146,8 +146,8 @@ public class MyCommonUtil {
|
||||
*/
|
||||
public static <T> String[] getNotNullFieldNames(T object, Class<T> clazz) {
|
||||
Field[] fields = ReflectUtil.getFields(clazz);
|
||||
List<String> fieldNameList = Arrays.stream(fields).
|
||||
filter(f -> ReflectUtil.getFieldValue(object, f) != null)
|
||||
List<String> fieldNameList = Arrays.stream(fields)
|
||||
.filter(f -> ReflectUtil.getFieldValue(object, f) != null)
|
||||
.map(Field::getName).collect(Collectors.toList());
|
||||
if (CollectionUtils.isNotEmpty(fieldNameList)) {
|
||||
return fieldNameList.toArray(new String[]{});
|
||||
|
||||
@@ -46,9 +46,9 @@ public class RsaUtil {
|
||||
// 得到私钥字符串
|
||||
String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
|
||||
// 将公钥和私钥保存到Map
|
||||
//0表示公钥
|
||||
// 0表示公钥
|
||||
keyMap.put(0, publicKeyString);
|
||||
//1表示私钥
|
||||
// 1表示私钥
|
||||
keyMap.put(1, privateKeyString);
|
||||
}
|
||||
|
||||
@@ -61,11 +61,11 @@ public class RsaUtil {
|
||||
* @throws Exception 加密过程中的异常信息
|
||||
*/
|
||||
public static String encrypt(String str, String publicKey) throws Exception {
|
||||
//base64编码的公钥
|
||||
// base64编码的公钥
|
||||
byte[] decoded = Base64.getDecoder().decode(publicKey);
|
||||
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
|
||||
//RSA加密。后面这个更安全,但是SonarQube始终report安全漏洞。"RSA/ECB/PKCS1Padding"
|
||||
//而浏览器自带的Javascript加密功能,目前safari不支持,而且用的人也不太多。所以暂时都不考虑了。
|
||||
// RSA加密。后面这个更安全,但是SonarQube始终report安全漏洞。"RSA/ECB/PKCS1Padding"
|
||||
// 而浏览器自带的Javascript加密功能,目前safari不支持,而且用的人也不太多。所以暂时都不考虑了。
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
|
||||
return Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
|
||||
@@ -80,12 +80,12 @@ public class RsaUtil {
|
||||
* @throws Exception 解密过程中的异常信息
|
||||
*/
|
||||
public static String decrypt(String str, String privateKey) throws Exception {
|
||||
//64位解码加密后的字符串
|
||||
// 64位解码加密后的字符串
|
||||
byte[] inputByte = Base64.getDecoder().decode(str);
|
||||
//base64编码的私钥
|
||||
// base64编码的私钥
|
||||
byte[] decoded = Base64.getDecoder().decode(privateKey);
|
||||
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
|
||||
//RSA解密
|
||||
// RSA解密
|
||||
Cipher cipher = Cipher.getInstance("RSA");
|
||||
cipher.init(Cipher.DECRYPT_MODE, priKey);
|
||||
return new String(cipher.doFinal(inputByte));
|
||||
@@ -93,9 +93,9 @@ public class RsaUtil {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
long temp = System.currentTimeMillis();
|
||||
//生成公钥和私钥
|
||||
// 生成公钥和私钥
|
||||
genKeyPair();
|
||||
//加密字符串
|
||||
// 加密字符串
|
||||
System.out.println("公钥:" + keyMap.get(0));
|
||||
System.out.println("私钥:" + keyMap.get(1));
|
||||
System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
|
||||
|
||||
Reference in New Issue
Block a user