【发布时间】:2015-06-19 06:22:38
【问题描述】:
我有 springboot 应用程序,它从 url 请求图像,然后将其显示在浏览器上。我想使用缓存控制标头缓存我的响应。
我使用ResponseEntity 并且已经将我的标题设置为eTag。我已经在浏览器中检查了响应标头,它显示:
Cache-Control:"max-age=31536000, public"
Content-Type:"image/jpeg;charset=UTF-8"
Etag:"db577053a18fa88f62293fbf1bd4b1ee"
我的请求也有If-None-Match 标头。但是,我总是得到200 状态而不是304。
这是我的代码
@RequestMapping(value = "/getimage", method=RequestMethod.GET)
public ResponseEntity<byte[]> getImage() throws Exception {
String url = "www.example.com/image.jpeg";
String eTag = getEtag(url);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("image", "jpeg"));
headers.add("Cache-Control", "max-age=31536000, public");
headers.add("ETag", eTag);
URL imageUrl = new URL(url);
InputStream is = imageUrl.openStream();
BufferedImage imBuff = ImageIO.read(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(imBuff, "jpeg", baos);
byte[] image = baos.toByteArray();
return new ResponseEntity<byte[]>(image, headers, HttpStatus.OK);
}
谁能帮帮我?
更新
我尝试使用Unable to cache images served by Spring MVC 中描述的方法,所以我的代码变成了:
@RequestMapping(value = "/getimage", method=RequestMethod.GET)
public ResponseEntity<byte[]> getImage() throws Exception {
String url = "www.example.com/image.jpeg";
String eTag = getEtag(url);
URL imageUrl = new URL(url);
HttpURLConnection httpCon = (HttpURLConnection)imageUrl.openConnection();
long lastModified = httpCon.getLastModified();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("image", "jpeg"));
headers.add("Cache-Control", "max-age=31536000, public");
headers.add("ETag", eTag);
headers.add("Last-Modified", new Date(lastModified).toString());
if (webRequest.checkNotModified(eTag)) {
return null;
}
InputStream is = imageUrl.openStream();
BufferedImage imBuff = ImageIO.read(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(imBuff, "jpeg", baos);
byte[] image = baos.toByteArray();
return new ResponseEntity<byte[]>(image, headers, HttpStatus.OK);
}
但现在我总是得到304 状态码,即使我更改了网址。我通过eTag 和last-modified 检查了webRequest.checkIsNotModified(...),它总是返回true。我在这里做错了吗?
【问题讨论】:
-
感谢@NitinArora 我已经尝试过使用这里描述的方法stackoverflow.com/questions/17821518/… 但是,
webRequest.checkNotModified(...)总是返回 true,使用eTag或lastModified。你能帮帮我吗? -
如果您的图像始终是静态的,那么您是在尝试动态提供它吗?使用静态资源来提供图像。这是参考docs.spring.io/spring-framework/docs/4.1.4.RELEASE/…
-
Mm.. 实际上,我将使用 RequestMapping 路径变量作为图像源 url,然后对该图像进行一些处理,然后在浏览器中显示它。它算作服务静态资源吗?我已经阅读了该文档,但我认为这不是我想要的。
-
不,它不算作静态资源。只是想了解用例。