Thymeleaf Tutorial: Chapter 16. Template Cache

  • Tutorial
Table of contents

16 Template Cache


Thymeleaf works thanks to a set of parsers for markup and text - which parses patterns in sequence (open tag, text, close tag, comment, etc.). And a series of processors , one for each type of behavior, that apply and change the pattern parsing sequence of events to create the expected results by combining the original pattern with our data.

It also includes - by default - a cache in which the analyzed patterns are stored; the sequence of events that result from reading and analyzing template files before they are processed. This is especially useful when working in a web application and is based on the following concepts:

  • I / O is almost always the slowest part of any application.
  • Cloning an existing sequence of events in memory is always much faster than reading a template file, parsing it, and creating a new sequence of events for it
  • Web applications usually have only a few dozen templates.
  • The template files are small and medium in size, and they do not change while the application is running

All this leads to the idea that caching the most used templates in a web application is possible without losing large amounts of memory, and also that it will save a lot of time that will be spent on I / O on a small set of files which, in fact, never change.

And how can we control this cache? Firstly, we learned that we can enable or disable the cache in the Resolver Template, even acting only on certain templates:

// По умолчанию true
templateResolver.setCacheable(false);
templateResolver.getCacheablePatternSpec().addPattern("/users/*");

In addition, we could change the configuration by installing our own Cache Manager object, which can be an instance of the default default CacheManager implementation:

// По умолчанию 200
StandardCacheManager cacheManager = new StandardCacheManager();
cacheManager.setTemplateCacheMaxSize(100);
...
templateEngine.setCacheManager(cacheManager);

Refer to javadoc API org.thymeleaf.cache. StandardCacheManager for more information on setting up caches.

Entries can be deleted manually from the template cache:

// Полностью очистить кеш
templateEngine.clearTemplateCache();
// Очистить определенный шаблон из кеша
templateEngine.clearTemplateCacheFor("/users/userList");

Also popular now: