springboot 页面静态化

页面静态化:将动态渲染的页面保存为静态页面(一般存储在nginx),提高访问速度

说明:页面静态化适用于数据不常变更的场景,如果数据频繁变更,宜使用其他方案提高访问性能

相关类与接口

IContext:存储上下文变量

public interface IContext {Locale getLocale();boolean containsVariable(String var1);Set<String> getVariableNames();Object getVariable(String var1);
}

AbstractContext

public abstract class AbstractContext implements IContext {private final Map<String, Object> variables;private Locale locale;protected AbstractContext() {protected AbstractContext(Locale locale) {protected AbstractContext(Locale locale, Map<String, Object> variables) {public void setLocale(Locale locale) {public final Locale getLocale() {public final boolean containsVariable(String name) {public final Set<String> getVariableNames() {public final Object getVariable(String name) {public void setVariable(String name, Object value) {public void setVariables(Map<String, Object> variables) {public void removeVariable(String name) {public void clearVariables() {

Context

public final class Context extends AbstractContext {public Context() {}public Context(Locale locale) {super(locale);}public Context(Locale locale, Map<String, Object> variables) {super(locale, variables);}
}

ITemplateEngine

public interface ITemplateEngine {IEngineConfiguration getConfiguration();String process(String var1, IContext var2);String process(String var1, Set<String> var2, IContext var3);String process(TemplateSpec var1, IContext var2);void process(String var1, IContext var2, Writer var3);void process(String var1, Set<String> var2, IContext var3, Writer var4);void process(TemplateSpec var1, IContext var2, Writer var3);IThrottledTemplateProcessor processThrottled(String var1, IContext var2);IThrottledTemplateProcessor processThrottled(String var1, Set<String> var2, IContext var3);IThrottledTemplateProcessor processThrottled(TemplateSpec var1, IContext var2);
}

ISpringTemplateEngine

public interface ISpringTemplateEngine extends ITemplateEngine {void setTemplateEngineMessageSource(MessageSource var1);
}

TemplateEngine

public class TemplateEngine implements ITemplateEngine {public static final String TIMER_LOGGER_NAME = TemplateEngine.class.getName() + ".TIMER";private static final Logger logger = LoggerFactory.getLogger(TemplateEngine.class);private static final Logger timerLogger;private static final int NANOS_IN_SECOND = 1000000;private volatile boolean initialized = false;private final Set<DialectConfiguration> dialectConfigurations = new LinkedHashSet(3);private final Set<ITemplateResolver> templateResolvers = new LinkedHashSet(3);private final Set<IMessageResolver> messageResolvers = new LinkedHashSet(3);private final Set<ILinkBuilder> linkBuilders = new LinkedHashSet(3);private ICacheManager cacheManager = null;private IEngineContextFactory engineContextFactory = null;private IDecoupledTemplateLogicResolver decoupledTemplateLogicResolver = null;private IEngineConfiguration configuration = null;public TemplateEngine() {this.setCacheManager(new StandardCacheManager());this.setEngineContextFactory(new StandardEngineContextFactory());this.setMessageResolver(new StandardMessageResolver());this.setLinkBuilder(new StandardLinkBuilder());this.setDecoupledTemplateLogicResolver(new StandardDecoupledTemplateLogicResolver());this.setDialect(new StandardDialect());}***********
dialect 操作public void setDialect(IDialect dialect) {public void setDialects(Set<IDialect> dialects) {public void setAdditionalDialects(Set<IDialect> additionalDialects) {public final Set<IDialect> getDialects() {public void addDialect(String prefix, IDialect dialect) {public void addDialect(IDialect dialect) {public void setDialectsByPrefix(Map<String, IDialect> dialects) {public final Map<String, Set<IDialect>> getDialectsByPrefix() {public void clearDialects() {***********
templateResolver 操作public void setTemplateResolver(ITemplateResolver templateResolver) {public void setTemplateResolvers(Set<ITemplateResolver> templateResolvers) {public void addTemplateResolver(ITemplateResolver templateResolver) {public final Set<ITemplateResolver> getTemplateResolvers() {***********
process 操作public final String process(String template, IContext context) {public final String process(String template, Set<String> templateSelectors, IContext context) {public final String process(TemplateSpec templateSpec, IContext context) {public final void process(String template, IContext context, Writer writer) {public final void process(String template, Set<String> templateSelectors, IContext context, Writer writer) {public final void process(TemplateSpec templateSpec, IContext context, Writer writer) {public final IThrottledTemplateProcessor processThrottled(String template, IContext context) {public final IThrottledTemplateProcessor processThrottled(String template, Set<String> templateSelectors, IContext context) {public final IThrottledTemplateProcessor processThrottled(TemplateSpec templateSpec, IContext context) {***********
其余操作public final ICacheManager getCacheManager() {public void setCacheManager(ICacheManager cacheManager) {public final IEngineContextFactory getEngineContextFactory() {public void setEngineContextFactory(IEngineContextFactory engineContextFactory) {public final IDecoupledTemplateLogicResolver getDecoupledTemplateLogicResolver() {public void setDecoupledTemplateLogicResolver(IDecoupledTemplateLogicResolver decoupledTemplateLogicResolver) {public final Set<IMessageResolver> getMessageResolvers() {public void setMessageResolvers(Set<IMessageResolver> messageResolvers) {public void addMessageResolver(IMessageResolver messageResolver) {public void setMessageResolver(IMessageResolver messageResolver) {public final Set<ILinkBuilder> getLinkBuilders() {public void setLinkBuilders(Set<ILinkBuilder> linkBuilders) {public void addLinkBuilder(ILinkBuilder linkBuilder) {public void setLinkBuilder(ILinkBuilder linkBuilder) {public void clearTemplateCache() {public void clearTemplateCacheFor(String templateName) {public static String threadIndex() {public final boolean isInitialized() {public IEngineConfiguration getConfiguration() {private void checkNotInitialized() {final void initialize() {protected void initializeSpecific() {static {timerLogger = LoggerFactory.getLogger(TIMER_LOGGER_NAME);}
}

SpringTemplateEngine:springboot启动时自动创建实例bean(mvc)

public class SpringTemplateEngine extends TemplateEngine implements ISpringTemplateEngine, MessageSourceAware {private static final SpringStandardDialect SPRINGSTANDARD_DIALECT = new SpringStandardDialect();private MessageSource messageSource = null;private MessageSource templateEngineMessageSource = null;public SpringTemplateEngine() {super.setDialect(SPRINGSTANDARD_DIALECT);}public void setMessageSource(MessageSource messageSource) {public void setTemplateEngineMessageSource(MessageSource templateEngineMessageSource) {public void setEnableSpringELCompiler(boolean enableSpringELCompiler) {public void setRenderHiddenMarkersBeforeCheckboxes(boolean renderHiddenMarkersBeforeCheckboxes) {public boolean getEnableSpringELCompiler() {public boolean getRenderHiddenMarkersBeforeCheckboxes() {protected final void initializeSpecific() {protected void initializeSpringSpecific() {

使用示例

*************

config 层

WebConfig

@EnableAsync
@Configuration
public class WebConfig implements AsyncConfigurer {@Overridepublic Executor getAsyncExecutor() {ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(10);executor.setKeepAliveSeconds(60);executor.initialize();return executor;}
}

*************

service

StaticPageService

@Service
public class StaticPageService {private final String path="/usr/nginx/html";@Resourceprivate TemplateEngine templateEngine;@Async@SuppressWarnings("all")public void createOrUpdatePage(Map<String,Object> map, String templateName, String dir, Integer id){System.out.println("createOrUpdatePage: "+dir);Context context=new Context();context.setVariables(map);File root=new File(path+File.separator+dir);if (!root.exists()){root.mkdir();}File file=new File(path,dir+File.separator+id+".html");if (file.exists()){file.delete();}try {PrintWriter writer=new PrintWriter(file, StandardCharsets.UTF_8);templateEngine.process(templateName,context,writer);}catch (Exception e){e.printStackTrace();}}@Async@SuppressWarnings("all")public void deletePage(String dir, Integer id){File file = new File(path, dir+File.separator+id+".html");if (file.exists()){file.delete();}}
}

*************

controller

HelloController

@Controller
public class HelloController {private Map<String,Object> map=new HashMap<>();@Resourceprivate StaticPageService pageService;@RequestMapping("/person/{id}.html")public ModelAndView get(@PathVariable("id") Integer id, ModelAndView mv){map.put("id",id);map.put("name","瓜田李下");map.put("age",20);pageService.createOrUpdatePage(map,"template","person", id);mv.setViewName("template");mv.addAllObjects(map);return mv;}
}

*************

前端页面

template.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head><meta charset="UTF-8"><title>static page</title>
</head>
<body>
<div th:align="center" style="color: coral"><span th:text="'id: '+${id}"></span><br><span th:text="'name: '+${name}"></span><br><span th:text="'age: '+${age}"></span>
</div>
</body>
</html>

创建应用

nginx 配置:default.conf

server {listen       80;server_name  localhost;#charset koi8-r;#access_log  /var/log/nginx/host.access.log  main;location /person {root   /usr/share/nginx/html;index  index.html index.htm;if ( !-e $request_filename ){proxy_pass http://192.168.57.2:8080;break;}}error_page   500 502 503 504  /50x.html;location = /50x.html {root   /usr/share/nginx/html;}}

创建应用:docker 启动springboot应用,nginx代理应用

docker run -it -d --net fixed3 --ip 192.168.57.2 \
-v /usr/nginx/static-page/demo.jar:/usr/local/app.jar \
-v /usr/nginx/html:/usr/nginx/html \
--name static-page commondocker run -it -d --net fixed3 --ip 192.168.57.3  \
-v /usr/nginx/static-page/conf/default.conf:/etc/nginx/conf.d/default.conf \
-v /usr/nginx/html:/usr/share/nginx/html \
--name nginx nginx

使用测试

192.168.57.3:8000/person/1.html

控制台输出

2021-08-24 12:25:21.123  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-08-24 12:25:21.180  INFO 1 --- [           main] com.example.demo.SpringbootApplication   : Started SpringbootApplication in 10.528 seconds (JVM running for 13.335)
2021-08-24 12:25:29.686  INFO 1 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-08-24 12:25:29.687  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2021-08-24 12:25:29.690  INFO 1 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms
createOrUpdatePage: person

查看本地目录:/usr/nginx/html

[root@centos html]# pwd
/usr/nginx/html[root@centos html]# ls
person
[root@centos html]# ls person
1.html[root@centos html]# cat person/1.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head><meta charset="UTF-8"><title>static page</title>
</head>
<body>
<div align="center" style="color: coral"><span>id: 1</span><br><span>name: 瓜田李下</span><br><span>age: 20</span>
</div>
</body>

再次访问192.168.57.3:8000/person/1.html,nginx直接返回本地缓存的静态文件

springboot 页面静态化相关推荐

  1. SpringBoot整合Thymleaf实现页面静态化

    文章整理题材来源于传智播客乐优商城项目实战! 1. 问题需求分析 在做乐优商城时,页面是通过Thymeleaf模板引擎渲染后返回到客户端.当商品详情页数据渲染时,在后台需要大量的数据查询,而后渲染得到 ...

  2. 学成在线--9.页面静态化

    文章目录 一.页面静态化流程 二.数据模型 1.轮播图DataUrl接口 1)需求分析 2)接口定义 3)Dao 4)Service 5)Controller 6)测试 2.远程请求接口 1)添加依赖 ...

  3. MySQL建表添加乐观锁字段_Java秒杀系统优化-Redis缓存-分布式session-RabbitMQ异步下单-页面静态化...

    Java秒杀系统优化-Redis缓存-分布式session-RabbitMQ异步下单-页面静态化 项目介绍 基于SpringBoot+Mybatis搭建的秒杀系统,并且针对高并发场景进行了优化,保证线 ...

  4. 学成在线 第4天 讲义-页面静态化 页面预览

    1页面静态化需求 1.为什么要进行页面管理? 本项目cms系统的功能就是根据运营需要,对门户等子系统的部分页面进行管理,从而实现快速根据用户需求修改 页面内容并上线的需求. 2.如何修改页面的内容? ...

  5. Thymeleaf实现页面静态化

    Thymeleaf实现页面静态化 前言 之前学习过的Redis.不过Redis适合数据规模比较小的情况.假如数据量比较大,例如我们的商品详情页.每个页面如果10kb,100万商品,就是10GB空间,对 ...

  6. freemarker之页面静态化

    静态化? 这里我们以网页静态化技术之一的Freemarker 为例子.以电商为原型 对于电商网站的商品详情页来说,至少几百万个商品,每个商品又有大量的信息,这样的情况同样也适用于使用网页静态化来解决 ...

  7. 网站页面静态化(二)thymeleaf生成

    今年是农历大年初三,在这里首先给各位朋友拜个年,祝大家新年快乐,虎年大吉大利,事业蒸蒸日上.过年无事,把页面静态化技术整理整理.本文将以thymeleaf为例子,说明在springboot当中,如何基 ...

  8. 页面静态化Freemaker

    1.简介 网站的web前端要实现高效,第一个要解决的短板就是网络的延迟性对网站的加载效率的影响,网站本身的确是没法控制网络速度的能力,但是如果我们不降低网络对页面加载效率的影响, 大型动态网站之所以可 ...

  9. 项目性能优化(实现页面静态化1)

    当首页访问频繁,而且查询数据量大,其中还有大量的循环处理时,这会耗费服务器大量的资源,并且响应数据的效率,这时就需要页面静态化. 1. 页面静态化介绍 1.为什么要做页面静态化 减少数据库查询次数. ...

最新文章

  1. c/c++内存机制(一)(原)
  2. mysql存储加速_mysql存储过程加速
  3. Hadoop的调度器总结
  4. python基础——字典
  5. 页面乱码及页面传值出现乱码
  6. 21个深度学习调参的实用技巧
  7. python tkinter画笑脸_Python3 tkinter基础 Canvas create_polygon 画三角形
  8. Eclipse去除js(JavaScript)验证错误
  9. 落魄前端,整理给自己的前端知识体系复习大纲(下篇)
  10. oracle ora-22992,ORACLE ORA--22992:无法使用远程表选择的LOB定位器,database link
  11. sqlserver的坑
  12. linux 内核编程视频
  13. BD 之 逻辑题 赛马
  14. iOS 依赖注入:Objection 和 Typhoon
  15. eclipse中一些常见的报错处理
  16. 通信工程测试图修改软件,通信工程工具仪器大全,你用过几种?
  17. 中国娱记的鼻祖留心shuo新浪博客
  18. 开启createjs+animate cc之旅
  19. Mac 修改AppleID 使用“登录”钥匙串
  20. 如何使用webshell方式登录腾讯云Linux轻量应用服务器实例?

热门文章

  1. TAQ服务器npc多久自动交物资,魔兽世界怀旧服:奥罗服务器物资捐献完成,已成国服第一个开门...
  2. 安卓日记——手把手教你做知乎日报
  3. 怎样成长为更好的自己--《靠谱:顶尖咨询师教你的工作基本功》
  4. tws真无线蓝牙耳机隐藏的冷知识
  5. Qt下QTableWidget 基本用法
  6. SpringMVC+FastJson+Swagger集成完整示例
  7. 使用BeautifulSoup爬网页指定内容
  8. 步进电机工作原理与编程
  9. 在c语言求30角的正弦值,正弦及30度角的正弦值.doc
  10. Python hashlib库和hamc库