public void cache(){ String id = getPara("id"); //保存的策略是60time,找这个缓存byId Keypage cacheMap = CacheKit.get("60time", id); //如果这个ById的缓存不存在,则查询一下数据,进行保存 if (cacheMap == null) { cacheMap = new Keypage(); cacheMap.put(id, Keypage.dao.findById(id)); CacheKit.put("60time", id, cacheMap); } //-----------疑惑就出现在这里 Start-------------- //----------前端enjoy渲染的时候使用----------- setAttr("cacheMap", cacheMap); /** * 问: * 如果我不是单单一个记录,而是用到findById,也不是用到findByCache,而且经常业务逻辑处理之后的属性改怎么保存呢? * ---解决办法:难道要new map ,把所有属性都put进去吗?如果整个项目很庞大,这种方式好像很吃力。前端enjoy调用也要进行修改 */ //-----------疑惑就出现在这里 End-------------- List s = CacheKit.getKeys("60time"); //查询缓存了多少个记录 for (Object object : s) { logger.info(object); } renderJson(cacheMap + "所有缓存keys :" +CacheKit.getKeys("60time")); }
解决办法:
mainConfig:
@Override public void configEngine(Engine me) { // TODO Auto-generated method stub me.addDirective("compress", CompressDirective.class); }
package com.seo.tool; import com.jfinal.template.Directive; import com.jfinal.template.Env; import com.jfinal.template.TemplateException; import com.jfinal.template.expr.ast.ExprList; import com.jfinal.template.io.CharWriter; import com.jfinal.template.io.FastStringWriter; import com.jfinal.template.io.Writer; import com.jfinal.template.stat.Scope; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CompressDirective extends Directive { // 不压缩pre/script/style标签 private static final Pattern ignoredPattern = Pattern.compile("(<pre>(.|\n)*?</pre>)|(<script>(.|\n)*?</script>)|(<style>(.|\n)*?</style>)"); private static final Pattern matchedPattern = Pattern.compile("\\s+"); @Override public void setExprList(ExprList exprList) { if (exprList.length() != 0) { throw new RuntimeException("#compress directive support no parameters only"); } super.setExprList(exprList); } @Override public void exec(Env env, Scope scope, Writer writer) { CharWriter charWriter = new CharWriter(2048); FastStringWriter fsw = new FastStringWriter(); charWriter.init(fsw); stat.exec(env, scope, charWriter); try { StringBuilder temp = fsw.getBuffer(); Matcher ignoredMatcher = ignoredPattern.matcher(temp); int lastIndex = 0; while (ignoredMatcher.find()) { int end = ignoredMatcher.start(); writer.write(compress(temp.substring(lastIndex, end))); writer.write(ignoredMatcher.group()); lastIndex = ignoredMatcher.end() + 1; } // 将最后一个标签后的内容压缩并写入 writer.write(compress(temp.substring(lastIndex, temp.length()))); } catch (IOException e) { throw new TemplateException(e.getMessage(), location, e); } } private String compress(String temp) { Matcher matchedMatcher = matchedPattern.matcher(temp.trim()); // 多个空白字符变为1个 temp = matchedMatcher.replaceAll(" "); return temp; } @Override public boolean hasEnd() { return true; } }
感谢某个大神的分享。
项目:JFinal
使用的时候这样:
#compress
这里是一切别的内容
#end