静态资源的Spring Boot ResourceLoader缓存
问题描述:
我有一个端点正在做一些处理,最后在ResponseEntity
内返回一个静态资源byte[]
。返回静态资源的服务层的当前实现如下。静态资源的Spring Boot ResourceLoader缓存
@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资源缓存机制,我可以使用这个资源保存在内存中,或者我需要在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,然后每次都返回缓存的实例。但是这可能会增加对象的内存占用。单身物体是优选的。只是如果你想缓存一个gif去ehcache可能不是一个合适的情况。 U还可以考虑将读取资源移动到Springs init方法生命周期回调中。
如果你有多个Gif需要根据输入(键/值)进行动态服务,那么你可以去任何第三方缓存实现,如番石榴或ehcache。