Spring Boot Thymeleaf 设置模板过期时间

Spring Boot Thymeleaf About 1,820 words

方法一

配置缓存

spring:
  thymeleaf:
    cache: true

设置缓存过期时间

默认使用LRU算法淘汰缓存,可以在Bean初始化后,调用方法设置缓存过期时间。(TTLMs没有配置,只能通过代码设置)

@Configuration
public class ThymeleafConfig implements InitializingBean {

    @Resource(name = "defaultTemplateResolver")
    private SpringResourceTemplateResolver springResourceTemplateResolver;


    @Override
    public void afterPropertiesSet() throws Exception {
        springResourceTemplateResolver.setCacheTTLMs(Duration.ofSeconds(5).toMillis());
    }

}

方法二

直接注入名称为defaultTemplateResolverBean对象,不触发Thymeleaf的默认配置。

设置setCacheTTLMs缓存过期时间。

@Configuration
public class Config {

    private final ThymeleafProperties properties;
    private final ApplicationContext applicationContext;

    Config(ThymeleafProperties properties, ApplicationContext applicationContext) {
        this.properties = properties;
        this.applicationContext = applicationContext;
    }

    @Bean
    public SpringResourceTemplateResolver defaultTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(this.applicationContext);
        resolver.setPrefix(this.properties.getPrefix());
        resolver.setSuffix(this.properties.getSuffix());
        resolver.setTemplateMode(this.properties.getMode());
        if (this.properties.getEncoding() != null) {
            resolver.setCharacterEncoding(this.properties.getEncoding().name());
        }
        resolver.setCacheable(this.properties.isCache());
        Integer order = this.properties.getTemplateResolverOrder();
        if (order != null) {
            resolver.setOrder(order);
        }
        resolver.setCheckExistence(this.properties.isCheckTemplate());
        resolver.setCacheTTLMs(Duration.ofSeconds(5).toMillis());
        return resolver;
    }
}
Views: 725 · Posted: 2023-08-14

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh