码库记事本

码库记事本

thymeleaf 实现静态化页面

小诸哥 0

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

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

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

- Freemarker

- Velocity -

Thymeleaf

这里采用Thymeleaf!!

 

3、查看项目结构

 

4、引入依赖,配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<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文件

1
2
server:
  port: 8080

5、配置启动类

1
2
3
4
5
6
@SpringBootApplication
public class DemoApp {
    public static void main(String[] args) {
        SpringApplication.run(DemoApp.class,args);
    }
}

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

创建controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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类

1
2
3
4
5
6
7
8
9
public class User {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

创建ThreadUtils工具类

1
2
3
4
5
6
7
8
9
10
11
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 : 

1
2
3
4
5
6
7
8
9
10
11
<!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做代理,配置如下

1
2
3
4
5
6
7
8
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

 

  

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

标签: 实现 静态