feat: 优化编译,更加稳定

This commit is contained in:
wangyu 2022-10-04 22:51:10 +08:00
parent 040452e066
commit b41f0f5ae8

View File

@ -12,6 +12,7 @@ import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -22,26 +23,28 @@ import java.util.stream.Collectors;
*/ */
public class TemplateCompiler { public class TemplateCompiler {
// 变量池缓存
private static final Map<Class<?>, Map<String, Method>> POOL_CACHE = new ConcurrentHashMap<>();
/** /**
* 编译模板文件和源码数据为源代码字符串 * 编译模板文件和源码数据为源代码字符串
* *
* @param dataClass 数据class * @param dataClass 数据class
* @param filename 文件名 * @param filename 文件名
* @return 结果 * @return 结果
*/ */
public static Function<JavaSource, String> compile(Class<?> dataClass, String filename) { public static <T> Function<T, String> compile(Class<T> dataClass, String filename) {
// 获取文件内容 // 获取文件内容
InputStream fis = TemplateCompiler.class.getResourceAsStream(filename); InputStream fis = TemplateCompiler.class.getResourceAsStream(filename);
try { try {
// 获取模板内容 // 获取模板内容
String template = StreamUtils.copyToString(fis, StandardCharsets.UTF_8); String template = StreamUtils.copyToString(fis, StandardCharsets.UTF_8);
// 准备变量池 // 准备变量池
Map<String, PropertyDescriptor> pool = Arrays.stream(BeanUtils.getPropertyDescriptors(dataClass)) Map<String, Method> pool = methodPool(dataClass);
.collect(Collectors.toMap(descriptor -> "#{" + descriptor.getName() + "}", a -> a));
// 编译 // 编译
return cfg -> pool.keySet().stream().reduce(template, (result, key) -> { return cfg -> pool.keySet().stream().reduce(template, (result, key) -> {
// 获取读取方法 // 获取读取方法
Method method = pool.get(key).getReadMethod(); Method method = pool.get(key);
Object value = null; Object value = null;
try { try {
// 取得结果 // 取得结果
@ -57,6 +60,17 @@ public class TemplateCompiler {
} }
} }
/**
* 数据类方法池
*
* @param dataClass 数据类
* @return 结果
*/
private static Map<String, Method> methodPool(Class<?> dataClass) {
return POOL_CACHE.computeIfAbsent(dataClass, k -> Arrays.stream(BeanUtils.getPropertyDescriptors(k))
.collect(Collectors.toMap(descriptor -> "#{" + descriptor.getName() + "}", PropertyDescriptor::getReadMethod)));
}
/** /**
* 解析单个值 * 解析单个值
* *