优化代码生成器模板引擎

v1.4.1
hiparker 4 years ago
parent c2b047b0e5
commit 5c91e96d79

@ -1,49 +1,57 @@
package org.opsli.core.creater.utils; package org.opsli.core.creater.utils;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import com.google.common.collect.Maps;
import com.jfinal.kit.Kv; import com.jfinal.kit.Kv;
import com.jfinal.template.Engine; import com.jfinal.template.Engine;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Map;
/*** /***
* jfinal * Enjoy
* @author dufuzhong * @author Parker
*/ */
@Slf4j @Slf4j
public final class EnjoyUtil { public final class EnjoyUtil {
private static final String BASE_PATH = "/tpl"; private static final String BASE_PATH = "/tpl";
/** 模板文件Map */
private static final Map<String, String> TEMPLATE_FILE_MAP = Maps.newConcurrentMap();
/** /**
* *
* @param templateFileName * @param templateFileName
* @param kv * @param kv
* @return * @return String
*/ */
public static String render(String templateFileName, Kv kv) { public static String render(final String templateFileName, Kv kv) {
String str = ""; // 模板缓存 减少每次更新
ClassPathResource resource = new ClassPathResource(BASE_PATH + templateFileName); String templateFile = TEMPLATE_FILE_MAP.get(templateFileName);
try (InputStream inputStream = resource.getInputStream()){ if(StringUtils.isEmpty(templateFile)){
String readTpl = IoUtil.read(inputStream, StandardCharsets.UTF_8);
// 如果为空 则IO 读取原始文件
str = Engine.use() ClassPathResource resource = new ClassPathResource(BASE_PATH + templateFileName);
// 开启预热模式 try (InputStream inputStream = resource.getInputStream()){
.setDevMode(true) templateFile = IoUtil.read(inputStream, StandardCharsets.UTF_8);
.getTemplateByString(readTpl) TEMPLATE_FILE_MAP.put(templateFileName, templateFile);
.renderToString(kv); } catch (Exception e) {
log.error("load file {} error", templateFileName, e);
} catch (Exception e) { }
log.error("load config file {} error", templateFileName, e);
} }
return str;
}
return Engine.use()
// 开启预热模式
.setDevMode(true)
.getTemplateByString(templateFile)
.renderToString(kv);
}
private EnjoyUtil(){} private EnjoyUtil(){}

Loading…
Cancel
Save