简体   繁体   中英

How to cache image files in spring java application?

In my public facing web app, images ( along with meta data) are shown like in photo album app which is being developed using Spring framework. What I want is to cache in RAM all images ( thousands of them) from the file system so that when image tag like is encountered in HTML:

<img src="images/folder1/subfolder/myimage.jpg" />

the image is served from cache memory and not from disk by tomcat webserver for high performance.

How to achieve this in spring framework web application?

If mongodb is used to store web content like image meta data, how to achieve above in this scenario in the same spring web app?

So there are two answers one involving no mongodb and one involving mongodb.

Spring Cache is easy to setup initially and is quite configurable. If you provide a dedicated caching library, it will use that; if not, it will use an in memory concurrent hash map to hold cached data. You will need a dedicated controller, that may look similar to this:

@ResponseBody
@RequestMapping(value = "/images/{path}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@Cacheable("images")
public byte[] image(@PathVariable path) throws IOException {
    InputStream in = servletContext.getResourceAsStream("images/"+path);
    return IOUtils.toByteArray(in);
}

This loads the image first time is called and caches it. Each time method is called with the same parameters cache value is returned.

I would first make sure this image caching is actually a boost to the performance. But if you decide to use it, probably you want to use a dedicated library for the cache, not the default one that could fill the heap very fast. But of course it depends on the application.

Read about the Spring Cache https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html

@Christaan's answer can also be extended to cache externally referenced images locally to your solution, for use in say captive environments. For example:

@ResponseBody
@RequestMapping(value = "/sample-image", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@Cacheable("images")
public byte[] image() throws IOException {

            URL url = new URL("http://iminsys.com/assets/images/pages/about/edrich.jpg");
            InputStream in = new BufferedInputStream(url.openStream());
            return FileCopyUtils.copyToByteArray(in); // using Spring's FileCopyUtils
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM