繁体   English   中英

Spring Boot ResourceLoader缓存用于静态资源

[英]Spring Boot ResourceLoader cache for static resource

我有一个正在做一些处理的端点,最后在ResponseEntity内以byte[]返回静态资源。 返回静态资源的服务层的当前实现如下。

@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);
    }
}

在高峰时,我看到此端点的响应时间大大增加,我的感觉是这是瓶颈,因为大约有100个线程同时请求此资源。 我是否可以使用一种特定的Spring Resource缓存机制来将该资源保留在内存中,或者需要在getMyResource()方法上引入ehcache

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;
    }
}

这只会读取gif一次,然后在每次缓存的实例时返回。 但这可能会增加对象的内存占用量。 单件对象是优选的。 只是如果您要缓存用于ehcache的单个gif可能不是合适的情况。 您还可以考虑将读取资源移至Springs初始化方法生命周期回调中。

如果您有多个Gif,需要根据输入(键/值)动态提供Gif,那么您可以使用任何第三方缓存实现方式,例如guava或ehcache。

暂无
暂无

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

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