ad068a03c51e5d74de4b2a0b4ae07d0a16501607.svn-base 18 KB

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