我有一个端点正在进行一些处理,最后在byte[]
内返回一个静态资源ResponseEntity
。返回静态资源的服务层的当前实现如下。
@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资源缓存机制可用于将此资源保留在内存中,或者我需要在ehcache
方法上引入getMyResource()
?
答案 0 :(得分:0)
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 init方法生命周期回调中。
如果您有多个Gif需要动态服务,具体取决于输入(键/值),那么您可以选择任何第三方缓存实现,如番石榴或ehcache。