在做开放平台的文档中心过程中,由于api文档不是经常变化的,所以如果每次页面渲染的时候,都去查询DB获取数据,这种性能浪费就太大了,而且文档中心是不需要登录就可以访问的,这样会给DB带来很大的压力。
对于这种情况,可以采用静态文件方案,基本思路如下:
- 小二在后台发布api时,api管控后台基于velocity生成静态文档,并将该文档存储至共享文件目录,存储的完整路径根据预定的规则来确定。
- 用户访问api文档时,文档中心前台根据api的名称确定文档在共享文件目录存储的完整路径,然后解析文档,最终展现给用户
以下代码示例如何基于velocity生成静态文档
public void generateDoc(ApiModel apiModel) {
FileOutputStream fos = null;
BufferedWriter writer = null;
try {
Properties properties = new Properties();
//指定生成静态文档需要的模板文件所在的目录
properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH,
apiDocTemplatePath);
VelocityEngine engine = new VelocityEngine();
//初始化模板引擎
engine.init(properties);
//根据API_TEMPLATE_FILE读取生成静态文档需要的模板文件
Template template = engine.getTemplate(API_TEMPLATE_FILE, "GBK");
VelocityContext context = new VelocityContext();
//将生成文档需要的数据apiModel放入模板引擎的上下文中
context.put("apiModel", apiModel);
//确定静态文档在共享文件目录的完整存储路径
String filePath = baseFolder.getFile().getAbsolutePath() + "/" + apiModel.getEnName() + ".html";
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
writer = new BufferedWriter(new OutputStreamWriter(fos, "GBK"));// 设置写入的文件编码,解决中文问题
//将数据与模板merge,并写入到静态文档
template.merge(context, writer);
} catch (Exception e) {
//打印日志
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
//打印日志
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
//打印日志
}
}
}
}
需要注意的是这行代码
properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH,apiDocTemplatePath);
必须指定模板文件所在的目录,否则引擎会找不到模板文件。
本文为原创,转载请注明出处