[关闭]
@liruiyi962464 2025-07-25T08:13:06.000000Z 字数 42113 阅读 104

Jeecg-boot字典翻译改造

代码

一.找到字典切面类(DictAspect)
二.改造方法(parseDictText)
三.修改后的parseDictText方法,支持IPage、List、Object,parseDictText 注释此方法,完后拷贝下方代码

  1. private void parseDictText(Object result) {
  2. if (result instanceof Result) {
  3. List<Object> list = new LinkedList<>();
  4. if (((Result) result).getResult() instanceof IPage) {
  5. //分页
  6. list = ((IPage) ((Result) result).getResult()).getRecords();
  7. } else if (((Result) result).getResult() instanceof List) {
  8. //List集合
  9. list = (List<Object>) ((Result) result).getResult();
  10. }else{
  11. //单对象
  12. Object record = ((Result) result).getResult();
  13. //判断能否转换成JSON,因为有些结果集返回的是String类型,导致翻译异常,因此判断是否可以转换json
  14. if(checkIsJsonStr(record)){
  15. //字典翻译
  16. record = this.dictEscape(record);
  17. }
  18. ((Result) result).setResult(record);
  19. }
  20. if(list != null && list.size() > 0){
  21. List<Object> items = new ArrayList<>();
  22. for(Object record : list){
  23. if(checkIsJsonStr(record)){
  24. //字典翻译
  25. record = this.dictEscape(record);
  26. }
  27. items.add(record);
  28. }
  29. if (((Result) result).getResult() instanceof IPage) {
  30. ((IPage) ((Result) result).getResult()).setRecords(items);
  31. } else if (((Result) result).getResult() instanceof List) {
  32. ((Result) result).setResult(items);
  33. }
  34. }
  35. }
  36. }

四.提取公共代码作为单独的方法进行翻译

  1. /**
  2. * 字典翻译
  3. * @param record
  4. * @return
  5. */
  6. private JSONObject dictEscape(Object record){
  7. ObjectMapper mapper = new ObjectMapper();
  8. String json = "{}";
  9. JSONObject item = null;
  10. try {
  11. //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  12. json = mapper.writeValueAsString(record);//对象序列化为JSON字符串
  13. } catch (JsonProcessingException e) {
  14. log.error("json解析失败" + e.getMessage(), e);
  15. }
  16. try {
  17. item = JSONObject.parseObject(json);
  18. //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  19. for (Field field : oConvertUtils.getAllFields(record)) {
  20. //update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  21. if (field.getAnnotation(Dict.class) != null) {
  22. String code = field.getAnnotation(Dict.class).dicCode();
  23. String text = field.getAnnotation(Dict.class).dicText();
  24. String table = field.getAnnotation(Dict.class).dictTable();
  25. String key = String.valueOf(item.get(field.getName()));
  26. //翻译字典值对应的txt
  27. String textValue = key;
  28. //非中文时翻译
  29. if(!checkCountName(key)){
  30. textValue = translateDictValue(code, text, table, key);
  31. }
  32. log.debug(" 字典Val : " + textValue);
  33. log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  34. item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  35. }
  36. //date类型默认转换string格式化日期
  37. if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
  38. SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  39. item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  40. }
  41. }
  42. }catch (Exception e){
  43. log.info("字典翻译异常:"+e.getMessage(),e);
  44. }
  45. return item;
  46. }

五.增加中文检测方法

  1. /**
  2. * 检测是否是中文
  3. * @param countName
  4. * @return
  5. */
  6. public static boolean checkCountName(String countName){
  7. Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
  8. Matcher m = p.matcher(countName);
  9. if (m.find()) {
  10. return true;
  11. }
  12. return false;
  13. }

六.增加检测是否可转换为JSON字符串方法

  1. /**
  2. * 检测是否可转换为JSON字符串
  3. * @param record
  4. * @return
  5. */
  6. public static boolean checkIsJsonStr(Object record){
  7. boolean jsonFlag = false;
  8. try {
  9. String json = new ObjectMapper().writeValueAsString(record);
  10. if(json.startsWith("{")) {
  11. jsonFlag = true;
  12. }
  13. } catch (JsonProcessingException e) {
  14. e.printStackTrace();
  15. }
  16. return jsonFlag;
  17. }

七、不涉及分布式的整体修改

  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.annotation.JsonFormat;
  7. import com.fasterxml.jackson.core.JsonProcessingException;
  8. import com.fasterxml.jackson.databind.ObjectMapper;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.aspectj.lang.ProceedingJoinPoint;
  11. import org.aspectj.lang.annotation.Around;
  12. import org.aspectj.lang.annotation.Aspect;
  13. import org.aspectj.lang.annotation.Pointcut;
  14. import org.jeecg.common.api.CommonAPI;
  15. import org.jeecg.common.api.vo.Result;
  16. import org.jeecg.common.aspect.annotation.Dict;
  17. import org.jeecg.common.constant.CommonConstant;
  18. import org.jeecg.common.system.vo.DictModel;
  19. import org.jeecg.common.util.oConvertUtils;
  20. import org.jetbrains.annotations.NotNull;
  21. import org.springframework.beans.factory.annotation.Autowired;
  22. import org.springframework.context.annotation.Lazy;
  23. import org.springframework.data.redis.core.RedisTemplate;
  24. import org.springframework.stereotype.Component;
  25. import org.springframework.util.StringUtils;
  26. import java.lang.reflect.Field;
  27. import java.text.SimpleDateFormat;
  28. import java.util.*;
  29. import java.util.concurrent.TimeUnit;
  30. import java.util.regex.Matcher;
  31. import java.util.regex.Pattern;
  32. import java.util.stream.Collectors;
  33. /**
  34. * @Description: 字典aop类
  35. * @Author: dangzhenghui
  36. * @Date: 2019-3-17 21:50
  37. * @Version: 1.0
  38. */
  39. @Aspect
  40. @Component
  41. @Slf4j
  42. public class DictAspect {
  43. @Lazy
  44. @Autowired
  45. private CommonAPI commonApi;
  46. @Autowired
  47. public RedisTemplate redisTemplate;
  48. @Autowired
  49. private ObjectMapper objectMapper;
  50. private static final String JAVA_UTIL_DATE = "java.util.Date";
  51. /**
  52. * 定义切点Pointcut
  53. */
  54. @Pointcut("(@within(org.springframework.web.bind.annotation.RestController) || " +
  55. "@within(org.springframework.stereotype.Controller) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)) " +
  56. "&& execution(public org.jeecg.common.api.vo.Result org.jeecg..*.*(..))")
  57. public void excudeService() {
  58. }
  59. @Around("excudeService()")
  60. public Object doAround(@NotNull ProceedingJoinPoint pjp) throws Throwable {
  61. long time1=System.currentTimeMillis();
  62. Object result = pjp.proceed();
  63. long time2=System.currentTimeMillis();
  64. log.debug("获取JSON数据 耗时:"+(time2-time1)+"ms");
  65. long start=System.currentTimeMillis();
  66. // result=this.parseDictText(result);
  67. this.parseDictText(result);
  68. long end=System.currentTimeMillis();
  69. log.debug("注入字典到JSON数据 耗时"+(end-start)+"ms");
  70. return result;
  71. }
  72. /**
  73. * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
  74. * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
  75. * 示例为SysUser 字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
  76. * 例输入当前返回值的就会多出一个sex_dictText字段
  77. * {
  78. * sex:1,
  79. * sex_dictText:"男"
  80. * }
  81. * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
  82. * customRender:function (text) {
  83. * if(text==1){
  84. * return "男";
  85. * }else if(text==2){
  86. * return "女";
  87. * }else{
  88. * return text;
  89. * }
  90. * }
  91. * 目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
  92. * @param result
  93. */
  94. // private Object parseDictText(Object result) {
  95. // //if (result instanceof Result) {
  96. // if (true) {
  97. // if (((Result) result).getResult() instanceof IPage) {
  98. // List<JSONObject> items = new ArrayList<>();
  99. //
  100. // //step.1 筛选出加了 Dict 注解的字段列表
  101. // List<Field> dictFieldList = new ArrayList<>();
  102. // // 字典数据列表, key = 字典code,value=数据列表
  103. // Map<String, List<String>> dataListMap = new HashMap<>(5);
  104. // //取出结果集
  105. // List<Object> records=((IPage) ((Result) result).getResult()).getRecords();
  106. // //update-begin--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  107. // Boolean hasDict= checkHasDict(records);
  108. // if(!hasDict){
  109. // return result;
  110. // }
  111. //
  112. // log.debug(" __ 进入字典翻译切面 DictAspect —— " );
  113. // //update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  114. // for (Object record : records) {
  115. // String json="{}";
  116. // try {
  117. // //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  118. // //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  119. // json = objectMapper.writeValueAsString(record);
  120. // //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  121. // } catch (JsonProcessingException e) {
  122. // log.error("json解析失败"+e.getMessage(),e);
  123. // }
  124. // //update-begin--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  125. // JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
  126. // //update-end--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  127. //
  128. // //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  129. // //for (Field field : record.getClass().getDeclaredFields()) {
  130. // // 遍历所有字段,把字典Code取出来,放到 map 里
  131. // for (Field field : oConvertUtils.getAllFields(record)) {
  132. // String value = item.getString(field.getName());
  133. // if (oConvertUtils.isEmpty(value)) {
  134. // continue;
  135. // }
  136. // //update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  137. // if (field.getAnnotation(Dict.class) != null) {
  138. // if (!dictFieldList.contains(field)) {
  139. // dictFieldList.add(field);
  140. // }
  141. // String code = field.getAnnotation(Dict.class).dicCode();
  142. // String text = field.getAnnotation(Dict.class).dicText();
  143. // String table = field.getAnnotation(Dict.class).dictTable();
  144. // //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  145. // String dataSource = field.getAnnotation(Dict.class).ds();
  146. // //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  147. // List<String> dataList;
  148. // String dictCode = code;
  149. // if (!StringUtils.isEmpty(table)) {
  150. // //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  151. // dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  152. // //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  153. // }
  154. // dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
  155. // this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
  156. // }
  157. // //date类型默认转换string格式化日期
  158. // //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  159. // //if (JAVA_UTIL_DATE.equals(field.getType().getName())&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
  160. // //SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  161. // // item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  162. // //}
  163. // //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  164. // }
  165. // items.add(item);
  166. // }
  167. //
  168. // //step.2 调用翻译方法,一次性翻译
  169. // Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
  170. //
  171. // //step.3 将翻译结果填充到返回结果里
  172. // for (JSONObject record : items) {
  173. // for (Field field : dictFieldList) {
  174. // String code = field.getAnnotation(Dict.class).dicCode();
  175. // String text = field.getAnnotation(Dict.class).dicText();
  176. // String table = field.getAnnotation(Dict.class).dictTable();
  177. // //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  178. // // 自定义的字典表数据源
  179. // String dataSource = field.getAnnotation(Dict.class).ds();
  180. // //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  181. // String fieldDictCode = code;
  182. // if (!StringUtils.isEmpty(table)) {
  183. // //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  184. // fieldDictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  185. // //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  186. // }
  187. //
  188. // String value = record.getString(field.getName());
  189. // if (oConvertUtils.isNotEmpty(value)) {
  190. // List<DictModel> dictModels = translText.get(fieldDictCode);
  191. // if(dictModels==null || dictModels.size()==0){
  192. // continue;
  193. // }
  194. //
  195. // String textValue = this.translDictText(dictModels, value);
  196. // log.debug(" 字典Val : " + textValue);
  197. // log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  198. //
  199. // // TODO-sun 测试输出,待删
  200. // log.debug(" ---- dictCode: " + fieldDictCode);
  201. // log.debug(" ---- value: " + value);
  202. // log.debug(" ----- text: " + textValue);
  203. // log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));
  204. //
  205. // record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  206. // }
  207. // }
  208. // }
  209. //
  210. // ((IPage) ((Result) result).getResult()).setRecords(items);
  211. // }
  212. //
  213. // }
  214. // return result;
  215. // }
  216. private void parseDictText(Object result) {
  217. if (result instanceof Result) {
  218. List<Object> list = new LinkedList<>();
  219. if (((Result) result).getResult() instanceof IPage) {
  220. //分页
  221. list = ((IPage) ((Result) result).getResult()).getRecords();
  222. } else if (((Result) result).getResult() instanceof List) {
  223. //List集合
  224. list = (List<Object>) ((Result) result).getResult();
  225. }else{
  226. //单对象
  227. Object record = ((Result) result).getResult();
  228. //判断能否转换成JSON,因为有些结果集返回的是String类型,导致翻译异常,因此判断是否可以转换json
  229. if(checkIsJsonStr(record)){
  230. //字典翻译
  231. record = this.dictEscape(record);
  232. }
  233. ((Result) result).setResult(record);
  234. }
  235. if(list != null && list.size() > 0){
  236. List<Object> items = new ArrayList<>();
  237. for(Object record : list){
  238. if(checkIsJsonStr(record)){
  239. //字典翻译
  240. record = this.dictEscape(record);
  241. }
  242. items.add(record);
  243. }
  244. if (((Result) result).getResult() instanceof IPage) {
  245. ((IPage) ((Result) result).getResult()).setRecords(items);
  246. } else if (((Result) result).getResult() instanceof List) {
  247. ((Result) result).setResult(items);
  248. }
  249. }
  250. }
  251. }
  252. /**
  253. * 字典翻译
  254. * @param record
  255. * @return
  256. */
  257. private JSONObject dictEscape(Object record){
  258. ObjectMapper mapper = new ObjectMapper();
  259. String json = "{}";
  260. JSONObject item = null;
  261. try {
  262. //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  263. json = mapper.writeValueAsString(record);//对象序列化为JSON字符串
  264. } catch (JsonProcessingException e) {
  265. log.error("json解析失败" + e.getMessage(), e);
  266. }
  267. try {
  268. item = JSONObject.parseObject(json);
  269. //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  270. for (Field field : oConvertUtils.getAllFields(record)) {
  271. //update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  272. if (field.getAnnotation(Dict.class) != null) {
  273. String code = field.getAnnotation(Dict.class).dicCode();
  274. String text = field.getAnnotation(Dict.class).dicText();
  275. String table = field.getAnnotation(Dict.class).dictTable();
  276. String key = String.valueOf(item.get(field.getName()));
  277. //翻译字典值对应的txt
  278. String textValue = key;
  279. //非中文时翻译
  280. if(!checkCountName(key)){
  281. textValue = translateDictValue(code, text, table, key);
  282. }
  283. log.debug(" 字典Val : " + textValue);
  284. log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  285. item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  286. }
  287. //date类型默认转换string格式化日期
  288. if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
  289. SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  290. item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  291. }
  292. }
  293. }catch (Exception e){
  294. log.info("字典翻译异常:"+e.getMessage(),e);
  295. }
  296. return item;
  297. }
  298. /**
  299. * 检测是否是中文
  300. * @param countName
  301. * @return
  302. */
  303. public static boolean checkCountName(String countName){
  304. Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
  305. Matcher m = p.matcher(countName);
  306. if (m.find()) {
  307. return true;
  308. }
  309. return false;
  310. }
  311. /**
  312. * 检测是否可转换为JSON字符串
  313. * @param record
  314. * @return
  315. */
  316. public static boolean checkIsJsonStr(Object record){
  317. boolean jsonFlag = false;
  318. try {
  319. String json = new ObjectMapper().writeValueAsString(record);
  320. if(json.startsWith("{")) {
  321. jsonFlag = true;
  322. }
  323. } catch (JsonProcessingException e) {
  324. e.printStackTrace();
  325. }
  326. return jsonFlag;
  327. }
  328. /**
  329. * list 去重添加
  330. */
  331. private void listAddAllDeduplicate(List<String> dataList, List<String> addList) {
  332. // 筛选出dataList中没有的数据
  333. List<String> filterList = addList.stream().filter(i -> !dataList.contains(i)).collect(Collectors.toList());
  334. dataList.addAll(filterList);
  335. }
  336. /**
  337. * 一次性把所有的字典都翻译了
  338. * 1. 所有的普通数据字典的所有数据只执行一次SQL
  339. * 2. 表字典相同的所有数据只执行一次SQL
  340. * @param dataListMap
  341. * @return
  342. */
  343. private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) {
  344. // 翻译后的字典文本,key=dictCode
  345. Map<String, List<DictModel>> translText = new HashMap<>(5);
  346. // 需要翻译的数据(有些可以从redis缓存中获取,就不走数据库查询)
  347. List<String> needTranslData = new ArrayList<>();
  348. //step.1 先通过redis中获取缓存字典数据
  349. for (String dictCode : dataListMap.keySet()) {
  350. List<String> dataList = dataListMap.get(dictCode);
  351. if (dataList.size() == 0) {
  352. continue;
  353. }
  354. // 表字典需要翻译的数据
  355. List<String> needTranslDataTable = new ArrayList<>();
  356. for (String s : dataList) {
  357. String data = s.trim();
  358. if (data.length() == 0) {
  359. continue; //跳过循环
  360. }
  361. if (dictCode.contains(",")) {
  362. String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, data);
  363. if (redisTemplate.hasKey(keyString)) {
  364. try {
  365. String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  366. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  367. list.add(new DictModel(data, text));
  368. } catch (Exception e) {
  369. log.warn(e.getMessage());
  370. }
  371. } else if (!needTranslDataTable.contains(data)) {
  372. // 去重添加
  373. needTranslDataTable.add(data);
  374. }
  375. } else {
  376. String keyString = String.format("sys:cache:dict::%s:%s", dictCode, data);
  377. if (redisTemplate.hasKey(keyString)) {
  378. try {
  379. String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  380. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  381. list.add(new DictModel(data, text));
  382. } catch (Exception e) {
  383. log.warn(e.getMessage());
  384. }
  385. } else if (!needTranslData.contains(data)) {
  386. // 去重添加
  387. needTranslData.add(data);
  388. }
  389. }
  390. }
  391. //step.2 调用数据库翻译表字典
  392. if (needTranslDataTable.size() > 0) {
  393. String[] arr = dictCode.split(",");
  394. String table = arr[0], text = arr[1], code = arr[2];
  395. String values = String.join(",", needTranslDataTable);
  396. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  397. // 自定义的数据源
  398. String dataSource = null;
  399. if (arr.length > 3) {
  400. dataSource = arr[3];
  401. }
  402. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  403. log.debug("translateDictFromTableByKeys.dictCode:" + dictCode);
  404. log.debug("translateDictFromTableByKeys.values:" + values);
  405. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  406. //update-begin---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串---
  407. if(null == dataSource){
  408. dataSource = "";
  409. }
  410. //update-end---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串---
  411. List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values, dataSource);
  412. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  413. log.debug("translateDictFromTableByKeys.result:" + texts);
  414. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  415. list.addAll(texts);
  416. // 做 redis 缓存
  417. for (DictModel dict : texts) {
  418. String redisKey = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, dict.getValue());
  419. try {
  420. // update-begin-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061
  421. // 保留5分钟
  422. redisTemplate.opsForValue().set(redisKey, dict.getText(), 300, TimeUnit.SECONDS);
  423. // update-end-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061
  424. } catch (Exception e) {
  425. log.warn(e.getMessage(), e);
  426. }
  427. }
  428. }
  429. }
  430. //step.3 调用数据库进行翻译普通字典
  431. if (needTranslData.size() > 0) {
  432. List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
  433. // 将不包含逗号的字典code筛选出来,因为带逗号的是表字典,而不是普通的数据字典
  434. List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList());
  435. String dictCodes = String.join(",", filterDictCodes);
  436. String values = String.join(",", needTranslData);
  437. log.debug("translateManyDict.dictCodes:" + dictCodes);
  438. log.debug("translateManyDict.values:" + values);
  439. Map<String, List<DictModel>> manyDict = commonApi.translateManyDict(dictCodes, values);
  440. log.debug("translateManyDict.result:" + manyDict);
  441. for (String dictCode : manyDict.keySet()) {
  442. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  443. List<DictModel> newList = manyDict.get(dictCode);
  444. list.addAll(newList);
  445. // 做 redis 缓存
  446. for (DictModel dict : newList) {
  447. String redisKey = String.format("sys:cache:dict::%s:%s", dictCode, dict.getValue());
  448. try {
  449. redisTemplate.opsForValue().set(redisKey, dict.getText());
  450. } catch (Exception e) {
  451. log.warn(e.getMessage(), e);
  452. }
  453. }
  454. }
  455. }
  456. return translText;
  457. }
  458. /**
  459. * 字典值替换文本
  460. *
  461. * @param dictModels
  462. * @param values
  463. * @return
  464. */
  465. private String translDictText(List<DictModel> dictModels, String values) {
  466. List<String> result = new ArrayList<>();
  467. // 允许多个逗号分隔,允许传数组对象
  468. String[] splitVal = values.split(",");
  469. for (String val : splitVal) {
  470. String dictText = val;
  471. for (DictModel dict : dictModels) {
  472. if (val.equals(dict.getValue())) {
  473. dictText = dict.getText();
  474. break;
  475. }
  476. }
  477. result.add(dictText);
  478. }
  479. return String.join(",", result);
  480. }
  481. /**
  482. * 翻译字典文本
  483. * @param code
  484. * @param text
  485. * @param table
  486. * @param key
  487. * @return
  488. */
  489. @Deprecated
  490. private String translateDictValue(String code, String text, String table, String key) {
  491. if(oConvertUtils.isEmpty(key)) {
  492. return null;
  493. }
  494. StringBuffer textValue=new StringBuffer();
  495. String[] keys = key.split(",");
  496. for (String k : keys) {
  497. String tmpValue = null;
  498. log.debug(" 字典 key : "+ k);
  499. if (k.trim().length() == 0) {
  500. continue; //跳过循环
  501. }
  502. //update-begin--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
  503. if (!StringUtils.isEmpty(table)){
  504. log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
  505. String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim());
  506. if (redisTemplate.hasKey(keyString)){
  507. try {
  508. tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  509. } catch (Exception e) {
  510. log.warn(e.getMessage());
  511. }
  512. }else {
  513. tmpValue= commonApi.translateDictFromTable(table,text,code,k.trim());
  514. }
  515. }else {
  516. String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim());
  517. if (redisTemplate.hasKey(keyString)){
  518. try {
  519. tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  520. } catch (Exception e) {
  521. log.warn(e.getMessage());
  522. }
  523. }else {
  524. tmpValue = commonApi.translateDict(code, k.trim());
  525. }
  526. }
  527. //update-end--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
  528. if (tmpValue != null) {
  529. if (!"".equals(textValue.toString())) {
  530. textValue.append(",");
  531. }
  532. textValue.append(tmpValue);
  533. }
  534. }
  535. return textValue.toString();
  536. }
  537. /**
  538. * 检测返回结果集中是否包含Dict注解
  539. * @param records
  540. * @return
  541. */
  542. private Boolean checkHasDict(List<Object> records){
  543. if(oConvertUtils.isNotEmpty(records) && records.size()>0){
  544. for (Field field : oConvertUtils.getAllFields(records.get(0))) {
  545. if (oConvertUtils.isNotEmpty(field.getAnnotation(Dict.class))) {
  546. return true;
  547. }
  548. }
  549. }
  550. return false;
  551. }
  552. }

八、涉及分布式的整体修改

  1. package org.jeecg.common.aspect;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.alibaba.fastjson.parser.Feature;
  4. import com.baomidou.mybatisplus.core.metadata.IPage;
  5. import com.fasterxml.jackson.core.JsonProcessingException;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.aspectj.lang.ProceedingJoinPoint;
  9. import org.aspectj.lang.annotation.Around;
  10. import org.aspectj.lang.annotation.Aspect;
  11. import org.aspectj.lang.annotation.Pointcut;
  12. import org.jeecg.common.api.CommonAPI;
  13. import org.jeecg.common.api.vo.Result;
  14. import org.jeecg.common.aspect.annotation.Dict;
  15. import org.jeecg.common.constant.CommonConstant;
  16. import org.jeecg.common.system.vo.DictModel;
  17. import org.jeecg.common.util.oConvertUtils;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.context.annotation.Lazy;
  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.lang.reflect.Method;
  25. import java.time.LocalDate;
  26. import java.time.LocalDateTime;
  27. import java.util.*;
  28. import java.util.concurrent.TimeUnit;
  29. import java.util.stream.Collectors;
  30. /**
  31. * @Description: 字典aop类
  32. * @Author: dangzhenghui
  33. * @Date: 2019-3-17 21:50
  34. * @Version: 1.0
  35. */
  36. @Aspect
  37. @Component
  38. @Slf4j
  39. public class DictAspect {
  40. @Lazy
  41. @Autowired
  42. private CommonAPI commonApi;
  43. @Autowired
  44. public RedisTemplate redisTemplate;
  45. @Autowired
  46. private ObjectMapper objectMapper;
  47. private static final String JAVA_UTIL_DATE = "java.util.Date";
  48. /**
  49. * 定义切点Pointcut
  50. */
  51. @Pointcut("(@within(org.springframework.web.bind.annotation.RestController) || " +
  52. "@within(org.springframework.stereotype.Controller) || @annotation(org.jeecg.common.aspect.annotation.AutoDict)) " +
  53. "&& execution(public org.jeecg.common.api.vo.Result org.jeecg..*.*(..))")
  54. public void excudeService() {
  55. }
  56. @Around("excudeService()")
  57. public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
  58. long time1=System.currentTimeMillis();
  59. Object result = pjp.proceed();
  60. long time2=System.currentTimeMillis();
  61. log.debug("获取JSON数据 耗时:"+(time2-time1)+"ms");
  62. long start=System.currentTimeMillis();
  63. result=this.parseDictText(result);
  64. long end=System.currentTimeMillis();
  65. log.debug("注入字典到JSON数据 耗时"+(end-start)+"ms");
  66. return result;
  67. }
  68. /**
  69. * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
  70. * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
  71. * 示例为SysUser 字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dictText形式返回到前端
  72. * 例输入当前返回值的就会多出一个sex_dictText字段
  73. * {
  74. * sex:1,
  75. * sex_dictText:"男"
  76. * }
  77. * 前端直接取值sext_dictText在table里面无需再进行前端的字典转换了
  78. * customRender:function (text) {
  79. * if(text==1){
  80. * return "男";
  81. * }else if(text==2){
  82. * return "女";
  83. * }else{
  84. * return text;
  85. * }
  86. * }
  87. * 目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
  88. * @param result
  89. */
  90. /*private Object parseDictText(Object result) {
  91. //if (result instanceof Result) {
  92. if (true) {
  93. if (((Result) result).getResult() instanceof IPage) {
  94. List<JSONObject> items = new ArrayList<>();
  95. //step.1 筛选出加了 Dict 注解的字段列表
  96. List<Field> dictFieldList = new ArrayList<>();
  97. // 字典数据列表, key = 字典code,value=数据列表
  98. Map<String, List<String>> dataListMap = new HashMap<>(5);
  99. //取出结果集
  100. List<Object> records=((IPage) ((Result) result).getResult()).getRecords();
  101. //update-begin--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  102. Boolean hasDict= checkHasDict(records);
  103. if(!hasDict){
  104. return result;
  105. }
  106. log.debug(" __ 进入字典翻译切面 DictAspect —— " );
  107. //update-end--Author:zyf -- Date:20220606 ----for:【VUEN-1230】 判断是否含有字典注解,没有注解返回-----
  108. for (Object record : records) {
  109. String json="{}";
  110. try {
  111. //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  112. //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
  113. json = objectMapper.writeValueAsString(record);
  114. //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  115. } catch (JsonProcessingException e) {
  116. log.error("json解析失败"+e.getMessage(),e);
  117. }
  118. //update-begin--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  119. JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
  120. //update-end--Author:scott -- Date:20211223 ----for:【issues/3303】restcontroller返回json数据后key顺序错乱 -----
  121. //update-begin--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  122. //for (Field field : record.getClass().getDeclaredFields()) {
  123. // 遍历所有字段,把字典Code取出来,放到 map 里
  124. for (Field field : oConvertUtils.getAllFields(record)) {
  125. String value = item.getString(field.getName());
  126. if (oConvertUtils.isEmpty(value)) {
  127. continue;
  128. }
  129. //update-end--Author:scott -- Date:20190603 ----for:解决继承实体字段无法翻译问题------
  130. if (field.getAnnotation(Dict.class) != null) {
  131. if (!dictFieldList.contains(field)) {
  132. dictFieldList.add(field);
  133. }
  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. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  138. String dataSource = field.getAnnotation(Dict.class).ds();
  139. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  140. List<String> dataList;
  141. String dictCode = code;
  142. if (!StringUtils.isEmpty(table)) {
  143. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  144. dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  145. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  146. }
  147. dataList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
  148. this.listAddAllDeduplicate(dataList, Arrays.asList(value.split(",")));
  149. }
  150. //date类型默认转换string格式化日期
  151. //update-begin--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  152. //if (JAVA_UTIL_DATE.equals(field.getType().getName())&&field.getAnnotation(JsonFormat.class)==null&&item.get(field.getName())!=null){
  153. //SimpleDateFormat aDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  154. // item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
  155. //}
  156. //update-end--Author:zyf -- Date:20220531 ----for:【issues/#3629】 DictAspect Jackson序列化报错-----
  157. }
  158. items.add(item);
  159. }
  160. //step.2 调用翻译方法,一次性翻译
  161. Map<String, List<DictModel>> translText = this.translateAllDict(dataListMap);
  162. //step.3 将翻译结果填充到返回结果里
  163. for (JSONObject record : items) {
  164. for (Field field : dictFieldList) {
  165. String code = field.getAnnotation(Dict.class).dicCode();
  166. String text = field.getAnnotation(Dict.class).dicText();
  167. String table = field.getAnnotation(Dict.class).dictTable();
  168. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  169. // 自定义的字典表数据源
  170. String dataSource = field.getAnnotation(Dict.class).ds();
  171. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  172. String fieldDictCode = code;
  173. if (!StringUtils.isEmpty(table)) {
  174. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  175. fieldDictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  176. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  177. }
  178. String value = record.getString(field.getName());
  179. if (oConvertUtils.isNotEmpty(value)) {
  180. List<DictModel> dictModels = translText.get(fieldDictCode);
  181. if(dictModels==null || dictModels.size()==0){
  182. continue;
  183. }
  184. String textValue = this.translDictText(dictModels, value);
  185. log.debug(" 字典Val : " + textValue);
  186. log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + ": " + textValue);
  187. // TODO-sun 测试输出,待删
  188. log.debug(" ---- dictCode: " + fieldDictCode);
  189. log.debug(" ---- value: " + value);
  190. log.debug(" ----- text: " + textValue);
  191. log.debug(" ---- dictModels: " + JSON.toJSONString(dictModels));
  192. record.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  193. }
  194. }
  195. }
  196. ((IPage) ((Result) result).getResult()).setRecords(items);
  197. }
  198. }
  199. return result;
  200. }*/
  201. private Object parseDictText(Object result) {
  202. if (result instanceof Result) {
  203. Result<?> resultObj = (Result<?>) result;
  204. Object data = resultObj.getResult();
  205. // 处理IPage类型
  206. if (data instanceof IPage) {
  207. handleIPage((IPage<?>) data);
  208. }
  209. // 新增:处理List类型
  210. else if (data instanceof List) {
  211. handleList((List<?>) data, resultObj);
  212. }
  213. // 新增:处理单个对象类型
  214. else if (data != null) {
  215. handleObject(data, resultObj);
  216. }
  217. }
  218. return result;
  219. }
  220. // 判断是否为简单类型(无需字典处理的类型)
  221. private boolean isSimpleType(Class<?> clazz) {
  222. return clazz.isPrimitive()
  223. || clazz == String.class
  224. || Number.class.isAssignableFrom(clazz)
  225. || clazz == Boolean.class
  226. || clazz == Date.class
  227. || clazz == LocalDate.class
  228. || clazz == LocalDateTime.class;
  229. }
  230. private void handleObject(Object data, Result<?> resultObj) {
  231. if (data == null) {
  232. return;
  233. }
  234. // 新增:判断是否为简单类型(非对象/非集合),直接跳过
  235. if (isSimpleType(data.getClass())) {
  236. log.debug("跳过简单类型[{}]的字典处理", data.getClass().getSimpleName());
  237. return;
  238. }
  239. if (data instanceof String) {
  240. log.debug("跳过字符串类型结果的字典处理,内容:{}", data.toString().length() > 100 ? data.toString().substring(0, 100) + "..." : data);
  241. return;
  242. }
  243. // 转换对象为JSONObject进行处理
  244. JSONObject jsonObject;
  245. try {
  246. String jsonStr = objectMapper.writeValueAsString(data);
  247. log.info("jsonStr:"+jsonStr);
  248. // 移除JSON中的控制字符(可选,进一步避免解析错误)
  249. jsonStr = jsonStr.replaceAll("[\\x00-\\x1F\\x7F]", "");
  250. jsonObject = JSONObject.parseObject(jsonStr, Feature.OrderedField);
  251. } catch (JsonProcessingException e) {
  252. log.error("对象转JSON失败,跳过字典处理", e);
  253. return; // 解析失败时直接返回原始对象,不进行字典处理
  254. }
  255. // 处理对象中的字典字段
  256. List<Field> dictFieldList = new ArrayList<>();
  257. Map<String, List<String>> dataListMap = new HashMap<>(5);
  258. // 收集对象中所有需要翻译的字典字段
  259. for (Field field : oConvertUtils.getAllFields(data)) {
  260. String fieldValue = jsonObject.getString(field.getName());
  261. if (oConvertUtils.isEmpty(fieldValue)) {
  262. continue;
  263. }
  264. Dict dictAnnotation = field.getAnnotation(Dict.class);
  265. if (dictAnnotation != null) {
  266. dictFieldList.add(field);
  267. // 构建字典code
  268. String code = dictAnnotation.dicCode();
  269. String text = dictAnnotation.dicText();
  270. String table = dictAnnotation.dictTable();
  271. String dataSource = dictAnnotation.ds();
  272. String dictCode = code;
  273. if (!StringUtils.isEmpty(table)) {
  274. dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  275. }
  276. // 收集需要翻译的值
  277. List<String> valueList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
  278. listAddAllDeduplicate(valueList, Arrays.asList(fieldValue.split(",")));
  279. }
  280. }
  281. // 如果没有字典字段,直接返回
  282. if (dictFieldList.isEmpty()) {
  283. return;
  284. }
  285. // 批量查询字典值
  286. Map<String, List<DictModel>> translText = translateAllDict(dataListMap);
  287. // 将字典文本填充到JSONObject
  288. for (Field field : dictFieldList) {
  289. Dict dictAnnotation = field.getAnnotation(Dict.class);
  290. String code = dictAnnotation.dicCode();
  291. String text = dictAnnotation.dicText();
  292. String table = dictAnnotation.dictTable();
  293. String dataSource = dictAnnotation.ds();
  294. String dictCode = code;
  295. if (!StringUtils.isEmpty(table)) {
  296. dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  297. }
  298. String fieldValue = jsonObject.getString(field.getName());
  299. if (oConvertUtils.isEmpty(fieldValue)) {
  300. continue;
  301. }
  302. List<DictModel> dictModels = translText.get(dictCode);
  303. if (dictModels == null || dictModels.isEmpty()) {
  304. continue;
  305. }
  306. String textValue = translDictText(dictModels, fieldValue);
  307. jsonObject.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  308. }
  309. // 将处理后的JSONObject转换回原始对象类型
  310. Object processedObject = convertToOriginalType(jsonObject, data.getClass());
  311. // 使用反射设置结果
  312. try {
  313. Method setResultMethod = resultObj.getClass().getMethod("setResult", Object.class);
  314. setResultMethod.invoke(resultObj, processedObject);
  315. } catch (Exception e) {
  316. log.error("设置结果失败", e);
  317. }
  318. }
  319. /**
  320. * 将JSONObject转换为原始对象类型
  321. */
  322. private Object convertToOriginalType(JSONObject jsonObject, Class<?> originalType) {
  323. try {
  324. return objectMapper.treeToValue(objectMapper.readTree(jsonObject.toJSONString()), originalType);
  325. } catch (JsonProcessingException e) {
  326. log.error("转换回原始类型失败", e);
  327. return jsonObject; // 转换失败时返回JSONObject
  328. }
  329. }
  330. /**
  331. * 处理记录列表(支持IPage的records和普通List)
  332. */
  333. private List<JSONObject> processRecords(List<?> records) {
  334. // 步骤1:检查是否包含@Dict注解字段,无则直接返回
  335. Boolean hasDict = checkHasDict(records);
  336. if (!hasDict) {
  337. return records.stream()
  338. .map(record -> {
  339. try {
  340. // return JSONObject.parseObject(objectMapper.writeValueAsString(record), Feature.OrderedField);
  341. String jsonStr;
  342. // 对字符串类型直接处理,避免额外引号
  343. if (record instanceof String) {
  344. String str = (String) record;
  345. // 移除控制字符
  346. str = str.replaceAll("[\\x00-\\x1F\\x7F]", "");
  347. // 包装为JSON对象(键为"value",值为处理后的字符串)
  348. JSONObject json = new JSONObject();
  349. json.put("value", str);
  350. return json;
  351. } else {
  352. // 非字符串类型正常转换并移除控制字符
  353. jsonStr = objectMapper.writeValueAsString(record);
  354. jsonStr = jsonStr.replaceAll("[\\x00-\\x1F\\x7F]", "");
  355. return JSONObject.parseObject(jsonStr, Feature.OrderedField);
  356. }
  357. } catch (JsonProcessingException e) {
  358. log.error("对象转JSON失败", e);
  359. return new JSONObject();
  360. }
  361. })
  362. .collect(Collectors.toList());
  363. }
  364. log.debug("__ 进入字典翻译切面(处理List/IPage) __");
  365. // 步骤2:收集需要翻译的字典信息
  366. List<JSONObject> items = new ArrayList<>();
  367. List<Field> dictFieldList = new ArrayList<>(); // 含@Dict注解的字段
  368. Map<String, List<String>> dataListMap = new HashMap<>(5); // key:字典code,value:需要翻译的字段值列表
  369. for (Object record : records) {
  370. // 将对象转为有序JSONObject(保持字段顺序)
  371. String json;
  372. try {
  373. json = objectMapper.writeValueAsString(record);
  374. } catch (JsonProcessingException e) {
  375. log.error("json解析失败", e);
  376. continue;
  377. }
  378. JSONObject item = JSONObject.parseObject(json, Feature.OrderedField);
  379. // 遍历所有字段(含父类字段),收集字典信息
  380. for (Field field : oConvertUtils.getAllFields(record)) {
  381. String fieldValue = item.getString(field.getName());
  382. if (oConvertUtils.isEmpty(fieldValue)) {
  383. continue;
  384. }
  385. Dict dictAnnotation = field.getAnnotation(Dict.class);
  386. if (dictAnnotation != null) {
  387. // 收集含@Dict注解的字段
  388. if (!dictFieldList.contains(field)) {
  389. dictFieldList.add(field);
  390. }
  391. // 构建字典code(区分普通字典和表字典)
  392. String code = dictAnnotation.dicCode();
  393. String text = dictAnnotation.dicText();
  394. String table = dictAnnotation.dictTable();
  395. String dataSource = dictAnnotation.ds(); // 数据源(分布式场景)
  396. String dictCode = code;
  397. if (!StringUtils.isEmpty(table)) {
  398. dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  399. }
  400. // 收集该字典code对应的所有需要翻译的值(去重)
  401. List<String> valueList = dataListMap.computeIfAbsent(dictCode, k -> new ArrayList<>());
  402. List<String> splitValues = Arrays.stream(fieldValue.split(","))
  403. .map(String::trim)
  404. .filter(v -> !v.isEmpty())
  405. .collect(Collectors.toList());
  406. listAddAllDeduplicate(valueList, splitValues);
  407. }
  408. }
  409. items.add(item);
  410. }
  411. // 步骤3:批量查询所有字典值(复用现有逻辑)
  412. Map<String, List<DictModel>> translText = translateAllDict(dataListMap);
  413. // 步骤4:将字典文本填充到结果中(添加xxx_dictText字段)
  414. for (JSONObject item : items) {
  415. for (Field field : dictFieldList) {
  416. Dict dictAnnotation = field.getAnnotation(Dict.class);
  417. String code = dictAnnotation.dicCode();
  418. String text = dictAnnotation.dicText();
  419. String table = dictAnnotation.dictTable();
  420. String dataSource = dictAnnotation.ds();
  421. String dictCode = code;
  422. if (!StringUtils.isEmpty(table)) {
  423. dictCode = String.format("%s,%s,%s,%s", table, text, code, dataSource);
  424. }
  425. String fieldValue = item.getString(field.getName());
  426. if (oConvertUtils.isEmpty(fieldValue)) {
  427. continue;
  428. }
  429. // 从翻译结果中获取文本
  430. List<DictModel> dictModels = translText.get(dictCode);
  431. if (dictModels == null || dictModels.isEmpty()) {
  432. continue;
  433. }
  434. String textValue = translDictText(dictModels, fieldValue);
  435. // 添加xxx_dictText字段
  436. item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
  437. }
  438. }
  439. return items;
  440. }
  441. /**
  442. * 处理IPage类型结果
  443. */
  444. /**
  445. * 处理IPage类型结果
  446. */
  447. private void handleIPage(IPage<?> page) {
  448. List<?> records = page.getRecords();
  449. if (oConvertUtils.isEmpty(records)) {
  450. return;
  451. }
  452. // 处理记录并获取JSONObject列表
  453. List<JSONObject> processedRecords = processRecords(records);
  454. // 如果列表不为空,尝试转换回原始类型
  455. if (!processedRecords.isEmpty() && records.size() > 0) {
  456. Class<?> originalType = records.get(0).getClass();
  457. List<Object> convertedRecords = processedRecords.stream()
  458. .map(json -> {
  459. try {
  460. // 将JSONObject转换回原始对象类型
  461. return objectMapper.treeToValue(objectMapper.readTree(json.toJSONString()), originalType);
  462. } catch (JsonProcessingException e) {
  463. log.error("转换JSONObject回原始类型失败", e);
  464. return json; // 转换失败时保留JSONObject
  465. }
  466. })
  467. .collect(Collectors.toList());
  468. // 使用反射调用setRecords方法(绕过泛型检查)
  469. try {
  470. Method setRecordsMethod = page.getClass().getMethod("setRecords", List.class);
  471. setRecordsMethod.invoke(page, processedRecords);
  472. } catch (Exception e) {
  473. log.error("调用setRecords方法失败", e);
  474. }
  475. }
  476. }
  477. /**
  478. * 处理List类型结果
  479. */
  480. private void handleList(List<?> records, Result<?> resultObj) {
  481. if (oConvertUtils.isEmpty(records)) {
  482. return;
  483. }
  484. // 转换为List<Object>(避免泛型问题)
  485. List<Object> recordList = records.stream().map(r -> (Object) r).collect(Collectors.toList());
  486. List<JSONObject> processedRecords = processRecords(recordList);
  487. // 使用反射设置结果,绕过泛型检查
  488. try {
  489. Method setResultMethod = resultObj.getClass().getMethod("setResult", Object.class);
  490. setResultMethod.invoke(resultObj, processedRecords);
  491. } catch (Exception e) {
  492. log.error("设置结果失败", e);
  493. }
  494. }
  495. /**
  496. * list 去重添加
  497. */
  498. private void listAddAllDeduplicate(List<String> dataList, List<String> addList) {
  499. // 筛选出dataList中没有的数据
  500. List<String> filterList = addList.stream().filter(i -> !dataList.contains(i)).collect(Collectors.toList());
  501. dataList.addAll(filterList);
  502. }
  503. /**
  504. * 一次性把所有的字典都翻译了
  505. * 1. 所有的普通数据字典的所有数据只执行一次SQL
  506. * 2. 表字典相同的所有数据只执行一次SQL
  507. * @param dataListMap
  508. * @return
  509. */
  510. private Map<String, List<DictModel>> translateAllDict(Map<String, List<String>> dataListMap) {
  511. // 翻译后的字典文本,key=dictCode
  512. Map<String, List<DictModel>> translText = new HashMap<>(5);
  513. // 需要翻译的数据(有些可以从redis缓存中获取,就不走数据库查询)
  514. List<String> needTranslData = new ArrayList<>();
  515. //step.1 先通过redis中获取缓存字典数据
  516. for (String dictCode : dataListMap.keySet()) {
  517. List<String> dataList = dataListMap.get(dictCode);
  518. if (dataList.size() == 0) {
  519. continue;
  520. }
  521. // 表字典需要翻译的数据
  522. List<String> needTranslDataTable = new ArrayList<>();
  523. for (String s : dataList) {
  524. String data = s.trim();
  525. if (data.length() == 0) {
  526. continue; //跳过循环
  527. }
  528. if (dictCode.contains(",")) {
  529. String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, data);
  530. if (redisTemplate.hasKey(keyString)) {
  531. try {
  532. String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  533. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  534. list.add(new DictModel(data, text));
  535. } catch (Exception e) {
  536. log.warn(e.getMessage());
  537. }
  538. } else if (!needTranslDataTable.contains(data)) {
  539. // 去重添加
  540. needTranslDataTable.add(data);
  541. }
  542. } else {
  543. String keyString = String.format("sys:cache:dict::%s:%s", dictCode, data);
  544. if (redisTemplate.hasKey(keyString)) {
  545. try {
  546. String text = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  547. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  548. list.add(new DictModel(data, text));
  549. } catch (Exception e) {
  550. log.warn(e.getMessage());
  551. }
  552. } else if (!needTranslData.contains(data)) {
  553. // 去重添加
  554. needTranslData.add(data);
  555. }
  556. }
  557. }
  558. //step.2 调用数据库翻译表字典
  559. if (needTranslDataTable.size() > 0) {
  560. String[] arr = dictCode.split(",");
  561. String table = arr[0], text = arr[1], code = arr[2];
  562. String values = String.join(",", needTranslDataTable);
  563. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  564. // 自定义的数据源
  565. String dataSource = null;
  566. if (arr.length > 3) {
  567. dataSource = arr[3];
  568. }
  569. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  570. log.debug("translateDictFromTableByKeys.dictCode:" + dictCode);
  571. log.debug("translateDictFromTableByKeys.values:" + values);
  572. //update-begin---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  573. //update-begin---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串---
  574. if(null == dataSource){
  575. dataSource = "";
  576. }
  577. //update-end---author:wangshuai---date:2024-01-09---for:微服务下为空报错没有参数需要传递空字符串---
  578. List<DictModel> texts = commonApi.translateDictFromTableByKeys(table, text, code, values, dataSource);
  579. //update-end---author:chenrui ---date:20231221 for:[issues/#5643]解决分布式下表字典跨库无法查询问题------------
  580. log.debug("translateDictFromTableByKeys.result:" + texts);
  581. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  582. list.addAll(texts);
  583. // 做 redis 缓存
  584. for (DictModel dict : texts) {
  585. String redisKey = String.format("sys:cache:dictTable::SimpleKey [%s,%s]", dictCode, dict.getValue());
  586. try {
  587. // update-begin-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061
  588. // 保留5分钟
  589. redisTemplate.opsForValue().set(redisKey, dict.getText(), 300, TimeUnit.SECONDS);
  590. // update-end-author:taoyan date:20211012 for: 字典表翻译注解缓存未更新 issues/3061
  591. } catch (Exception e) {
  592. log.warn(e.getMessage(), e);
  593. }
  594. }
  595. }
  596. }
  597. //step.3 调用数据库进行翻译普通字典
  598. if (needTranslData.size() > 0) {
  599. List<String> dictCodeList = Arrays.asList(dataListMap.keySet().toArray(new String[]{}));
  600. // 将不包含逗号的字典code筛选出来,因为带逗号的是表字典,而不是普通的数据字典
  601. List<String> filterDictCodes = dictCodeList.stream().filter(key -> !key.contains(",")).collect(Collectors.toList());
  602. String dictCodes = String.join(",", filterDictCodes);
  603. String values = String.join(",", needTranslData);
  604. log.debug("translateManyDict.dictCodes:" + dictCodes);
  605. log.debug("translateManyDict.values:" + values);
  606. Map<String, List<DictModel>> manyDict = commonApi.translateManyDict(dictCodes, values);
  607. log.debug("translateManyDict.result:" + manyDict);
  608. for (String dictCode : manyDict.keySet()) {
  609. List<DictModel> list = translText.computeIfAbsent(dictCode, k -> new ArrayList<>());
  610. List<DictModel> newList = manyDict.get(dictCode);
  611. list.addAll(newList);
  612. // 做 redis 缓存
  613. for (DictModel dict : newList) {
  614. String redisKey = String.format("sys:cache:dict::%s:%s", dictCode, dict.getValue());
  615. try {
  616. redisTemplate.opsForValue().set(redisKey, dict.getText());
  617. } catch (Exception e) {
  618. log.warn(e.getMessage(), e);
  619. }
  620. }
  621. }
  622. }
  623. return translText;
  624. }
  625. /**
  626. * 字典值替换文本
  627. *
  628. * @param dictModels
  629. * @param values
  630. * @return
  631. */
  632. private String translDictText(List<DictModel> dictModels, String values) {
  633. List<String> result = new ArrayList<>();
  634. // 允许多个逗号分隔,允许传数组对象
  635. String[] splitVal = values.split(",");
  636. for (String val : splitVal) {
  637. String dictText = val;
  638. for (DictModel dict : dictModels) {
  639. if (val.equals(dict.getValue())) {
  640. dictText = dict.getText();
  641. break;
  642. }
  643. }
  644. result.add(dictText);
  645. }
  646. return String.join(",", result);
  647. }
  648. /**
  649. * 翻译字典文本
  650. * @param code
  651. * @param text
  652. * @param table
  653. * @param key
  654. * @return
  655. */
  656. @Deprecated
  657. private String translateDictValue(String code, String text, String table, String key) {
  658. if(oConvertUtils.isEmpty(key)) {
  659. return null;
  660. }
  661. StringBuffer textValue=new StringBuffer();
  662. String[] keys = key.split(",");
  663. for (String k : keys) {
  664. String tmpValue = null;
  665. log.debug(" 字典 key : "+ k);
  666. if (k.trim().length() == 0) {
  667. continue; //跳过循环
  668. }
  669. //update-begin--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
  670. if (!StringUtils.isEmpty(table)){
  671. log.debug("--DictAspect------dicTable="+ table+" ,dicText= "+text+" ,dicCode="+code);
  672. String keyString = String.format("sys:cache:dictTable::SimpleKey [%s,%s,%s,%s]",table,text,code,k.trim());
  673. if (redisTemplate.hasKey(keyString)){
  674. try {
  675. tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  676. } catch (Exception e) {
  677. log.warn(e.getMessage());
  678. }
  679. }else {
  680. tmpValue= commonApi.translateDictFromTable(table,text,code,k.trim());
  681. }
  682. }else {
  683. String keyString = String.format("sys:cache:dict::%s:%s",code,k.trim());
  684. if (redisTemplate.hasKey(keyString)){
  685. try {
  686. tmpValue = oConvertUtils.getString(redisTemplate.opsForValue().get(keyString));
  687. } catch (Exception e) {
  688. log.warn(e.getMessage());
  689. }
  690. }else {
  691. tmpValue = commonApi.translateDict(code, k.trim());
  692. }
  693. }
  694. //update-end--Author:scott -- Date:20210531 ----for: !56 优化微服务应用下存在表字段需要字典翻译时加载缓慢问题-----
  695. if (tmpValue != null) {
  696. if (!"".equals(textValue.toString())) {
  697. textValue.append(",");
  698. }
  699. textValue.append(tmpValue);
  700. }
  701. }
  702. return textValue.toString();
  703. }
  704. /**
  705. * 检测返回结果集中是否包含Dict注解
  706. * @param records
  707. * @return
  708. */
  709. private Boolean checkHasDict(List<?> records){
  710. if(oConvertUtils.isNotEmpty(records) && records.size()>0){
  711. for (Field field : oConvertUtils.getAllFields(records.get(0))) {
  712. if (oConvertUtils.isNotEmpty(field.getAnnotation(Dict.class))) {
  713. return true;
  714. }
  715. }
  716. }
  717. return false;
  718. }
  719. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注