From 5c91e96d79a08619f9eec28b4d30980e40c595dd Mon Sep 17 00:00:00 2001 From: hiparker Date: Sat, 8 May 2021 10:33:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81=E7=94=9F?= =?UTF-8?q?=E6=88=90=E5=99=A8=E6=A8=A1=E6=9D=BF=E5=BC=95=E6=93=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../opsli/core/creater/utils/EnjoyUtil.java | 50 +++++++++++-------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/opsli-modulars/opsli-modulars-creater/src/main/java/org/opsli/core/creater/utils/EnjoyUtil.java b/opsli-modulars/opsli-modulars-creater/src/main/java/org/opsli/core/creater/utils/EnjoyUtil.java index 08148f5..8e90e88 100644 --- a/opsli-modulars/opsli-modulars-creater/src/main/java/org/opsli/core/creater/utils/EnjoyUtil.java +++ b/opsli-modulars/opsli-modulars-creater/src/main/java/org/opsli/core/creater/utils/EnjoyUtil.java @@ -1,49 +1,57 @@ package org.opsli.core.creater.utils; import cn.hutool.core.io.IoUtil; +import com.google.common.collect.Maps; import com.jfinal.kit.Kv; import com.jfinal.template.Engine; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; -import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.Map; /*** - * jfinal魔板引擎 - * @author dufuzhong + * Enjoy 模板引擎 + * @author Parker */ @Slf4j public final class EnjoyUtil { private static final String BASE_PATH = "/tpl"; + /** 模板文件Map */ + private static final Map TEMPLATE_FILE_MAP = Maps.newConcurrentMap(); + /** * 根据具体魔板生成文件 * @param templateFileName 模板文件名称 * @param kv 渲染参数 - * @return + * @return String */ - public static String render(String templateFileName, Kv kv) { - - String str = ""; - ClassPathResource resource = new ClassPathResource(BASE_PATH + templateFileName); - try (InputStream inputStream = resource.getInputStream()){ - String readTpl = IoUtil.read(inputStream, StandardCharsets.UTF_8); - - str = Engine.use() - // 开启预热模式 - .setDevMode(true) - .getTemplateByString(readTpl) - .renderToString(kv); - - } catch (Exception e) { - log.error("load config file {} error", templateFileName, e); + public static String render(final String templateFileName, Kv kv) { + + // 模板缓存 减少每次更新 + String templateFile = TEMPLATE_FILE_MAP.get(templateFileName); + if(StringUtils.isEmpty(templateFile)){ + + // 如果为空 则IO 读取原始文件 + ClassPathResource resource = new ClassPathResource(BASE_PATH + templateFileName); + try (InputStream inputStream = resource.getInputStream()){ + templateFile = IoUtil.read(inputStream, StandardCharsets.UTF_8); + TEMPLATE_FILE_MAP.put(templateFileName, templateFile); + } catch (Exception e) { + log.error("load file {} error", templateFileName, e); + } } - return str; - } + return Engine.use() + // 开启预热模式 + .setDevMode(true) + .getTemplateByString(templateFile) + .renderToString(kv); + } private EnjoyUtil(){}