DictAspect.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package org.jeecg.common.aspect;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.fastjson.parser.Feature;
  5. import com.baomidou.mybatisplus.core.metadata.IPage;
  6. import com.fasterxml.jackson.core.JsonProcessingException;
  7. import com.fasterxml.jackson.databind.ObjectMapper;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.aspectj.lang.ProceedingJoinPoint;
  10. import org.aspectj.lang.annotation.Around;
  11. import org.aspectj.lang.annotation.Aspect;
  12. import org.aspectj.lang.annotation.Pointcut;
  13. import org.jeecg.common.api.CommonAPI;
  14. import org.jeecg.common.api.vo.Result;
  15. import org.jeecg.common.aspect.annotation.Dict;
  16. import org.jeecg.common.constant.CommonConstant;
  17. import org.jeecg.common.system.vo.DictModel;
  18. import org.jeecg.common.util.oConvertUtils;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.context.annotation.Lazy;
  21. import org.springframework.data.redis.core.RedisTemplate;
  22. import org.springframework.stereotype.Component;
  23. import org.springframework.util.StringUtils;
  24. import java.lang.reflect.Field;
  25. import java.util.*;
  26. import java.util.concurrent.TimeUnit;
  27. import java.util.stream.Collectors;
  28. /**
  29. * @Description: 字典aop类
  30. * @Author: dangzhenghui
  31. * @Date: 2019-3-17 21:50
  32. * @Version: 1.0
  33. */
  34. @Aspect
  35. @Component
  36. @Slf4j
  37. public class DictAspect {
  38. @Lazy
  39. @Autowired
  40. private CommonAPI commonApi;
  41. @Autowired
  42. public RedisTemplate redisTemplate;
  43. @Autowired
  44. private ObjectMapper objectMapper;
  45. private static final String JAVA_UTIL_DATE = "java.util.Date";
  46. /**
  47. * 定义切点Pointcut
  48. */
  49. @Pointcut("execution(public * org.jeecg.modules..*.*Controller.*(..)) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)")
  50. public void excudeService() {
  51. }
  52. @Around("excudeService()")
  53. public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
  54. long time1=System.currentTimeMillis();
  55. Object result = pjp.proceed();
  56. long time2=System.currentTimeMillis();
  57. log.debug("获取JSON数据 耗时:"+(time2-time1)+"ms");
  58. long start=System.currentTimeMillis();
  59. result=this.parseDictText(result);
  60. long end=System.currentTimeMillis();
  61. log.debug("注入字典到JSON数据 耗时"+(end-start)+"ms");
  62. return result;
  63. }
  64. /**
  65. * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
  66. * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
  67. * 示例为SysUser 字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
  68. * 例输入当前返回值的就会多出一个sex_dictText字段
  69. * {
  70. * sex:1,
  71. * sex_dictText:"男"
  72. * }
  73. * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
  74. * customRender:function (text) {
  75. * if(text==1){
  76. * return "男";
  77. * }else if(text==2){
  78. * return "女";
  79. * }else{
  80. * return text;
  81. * }
  82. * }
  83. * 目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
  84. * @param result
  85. */
  86. private Object parseDictText(Object result) {
  87. if (result instanceof Result) {
  88. if (((Result) result).getResult() instanceof IPage) {
  89. List<JSONObject> items = new ArrayList<>();
  90. //step.1 筛选出加了 Dict 注解的字段列表
  91. List<Field> dictFieldList = new ArrayList<>();
  92. // 字典数据列表, key = 字典code,value=数据列表
  93. Map<String, List<String>> dataListMap = new HashMap<>(5);
  94. //取出结果集
  95. List<Object> records=((IPage) ((Result) result).getResult()).getRecords();
  96. //update-begin--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  97. Boolean hasDict= checkHasDict(records);
  98. if(!hasDict){
  99. return result;
  100. }
  101. log.debug(" __ 进入字典翻译切面 DictAspect —— " );
  102. //update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  103. for (Object record : records) {
  104. String json="{}";
  105. try {
  106. //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  107. //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  108. json = objectMapper.writeValueAsString(record);
  109. //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  110. } catch (JsonProcessingException e) {
  111. log.error("json解析失败"+e.getMessage(),e);
  112. }
  113. //update-begin--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  114. JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
  115. //update-end--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  116. //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  117. //for (Field field : record.getClass().getDeclaredFields()) {
  118. // 遍历所有字段,把字典Code取出来,放到 map 里
  119. for (Field field : oConvertUtils.getAllFields(record)) {
  120. String value = item.getString(field.getName());
  121. if (oConvertUtils.isEmpty(value)) {
  122. continue;
  123. }
  124. //update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  125. if (field.getAnnotation(Dict.class) != null) {
  126. if (!dictFieldList.contains(field)) {
  127. dictFieldList.add(field);
  128. }
  129. String code = field.getAnnotation(Dict.class).dicCode();
  130. String text = field.getAnnotation(Dict.class).dicText();
  131. String table = field.getAnnotation(Dict.class).dictTable();
  132. List<String> dataList;
  133. String dictCode = code;
  134. if (!StringUtils.isEmpty(table)) {
  135. dictCode = String.format("%s,%s,%s", table, text, code);
  136. }
  137. dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
  138. this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
  139. }
  140. //date类型默认转换string格式化日期
  141. //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  142. //if (JAVA_UTIL_DATE.equals(field.getType().getName())&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
  143. //SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  144. // item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  145. //}
  146. //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  147. }
  148. items.add(item);
  149. }
  150. //step.2 调用翻译方法,一次性翻译
  151. Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
  152. //step.3 将翻译结果填充到返回结果里
  153. for (JSONObject record : items) {
  154. for (Field field : dictFieldList) {
  155. String code = field.getAnnotation(Dict.class).dicCode();
  156. String text = field.getAnnotation(Dict.class).dicText();
  157. String table = field.getAnnotation(Dict.class).dictTable();
  158. String fieldDictCode = code;
  159. if (!StringUtils.isEmpty(table)) {
  160. fieldDictCode = String.format("%s,%s,%s", table, text, code);
  161. }
  162. String value = record.getString(field.getName());
  163. if (oConvertUtils.isNotEmpty(value)) {
  164. List<DictModel> dictModels = translText.get(fieldDictCode);
  165. if(dictModels==null || dictModels.size()==0){
  166. continue;
  167. }
  168. String textValue = this.translDictText(dictModels, value);
  169. log.debug(" 字典Val : " + textValue);
  170. log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  171. // TODO-sun 测试输出,待删
  172. log.debug(" ---- dictCode: " + fieldDictCode);
  173. log.debug(" ---- value: " + value);
  174. log.debug(" ----- text: " + textValue);
  175. log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));
  176. record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  177. }
  178. }
  179. }
  180. ((IPage) ((Result) result).getResult()).setRecords(items);
  181. }
  182. }
  183. return result;
  184. }
  185. /**
  186. * list 去重添加
  187. */
  188. private void listAddAllDeduplicate(List<String> dataList, List<String> addList) {
  189. // 筛选出dataList中没有的数据
  190. List<String> filterList = addList.stream().filter(i -> !dataList.contains(i)).collect(Collectors.toList());
  191. dataList.addAll(filterList);
  192. }
  193. /**
  194. * 一次性把所有的字典都翻译了
  195. * 1. 所有的普通数据字典的所有数据只执行一次SQL
  196. * 2. 表字典相同的所有数据只执行一次SQL
  197. * @param dataListMap
  198. * @return
  199. */
  200. private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) {
  201. // 翻译后的字典文本,key=dictCode
  202. Map<String, List<DictModel>> translText = new HashMap<>(5);
  203. // 需要翻译的数据(有些可以从redis缓存中获取,就不走数据库查询)
  204. List<String> needTranslData = new ArrayList<>();
  205. //step.1 先通过redis中获取缓存字典数据
  206. for (String dictCode : dataListMap.keySet()) {
  207. List<String> dataList = dataListMap.get(dictCode);
  208. if (dataList.size() == 0) {
  209. continue;
  210. }
  211. // 表字典需要翻译的数据
  212. List<String> needTranslDataTable = new ArrayList<>();
  213. for (String s : dataList) {
  214. String data = s.trim();
  215. if (data.length() == 0) {
  216. continue; //跳过循环
  217. }
  218. if (dictCode.contains(",")) {
  219. String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, data);
  220. if (redisTemplate.hasKey(keyString)) {
  221. try {
  222. String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  223. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  224. list.add(new DictModel(data, text));
  225. } catch (Exception e) {
  226. log.warn(e.getMessage());
  227. }
  228. } else if (!needTranslDataTable.contains(data)) {
  229. // 去重添加
  230. needTranslDataTable.add(data);
  231. }
  232. } else {
  233. String keyString = String.format("sys:cache:dict::%s:%s", dictCode, data);
  234. if (redisTemplate.hasKey(keyString)) {
  235. try {
  236. String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  237. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  238. list.add(new DictModel(data, text));
  239. } catch (Exception e) {
  240. log.warn(e.getMessage());
  241. }
  242. } else if (!needTranslData.contains(data)) {
  243. // 去重添加
  244. needTranslData.add(data);
  245. }
  246. }
  247. }
  248. //step.2 调用数据库翻译表字典
  249. if (needTranslDataTable.size() > 0) {
  250. String[] arr = dictCode.split(",");
  251. String table = arr[0], text = arr[1], code = arr[2];
  252. String values = String.join(",", needTranslDataTable);
  253. log.debug("translateDictFromTableByKeys.dictCode:" + dictCode);
  254. log.debug("translateDictFromTableByKeys.values:" + values);
  255. List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values);
  256. log.debug("translateDictFromTableByKeys.result:" + texts);
  257. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  258. list.addAll(texts);
  259. // 做 redis 缓存
  260. for (DictModel dict : texts) {
  261. String redisKey = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, dict.getValue());
  262. try {
  263. // update-begin-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061
  264. // 保留5分钟
  265. redisTemplate.opsForValue().set(redisKey, dict.getText(), 300, TimeUnit.SECONDS);
  266. // update-end-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061
  267. } catch (Exception e) {
  268. log.warn(e.getMessage(), e);
  269. }
  270. }
  271. }
  272. }
  273. //step.3 调用数据库进行翻译普通字典
  274. if (needTranslData.size() > 0) {
  275. List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
  276. // 将不包含逗号的字典code筛选出来,因为带逗号的是表字典,而不是普通的数据字典
  277. List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList());
  278. String dictCodes = String.join(",", filterDictCodes);
  279. String values = String.join(",", needTranslData);
  280. log.debug("translateManyDict.dictCodes:" + dictCodes);
  281. log.debug("translateManyDict.values:" + values);
  282. Map<String, List<DictModel>> manyDict = commonApi.translateManyDict(dictCodes, values);
  283. log.debug("translateManyDict.result:" + manyDict);
  284. for (String dictCode : manyDict.keySet()) {
  285. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  286. List<DictModel> newList = manyDict.get(dictCode);
  287. list.addAll(newList);
  288. // 做 redis 缓存
  289. for (DictModel dict : newList) {
  290. String redisKey = String.format("sys:cache:dict::%s:%s", dictCode, dict.getValue());
  291. try {
  292. redisTemplate.opsForValue().set(redisKey, dict.getText());
  293. } catch (Exception e) {
  294. log.warn(e.getMessage(), e);
  295. }
  296. }
  297. }
  298. }
  299. return translText;
  300. }
  301. /**
  302. * 字典值替换文本
  303. *
  304. * @param dictModels
  305. * @param values
  306. * @return
  307. */
  308. private String translDictText(List<DictModel> dictModels, String values) {
  309. List<String> result = new ArrayList<>();
  310. // 允许多个逗号分隔,允许传数组对象
  311. String[] splitVal = values.split(",");
  312. for (String val : splitVal) {
  313. String dictText = val;
  314. for (DictModel dict : dictModels) {
  315. if (val.equals(dict.getValue())) {
  316. dictText = dict.getText();
  317. break;
  318. }
  319. }
  320. result.add(dictText);
  321. }
  322. return String.join(",", result);
  323. }
  324. /**
  325. * 翻译字典文本
  326. * @param code
  327. * @param text
  328. * @param table
  329. * @param key
  330. * @return
  331. */
  332. @Deprecated
  333. private String translateDictValue(String code, String text, String table, String key) {
  334. if(oConvertUtils.isEmpty(key)) {
  335. return null;
  336. }
  337. StringBuffer textValue=new StringBuffer();
  338. String[] keys = key.split(",");
  339. for (String k : keys) {
  340. String tmpValue = null;
  341. log.debug(" 字典 key : "+ k);
  342. if (k.trim().length() == 0) {
  343. continue; //跳过循环
  344. }
  345. //update-begin--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
  346. if (!StringUtils.isEmpty(table)){
  347. log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
  348. String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim());
  349. if (redisTemplate.hasKey(keyString)){
  350. try {
  351. tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  352. } catch (Exception e) {
  353. log.warn(e.getMessage());
  354. }
  355. }else {
  356. tmpValue= commonApi.translateDictFromTable(table,text,code,k.trim());
  357. }
  358. }else {
  359. String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim());
  360. if (redisTemplate.hasKey(keyString)){
  361. try {
  362. tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  363. } catch (Exception e) {
  364. log.warn(e.getMessage());
  365. }
  366. }else {
  367. tmpValue = commonApi.translateDict(code, k.trim());
  368. }
  369. }
  370. //update-end--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
  371. if (tmpValue != null) {
  372. if (!"".equals(textValue.toString())) {
  373. textValue.append(",");
  374. }
  375. textValue.append(tmpValue);
  376. }
  377. }
  378. return textValue.toString();
  379. }
  380. /**
  381. * 检测返回结果集中是否包含Dict注解
  382. * @param records
  383. * @return
  384. */
  385. private Boolean checkHasDict(List<Object> records){
  386. if(oConvertUtils.isNotEmpty(records) && records.size()>0){
  387. for (Field field : oConvertUtils.getAllFields(records.get(0))) {
  388. if (oConvertUtils.isNotEmpty(field.getAnnotation(Dict.class))) {
  389. return true;
  390. }
  391. }
  392. }
  393. return false;
  394. }
  395. }