1. 程式人生 > >SpringBoot 快取&資源優化

SpringBoot 快取&資源優化

頁面快取

1. freemarker 的頁面靜態化

application.properties 配置實現瀏覽器快取

# SPRING RESOURCES HANDLING ([ResourceProperties](https://github.com/spring-projects/spring-boot/tree/v1.5.4.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ResourceProperties.java))
spring.resources.add-mappings=true # Enable default resource handling.
spring.resources.cache-period= # Cache period for the resources served by the resource handler, in seconds. spring.resources.chain.cache=true # Enable caching in the Resource chain. spring.resources.chain.enabled= # Enable the Spring Resource Handling chain. Disabled by default unless at least one strategy has been enabled.
spring.resources.chain.gzipped=false # Enable resolution of already gzipped resources. spring.resources.chain.html-application-cache=false # Enable HTML5 application cache manifest rewriting. spring.resources.chain.strategy.content.enabled=false # Enable the content Version Strategy. spring.resources
.chain.strategy.content.paths=/** # Comma-separated list of patterns to apply to the Version Strategy. spring.resources.chain.strategy.fixed.enabled=false # Enable the fixed Version Strategy. spring.resources.chain.strategy.fixed.paths=/** # Comma-separated list of patterns to apply to the Version Strategy. spring.resources.chain.strategy.fixed.version= # Version string to use for the Version Strategy. spring.resources.static-locations=classpath:/static/

controller中實現頁面靜態化


/**
 * Created by Fant.J.
 */
@RestController
public class HelloController {

    @Autowired
    private Configuration configuration;


    @GetMapping("/hello")
    public String demo(Map<String, Object> map) {
        map.put("name", "demo");
        freeMarkerContent(map,"hello");
        return "hello";
    }

    private void freeMarkerContent(Map<String,Object> root,String ftl){
        try {
            Template temp = configuration.getTemplate(ftl+".ftl");
            //以classpath下面的static目錄作為靜態頁面的儲存目錄,同時命名生成的靜態html檔名稱
            String path=this.getClass().getResource("/").getPath()+"templates/"+ftl+".html";
            Writer file = new FileWriter(path);
            temp.process(root, file);
            file.flush();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. thymeleaf 的頁面靜態化

核心程式碼的不同:

        SpringWebContext ctx = new SpringWebContext(request,response,
                request.getServletContext(),request.getLocale(), model.asMap(), applicationContext );
        String html = thymeleafViewResolver.getTemplateEngine().process("hello", ctx);

物件快取

利用Redis實現物件的快取:

後面我會新增SpringBoot 對 Redis 的整合開發。

靜態資源優化

1. JS/CSS壓縮

取消空格。

2. 多個JS/CSS組合

打包成一個js/css,減少請求次數

3.CDN訪問

js/css打包放到cdn上做提速