0

I want to store thymleaf template into database instead of file system.

Because of If I store into file system, This will be major issue if we need to run several nodes of application to distribute the load across servers. Templates should not be big so it will be easy to store them in DB.

Till now I read file through pre-defined path from context, using code like

FileTemplateResolver resolver = new FileTemplateResolver();
String filePath = env.getProperty("external.notification.template.dir");
resolver.setPrefix(filePath);
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(templateEngine.getTemplateResolvers().size());
resolver.setCacheable(false);
templateEngine.addTemplateResolver(resolver);

It can be possible to create temporary file using blob and read from same location. But There may be good approach available.

Anybody know configuration for to read blob data.

Is there anyway to read blob format file using thymleaf context?

bNd
  • 7,512
  • 7
  • 39
  • 72
  • Don't think it is supported out-of-the-box but implementing a `TemplateResolver` which does what you want shouldn't be that hard. – M. Deinum Mar 18 '16 at 11:26
  • @M.Deinum Thanks. you are right. I didn't found any API related to same. so it is possible only by creating temporary file and read it. is it correct/good approach if I go with database solution? – bNd Mar 18 '16 at 11:32
  • No why should it write to a file. Just create a resolver that returns the template from the database, you don't need to write it to disc first... – M. Deinum Mar 18 '16 at 11:35
  • @M.Deinum ohk. let me do with TemplateResolver. thanks. – bNd Mar 18 '16 at 11:36
  • I think it's not correct to do load balancing this way :) If you have several nodes you must use load balancer like this http://i.stack.imgur.com/amxhy.png – sanluck Mar 21 '16 at 04:02

1 Answers1

0

I have created DbTemplateResolver class which extends TemplateResolver. It has inner class, that have a db call which fetch image data from the tabel.

private class DbResourceResolver implements IResourceResolver {

        @Override
        public InputStream getResourceAsStream(TemplateProcessingParameters params, String resourceName) {

            NotificationTemplate template = templateService.getNotificationTemplateByName(resourceName);
            if (template != null) {
                return new ByteArrayInputStream(template.getFileData());
            }
            return null;
        }

        @Override
        public String getName() {
            return "dbResourceResolver";
        }
    }

This will be call on process method call.

mergedMessage = templateEngine.process(fileName, ctx);
bNd
  • 7,512
  • 7
  • 39
  • 72