huayandong

跑课项目重构;

  1 +#获取课程的听力时长和短句数
  2 +
  3 +##接口
  4 +遍历文件夹下所有的excel,获得课的短句数,视频的长度,音频的长度:
  5 + 访问例子:192.168.0.111:8090/single/config/number
  6 + 访问方式:GET
  7 + 访问参数:无
  8 +根据数据表中的课程id,来获得课中的短句数和听力时长:
  9 + 访问例子:192.168.0.111:8090/single/config/number/two
  10 + 访问方式:GET
  11 + 访问参数:无
  12 +通过excel的id得到课中"单词释意"的值
  13 + 访问例子:192.168.0.111:8090/single//run/words/{lessonId}
  14 + 访问方式:GET
  15 + 访问参数:lessonId 课程的id,String类型
  16 +
  17 +
  18 +1.短句数是excel表中“图片英文”的字段数:在解析excel时,遍历excel中的每一个sheet页和每一个sheet页下面的所有包含“图片英文”的字段,为了避免计算重复的短句数,在得到所有的“图片英文”的值后,将这些值存放到HashSet集合中,最后得到集合的大小为该课程的短句数;
  19 +//获取excel中短句数的方法
  20 +public static Integer count(Map<String, Table<Integer, String, String>> map, File file, String catalogId) {
  21 + int count = 0;
  22 + Set<String> djSet = new HashSet<>();
  23 + for (Map.Entry<String, Table<Integer, String, String>> entity : map.entrySet()) {
  24 + Table<Integer, String, String> table = entity.getValue();
  25 +
  26 + Map<Integer, String> djColumn = table.column("图片英文");
  27 + for (Map.Entry<Integer, String> djEntity : djColumn.entrySet()) {
  28 + String djName = djEntity.getValue();
  29 + djSet.add(djName);
  30 + }
  31 + }
  32 + count = djSet.size();
  33 + if (count == 0) {
  34 + logger.error("课中没有短句! 课的名字为:[{}], 课的id是:[{}], 课中短句书为:[{}]", file.getName(), catalogId, count);
  35 + } else {
  36 + logger.info("课中有短句!课的名字为:[{}], 课的id是:[{}], 课中短句书为:[{}]", file.getName(), catalogId, count);
  37 + }
  38 + return count;
  39 +}
  40 +
  41 +2.课程中的听力时长为excel表中视频的长度+音频的长度:在VideoDuration类countVideoDuration方法中,遍历excel表中所有的sheet页和sheet页下所有的包含“视频”的字段,得到map集合,遍历该集合,得到每个视频的名称,通过调用rms资源管理平台提供的接口,定义FileEntity对象,给对象赋值资源类型restType、资源搜索目录dataMayKey、资源名称resName、资源前缀prefix,调用接口中的downLoadResource方法,得到FileEntity对象,并获得视频时长,将所有的视频时长加在一起,就可以得到该excel的视频总时长;
  42 +//跑书的时候计算出书中所有音频的时长
  43 +public static Long countAudioDuration(Map<String, Table<Integer, String, String>> bookMap) {
  44 + Long totalDuration = 0L;
  45 + for (Map.Entry<String, Table<Integer, String, String>> entity : bookMap.entrySet()) {
  46 + Table<Integer, String, String> table = entity.getValue(); //遍历sheet页,得到每页的table
  47 + Set<String> columnKeySet = table.columnKeySet(); //table中,获得列的集合
  48 +
  49 + for (String column : columnKeySet) { //遍历列的集合,得到每一个列的名称
  50 + if (column.contains("音频")) {
  51 +
  52 + Map<Integer, String> columnMap = table.column(column);
  53 + for (Map.Entry<Integer, String> entries : columnMap.entrySet()) {
  54 + String audioName = entries.getValue();
  55 +
  56 + FileEntity fileEntity = new FileEntity(); //创建FileEntity对象
  57 + fileEntity.setResType("audio"); //设置资源类型
  58 + fileEntity.setDataMapKey("default"); //设置资源映射
  59 + fileEntity.setResName(audioName); //设置资源前缀
  60 + fileEntity.setPrefix("audio"); // 设置前缀
  61 +
  62 + FileEntity audioFileEntity = rmiClient.downLoadResource(fileEntity);
  63 + if (audioFileEntity != null) {
  64 + String audioDuration = audioFileEntity.getDuration();
  65 + //计算音频的总时长
  66 + if (StringUtils.isNotBlank(audioDuration)) {
  67 + Long audioLong = Long.valueOf(audioDuration);
  68 + totalDuration += audioLong;
  69 + } else {
  70 + totalDuration += 0L;
  71 + }
  72 + } else {
  73 + logger.error("资源管理平台上没有找到[{}]的音频", audioName);
  74 + }
  75 + }
  76 + }
  77 + }
  78 + }
  79 + logger.info("音频总时长为:[{}]", totalDuration);
  80 + return totalDuration;
  81 +}
  82 +
  83 +3.类似,在AudioDuration类中countAudioDuration方法,在遍历excel表的时候,获得表中所有sheet页中包含“音频”字段的map集合,遍历集合,获得每个音频的name值,调用rms资源管理项目中提供的接口,获得每个音频的时长,将所有的音频时长统计加在一起,就可以得到该excel的音频总时长;
  84 +
  85 +4.将得到的音频总时长和视频总时长相加,得到的就是该课的听力时长;
  86 +
  87 +5.配置第二数据源,将课程的听力时长和课程的短句数保存到数据库中,在向数据库保存的操作中,由于需要保存的数据库与jpa框架配置的数据库不是同一个数据库,在向数据库保存的时需要使用第二数据源完成数据的更新和保存操作;在cn.boxfish.onekey.count.jpa.DataSourceConfig类中,通过注解的方式定义第一数据源“primaryDataSource”和第二数据源“secondaryDataSource”,在spring boot的配置文件中,指定两个数据源连接不同的数据库;
  88 +//定义多数据源
  89 +@Configuration
  90 +@EnableConfigurationProperties
  91 +@EnableAutoConfiguration
  92 +public class DataSourceConfig {
  93 +
  94 + @Bean(name = "primaryDataSource")
  95 + @Primary
  96 + @ConfigurationProperties(prefix = "spring.datasource.primary")
  97 + public DataSource primaryDataSource() {
  98 + return DataSourceBuilder.create().build();
  99 + }
  100 +
  101 + @Bean(name = "secondaryDataSource")
  102 + @ConfigurationProperties(prefix = "spring.datasource.secondary")
  103 + public DataSource secondaryDataSource() {
  104 + return DataSourceBuilder.create().build();
  105 + }
  106 +}
  107 +
  108 +//在配置文件中,为不同的数据源指定不同的数据库
  109 +spring:
  110 + profiles: development
  111 + datasource:
  112 + primary:
  113 + url: jdbc:mysql://192.168.0.100:3306/bebase?useUnicode=true&characterEncoding=utf8
  114 + username: bebase
  115 + password: boxfish
  116 + secondary:
  117 + url: jdbc:mysql://192.168.0.100:3306/statistic?useUnicode=true&characterEncoding=utf8
  118 + username: bebase
  119 + password: boxfish
  120 +
  121 +在CountDao类中完成对数据的更新和保存,在使用之前,先指定使用第二数据源,在对数据的操作的时候,不能再使用jpa框架提供的方法,在对数据的保存中,采用的DBUtils完成对数据库的更新和保存;
  122 +//第二数据源的使用
  123 +@Named
  124 +public class CountDao {
  125 + QueryRunner queryRunner = new QueryRunner();
  126 + private final Logger logger = LoggerFactory.getLogger(CountDao.class);
  127 +
  128 + @Inject
  129 + @Resource(name = "secondaryDataSource")
  130 + DataSource dataSource;
  131 +
  132 + //更新数据库中的听力时长和短句数
  133 + public void updateLessonVersion(Integer clauseSize, Long listeningDuration, String lessonId) {
  134 + try (Connection conn = dataSource.getConnection()) {
  135 + String sql = "UPDATE nlp_lesson_version lv SET lv.phrase_count = ? ,lv.listening_duration = ? WHERE lv.lesson_id = ? ";
  136 + queryRunner.update(conn, sql, clauseSize, listeningDuration, lessonId);
  137 + } catch (SQLException e) {
  138 + logger.error("更新数据库出现异常:[{}}", e);
  139 + e.printStackTrace();
  140 + }
  141 + }
  142 +
  143 + //根据课程ID查询对象
  144 + public List<LessonVersion> findEntityByLessonId(String lessonId) {
  145 + try (Connection conn = dataSource.getConnection()) {
  146 + List<LessonVersion> list = new ArrayList<>();
  147 + String sql = "SELECT id ,lesson_id AS lessonId ,phrase_count AS clauseCount ,listening_duration listeningDuration FROM nlp_lesson_version WHERE lesson_id = ? ";
  148 + Map<Integer, LessonVersion> result = queryRunner.query(conn, sql, new BeanMapHandler<Integer, LessonVersion>(LessonVersion.class), lessonId);
  149 + for (Map.Entry<Integer, LessonVersion> entity : result.entrySet()) {
  150 + LessonVersion lessonVersion = entity.getValue();
  151 + if (lessonVersion != null) {
  152 + list.add(lessonVersion);
  153 + }
  154 + }
  155 + return list;
  156 + } catch (SQLException e) {
  157 + logger.error("查询数据库出现异常:[{}}", e);
  158 + e.printStackTrace();
  159 + }
  160 + return null;
  161 + }
  162 +}
  163 +
  164 +6.在跑课的代码中,每跑一课需要计算出课程的短句数和听力时长,在跑课代码中,调用获得短句数、音频时长和视频时长的方法,将获得的短句数和听力时长传入到nlp接口中,增加nlp接口中的参数,调用nlp接口中的方法,完成数据的保存操作;
  165 + //跑课时获得听力时长的短句书,调用nlp保存
  166 + //获得课的短句数
  167 + Integer phraseCount = CalculCount.count(workbook, excel.toFile(), index.getId());
  168 + //获得课中音频时长
  169 + Long audioDuration = AudioDuration.countAudioDuration(workbook);
  170 + //获得课中视频时长
  171 + Long videoDuration = VideoDuration.countVideoDuration(workbook);
  172 + //听力时长
  173 + Long listeningDuration = audioDuration + videoDuration;
  174 + // 校验课程是否已经跑目录
  175 + checkCourse(index.getId());
  176 + log.info("NLP数据获取-学生版: id:[{}]", index.getId());
  177 + try {
  178 + nlpHandler.saveNlpArticle(index.getId(), "student",phraseCount,listeningDuration);
  179 + } catch (Exception e) {
  180 + log.error("NLP数据获取出错-学生版: id:[{}],错误:{{}}", index.getId(), e);
  181 + }
  182 +
  183 + //nlp接口中增加听力时长和短句数的参数
  184 + public void saveNlpArticle(String lessonId, String type,Integer phraseCount,Long listeningDuration){
  185 + restTemplate.postForEntity(
  186 + nlpUrl.replace("::lessonId",lessonId)
  187 + .replace("::type",type)
  188 + .replace("::phraseCount",String.valueOf(phraseCount))
  189 + .replace("::listeningDuration",String.valueOf(listeningDuration)),
  190 + null,Object.class);
  191 + }
  192 +
  193 +7.提供"单词释义"接口,根据课程id得到课程中所有"单词释义"的值,在类cn.boxfish.onekey.count.CountController方法下
  194 +//获得单词释义的所有值
  195 +public static Set<String> getValues(Map<String, Table<Integer, String, String>> map, File file) {
  196 + Set<String> valueSet = new HashSet<>();
  197 + for (Map.Entry<String, Table<Integer, String, String>> entity : map.entrySet()) {
  198 + Table<Integer, String, String> table = entity.getValue();
  199 + Map<Integer, String> column = table.column("单词释义");
  200 + //判断excel中是否有"单词释义"
  201 + if (column.isEmpty()) {
  202 + logger.error("课[{}][{}]sheet页没有单词释义!", file.getName(),entity.getKey());
  203 + return valueSet;
  204 + }
  205 + for (Map.Entry<Integer, String> entry : column.entrySet()) {
  206 + valueSet.add(entry.getValue());
  207 + }
  208 + logger.info("课[{}][{}]sheet页有单词释义!", file.getName(),entity.getKey());
  209 + }
  210 + return valueSet;
  211 +}
  212 +
  213 +
  214 +
  1 +#逻辑拆解
  2 +1.在跑课项目的老师版和学生版模块中,之前的代码中存在有大量的逻辑判断部分,如在学生版的JobHandler.java和老师版的ExerciseManager.java两个类中,存在大量的if-else逻辑判断,在代码重构的初期工作中,将JobHandler与ExerciseManager中的if-esle逻辑判断拆分出来,将每个逻辑判断的条件体封装到类中,并存放在项目的cn.boxfish.onekey.helper文件夹中,为了区分老师模块与学生模块,将老师模块逻辑判断的类存放到teacher文件夹下,将学生模块逻辑判断拆解的类存放到student文件夹下;
  3 +
  4 +//老师模块初步拆解后的代码:
  5 +for (Map.Entry<String, Table<Integer, String, String>> entry : map.entrySet()) {
  6 + String key = entry.getKey().trim();
  7 + Table<Integer, String, String> table = entry.getValue();
  8 + if (key.equals("图片")) {
  9 + TPTeachHelper.build(table,key,exercises,logger);
  10 + } else if (key.equals("文字")) {
  11 + WZTeachHelper.build(table,key,exercises);
  12 + } else if (key.equals("释义")) {
  13 + SYTeachHelper.build(table,key,exercises);
  14 + } else if (key.equals("阅读")) {
  15 + YDTeachHelper.build(table,key,exercises);
  16 + } else if (key.equals("综合学习")) {
  17 + ZHXXTeachHelper.build(table,key,exercises,isPriExtend,priExtendMap,extendInfo);
  18 + } else if (key.equals("同义词")) {
  19 + TYCTeachHelper.build(table,key,exercises);
  20 + } else if (key.equals("托福口语")) {
  21 + TFKYTeachHelper.build(table,key,exercises);
  22 + } else if (key.equals("托福写作")) {
  23 + TFXZTeachHelper.build(table,key,exercises);
  24 + } else {
  25 + logger.debug("key : " + key);
  26 + }
  27 +}
  28 +2.将逻辑判断移动到类中;在代码的执行中,会判断条件是否成立,然后进入到类中执行条件体,在重构中需要将条件判断移动到条件体中;使用链式模式,在链中传入逻辑判断的条件。当条件成立的时候就会执行该条件体;
  29 +
  30 +//判断条件放到类中,变为链式模式
  31 +public class TFKYTeachHelper extends SheetCommand {
  32 + public TFKYTeachHelper() {
  33 + setSheetName("托福口语");
  34 + }
  35 +
  36 + public void doBuild(Context context) {
  37 + for (Integer r : context.getTable().rowKeySet()) {
  38 + Map<String, String> row = context.getTable().row(r);
  39 + if (StringUtils.isNotBlank(row.get("题目"))
  40 + || StringUtils.isNotBlank(row.get("主题句"))) {
  41 + OralCover oral = new OralCover(row);
  42 + ChecksumUtils.checksum(oral, row);
  43 + KnowledgeUtils.setCode(oral, context.getKey(), row);
  44 +
  45 + // AuditUtils.auditKey(oral, row);
  46 + context.getExercises().add(oral);
  47 +
  48 + } else if (StringUtils.isNotBlank(row.get("核心词"))
  49 + || StringUtils.isNotBlank(row.get("简单句"))) {
  50 + OralContext oral = new OralContext(row);
  51 + ChecksumUtils.checksum(oral, row);
  52 + KnowledgeUtils.setCode(oral, context.getKey(), row);
  53 + // AuditUtils.auditKey(oral, row);
  54 + context.getExercises().add(oral);
  55 + }
  56 + }
  57 + }
  58 +}
  59 +在进行逻辑拆分的时候,不同的逻辑拆分需要判断是否需要执行;前期采用的方法是使用标识符判断的方式,在上下文中设置Flag值默认为false,如果需要执行,在进行逻辑拆分的时候,通过判断falg的值来判断是都需要执行这个逻辑模块;在后期的代码重构中,使用chain链的方式来判断该逻辑模块是否需要执行;
  60 +
  61 +3.拆解后,每个逻辑模块上任然有大量的逻辑判断,按照逻辑拆解的思想,每个类按照模块细分还能进行细化拆解;
  62 +
  63 +4.将拆解完成的逻辑分支合并到develop分支;
  64 +
  65 +#按照跑课模板对每个模块进行拆解
  66 +1.完成对跑课逻辑的拆解后,拆解后的逻辑中任然存在一个或多个跑课模块的判断,需要对跑课中的逻辑进行二次拆解,将老师版和学生版第一次拆解得到的helper下的所有类再次进行拆解;将老师版的模块拆后得到的类放在cn.boxfish.onekey.helper.teacher.helper文件夹下,将学生版的模块拆后得到的类放在cn.boxfish.onekey.helper.student.helper文件夹下;
  67 +//学生版口语考试模块进一步拆解
  68 +public class OralTestHelper {
  69 +
  70 + private static final String SHEET_NAME = "口语考试";
  71 +
  72 + public static void build(Context context) {
  73 + if (!context.isFlag()) {
  74 + if (context.getKey().equals(SHEET_NAME)) {
  75 + doBuild(context);
  76 + context.setFlag(true);
  77 + }
  78 + }
  79 + }
  80 + //口语考试
  81 + public static void doBuild(Context context) {
  82 + for (Integer row : context.getTable().rowKeySet()) {
  83 + Map<String, String> map = context.getTable().row(row);
  84 +
  85 + Context oralContext = new Context();
  86 + oralContext.setMap(map);
  87 + oralContext.setContext(context);
  88 +
  89 + SpHasShortDialogueHelper.build(oralContext);
  90 + SpHasReadAloudHelper.build(oralContext);
  91 + SpHasCompositionHelper.build(oralContext);
  92 + SpHasCoverHelper.build(oralContext);
  93 + SpHasNot.build(oralContext);
  94 + }
  95 + }
  96 +}
  97 +
  98 +2.在对模块进行二次拆解的时候,需要判断每个模块是否需要进入执行,在初期的时候,代码的重构需要使用设置标识符flag,初始值为false;对于互斥的逻辑判断,在执行该模块的代码之前先判断是否flag的值是否为false,如果为false就执行该模块的逻辑,执行完成后设置flag为true;在后来的代码重构中,拆解的时候让该类继承ModelCommand类,使用无参构造的方式调用ModelCommand中的方法,使用闭包的方式将上下文对象传入进去,得到的结果是该类的执行条件的结果值;
  99 +//对学生模块的“APP学生版”中模块拆解,其中的一个模块
  100 +public class APPIsCoverNew extends ModelCommand {
  101 + public APPIsCoverNew() {
  102 + setCallback(context -> CoverNew.isCoverNew(context.getMap()));
  103 + }
  104 +
  105 + public void doBuild(Context context) {
  106 + CoverNew obj = new CoverNew(context.getIndex(), context.getMap());
  107 + ChecksumUtils.checksum(obj, context.getMap());
  108 + KnowledgeUtils.setCode(obj, context.getSheetName(), context.getMap());
  109 + context.getIndex().addCourses(obj);
  110 + }
  111 +}
  112 +
  113 +3.在完成二次拆解后,第一次拆解中各个逻辑模块中就会出现大量的重读代码,将相同的代码抽取到sheetCommand中,将链作为SheetCommand的属性,提取到sheetCommand中;
  114 +//拆解完成APP学生版模块
  115 +public class StudentHelper extends SheetCommand {
  116 +
  117 + public StudentHelper() {
  118 + setSheetName("APP学生版");
  119 + addCommand(new APPHasGrammar());
  120 + addCommand(new APPIsGrammarSum());
  121 + addCommand(new APPIsBigCover());
  122 + addCommand(new APPIsAppreciation());
  123 + addCommand(new APPIsEquals());
  124 + addCommand(new APPIsExpress());
  125 + addCommand(new APPIsOpenQuestion());
  126 + addCommand(new APPIsNotBlank());
  127 + addCommand(new APPIsSceneVideo());
  128 + addCommand(new APPIsNotBlankVideo());
  129 + addCommand(new APPIsNotBlankAudio());
  130 + addCommand(new APPIsNotBlankWZ());
  131 + addCommand(new APPIsNotBlankTPO());
  132 + addCommand(new APPIsCloseTest());
  133 + addCommand(new APPIsScene());
  134 + addCommand(new APPIsCoverNew());
  135 + addCommand(new APPIsLoadingPage());
  136 + addCommand(new APPIsNothing());
  137 + }
  138 +}
  139 +
  140 +#将变量抽取到上下文对象中
  141 +1.在逻辑的拆分的时候,每个逻辑模块都传入了多个参数,为了统一各个模块,将每个类中方法的参数传入到上下文对象中;在项目的cn.boxfish.onekey.helper.context文件夹下创建上下文类Context,将老师模块与学生模块中方法的参数设置为上下文属性,在传递参数的时候,只需要初始化Context对象然后将参数存入上下文对象中,在调用模块中的方法的时候,参数只需要传入context对象;
  142 +
  143 +2.在设置上下文对象的属性时,需要注意,不是所有的参数都需要存放在上下文对象中,有些参数是需要从另一个参数中得到的,可以直接从另一个参数中获取即可;
  144 +
  145 +3.修改初始化上下文的位置,上下文对象在一次跑课中,只使用一次,在初始化的时候,应该是在跑课开始的时候创建上下文对象,不能在全局位置创建上下文对象;
  146 +
  147 +
  148 +#调整跑课代码顺序
  149 +1.定义抽象类cn.boxfish.single.export.AbstractExportService,实现ApplicationEventPublisherAware接口,将学生模块与老师模块公共的功能代码移动到该类中;初始化赋值、提供excel解析完成的主数据、扩展数据等;
  150 +
  151 +2.整理学生版跑课与老师版跑课代码:将学生版跑课代码中初始化链和初始化上下文的代码放在cn.boxfish.single.export.ExportStudentService类中;将老师版中初始化链和上下文的代码放在ExportTeacherService中,将具体的细节交给子类实现;
  152 +
  153 +3.整理nlp相关的代码:将调用nlp接口保存数据的方法和获得听力时长和短句数的方法保存到cn.boxfish.onekey.nlp.NlpHandler中,给跑课代码调用
  154 +/
  155 +/与nlp相关的代码放在NlpHandler类中
  156 +@Value("${nlp.article.url}")
  157 +private String nlpUrl;
  158 +
  159 +private AsyncRestTemplate restTemplate = new AsyncRestTemplate();
  160 +
  161 +public void saveNlpArticle(String lessonId, String type, Integer phraseCount, Long listeningDuration) {
  162 + restTemplate.postForEntity(
  163 + nlpUrl.replace("::lessonId", lessonId)
  164 + .replace("::type", type)
  165 + .replace("::phraseCount", String.valueOf(phraseCount))
  166 + .replace("::listeningDuration", String.valueOf(listeningDuration)),
  167 + null, Object.class);
  168 +}
  169 +
  170 +public void handle(Context context) {
  171 + Map<String, Table<Integer, String, String>> sheetMap = context.getSheetMap();
  172 + File file = context.getFile().toFile();
  173 + String projectId = context.getProjectId();
  174 + String type = context.getType();
  175 +
  176 + //获得课的短句数
  177 + Integer phraseCount = CalculCount.count(sheetMap, file, projectId);
  178 + //获得课中音频时长
  179 + Long audioDuration = AudioDuration.countAudioDuration(sheetMap);
  180 + //获得课中视频时长
  181 + Long videoDuration = VideoDuration.countVideoDuration(sheetMap);
  182 + //听力时长
  183 + Long listeningDuration = audioDuration + videoDuration;
  184 +
  185 + logger.info("NLP数据获取-{}: id:[{}]", type, projectId);
  186 + try {
  187 + this.saveNlpArticle(projectId, type, phraseCount, listeningDuration);
  188 + } catch (Exception e) {
  189 + logger.error("NLP数据获取出错-{}: id:[{}],错误:{{}}", type, projectId, e);
  190 + }
  191 +}
  192 +
  193 +