thymeleaf 实现静态化页面

1、什么是页面静态化 静态化

  是指把动态生成的HTML页面变为静态内容保存,以后用户的请求到来,直接访问静态页面,不再经过服务的渲染。 而静态的HTML页面可以部署在nginx中,从而大大提高并发能力,减小tomcat压力。

2、目前,静态化页面都是通过模板引擎来生成,而后保存到nginx服务器来部署。常用的模板引擎比如:

- Freemarker

- Velocity -

Thymeleaf

这里采用Thymeleaf!!

 

3、查看项目结构

thymeleaf 实现静态化页面

 

4、引入依赖,配置文件

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

配置application.yml文件

server:
  port: 8080

5、配置启动类

@SpringBootApplication
public class DemoApp {
    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class,args);
    }
}

6、创建controller、service、user对象、utils工具类, 静态页面

创建controller:

@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private HtmlService htmlService;

    @GetMapping("{id}.html")
    public String get(Model model,@PathVariable("id") Long id){
        User user = new User();
        user.setName("张三");
        model.addAttribute("user",user);

        // 页面静态化
        this.htmlService.asyncExcute(id);

        return "index";
    }
}

创建service,命名为HtmlService:

import com.leyou.utils.ThreadUtils;
import org.example.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;

@Service
public class HtmlService {

    @Autowired
    private TemplateEngine templateEngine;

    private static final Logger LOGGER = LoggerFactory.getLogger(HtmlService.class);

    /**
     * 创建html页面
     * @param id
     * @throws Exception
     */
    public void createHtml(Long id) {

        PrintWriter writer = null;
        try {
            // 获取页面数据
            User user = new User();
            user.setName("张三");

            // 创建thymeleaf上下文对象
            Context context = new Context();
            // 把数据放入上下文对象
            context.setVariable("user",user);

            // 创建输出流 D:\nginx-1.18.0\html
            File file = new File("D:\\nginx-1.18.0\\html\\user\\" + id + ".html");
            writer = new PrintWriter(file);

            // 执行页面静态化方法
            templateEngine.process("index", context, writer);

        } catch (Exception e) {
            LOGGER.error("页面静态化出错:{},"+ e, id);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(()->createHtml(spuId));
        ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });
    }
}

创建user类

public class User {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

创建ThreadUtils工具类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadUtils {

    private static final ExecutorService es = Executors.newFixedThreadPool(10);

    public static void execute(Runnable runnable) {
        es.submit(runnable);
    }
}

在resources/templates下创建index.html : 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>hello world!</h1>
    <p th:text="${user.name}"></p>
</body>
</html>

7、需要nginx做代理,配置如下

location /user {
     root html;
             
     if (!-f $request_filename) { #请求的文件不存在,就反向代理
         proxy_pass http://127.0.0.1:8080;
         break;
     }
}

配置好后重启nginx,指令: nginx -s reload

 

8、测试

访问 http://localhost/user/1.html

thymeleaf 实现静态化页面

 

  

检查D:\nginx-1.18.0\html\user目录下是否有静态化的html文件!

thymeleaf 实现静态化页面

 

上一篇:韩旭个人博客SpringBoot + Mybatis + Thymeleaf + MySQL


下一篇:Java实现串口通信(SpringBoot+RXTX+Thymeleaf+ElementUI)