简体   繁体   English

Spring Boot ResourceLoader缓存用于静态资源

[英]Spring Boot ResourceLoader cache for static resource

I've got an endpoint which is doing some processing and at the end returns a static resource as byte[] inside a ResponseEntity . 我有一个正在做一些处理的端点,最后在ResponseEntity内以byte[]返回静态资源。 The current implementation of the service layer, which returns the static resource is the following. 返回静态资源的服务层的当前实现如下。

@Service
public class MyService_Impl implements MyService {
    private ResourceLoader resourceLoader;

    @Autowired
    public MyService_Impl (ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public byte[] getMyResource() throws IOException {
        Resource myResource = resourceLoader.getResource("classpath:/static/my-resource.gif");
        InputStream is = myResource.getInputStream();
        return IOUtils.toByteArray(is);
    }
}

At peak I see large increase in the response time of this endpoint and my feeling is that this is the bottleneck as about 100 threads are requesting this resource simultaneously. 在高峰时,我看到此端点的响应时间大大增加,我的感觉是这是瓶颈,因为大约有100个线程同时请求此资源。 Is there a specific Spring Resource caching mechanism that I can use to keep this resource in memory or I need to introduce ehcache on getMyResource() method? 我是否可以使用一种特定的Spring Resource缓存机制来将该资源保留在内存中,或者需要在getMyResource()方法上引入ehcache

U can keep the converted gif object in a private variable inside the same object. U可以将转换后的gif对象保留在同一对象内的私有变量中。

@Service
public class MyService_Impl implements MyService {
    private ResourceLoader resourceLoader;
    private byte[] gifContent;

    @Autowired
    public MyService_Impl (ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public byte[] getMyResource() throws IOException {
        if(gifContent == null ){
        Resource myResource = resourceLoader.getResource("classpath:/static/my-resource.gif");
        InputStream is = myResource.getInputStream();
        gifContent = IOUtils.toByteArray(is);
        }
        return gitContent;
    }
}

This only reads the gif once and then returns every time the cached instance. 这只会读取gif一次,然后在每次缓存的实例时返回。 But this may create increase the memory footprint of your object. 但这可能会增加对象的内存占用量。 Singleton objects are preferable. 单件对象是优选的。 Just if u want to cache a single gif going for ehcache may not be a suitable case. 只是如果您要缓存用于ehcache的单个gif可能不是合适的情况。 U can also consider moving reading resource into Springs init method life cycle callback. 您还可以考虑将读取资源移至Springs初始化方法生命周期回调中。

If u have multiple Gif which need to be dynamically served depending on the input(Key/Value) then u can go for any third party cache implementations like guava or ehcache. 如果您有多个Gif,需要根据输入(键/值)动态提供Gif,那么您可以使用任何第三方缓存实现方式,例如guava或ehcache。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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