Spring Boot中缓存图片的方法有多种,以下是一些常见的方法:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CacheInterceptor());
}
}
public class CacheInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 设置Cache-Control和Expires头信息
response.setHeader("Cache-Control", "max-age=3600");
response.setHeader("Expires", "Sun, 01 Jan 2023 00:00:00 GMT");
return true;
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
spring:
cache:
type: ehcache
然后在需要缓存图片的方法上添加@Cacheable注解,并指定缓存的名称和缓存的key。
@Cacheable(cacheNames = "imageCache", key = "#url")
public byte[] getImage(String url) {
// 从网络或其他地方获取图片数据
return imageData;
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
redis:
host: localhost
port: 6379
然后在需要缓存图片的方法上添加@Cacheable注解,并指定缓存的名称和缓存的key。
@Cacheable(cacheNames = "imageCache", key = "#url")
public byte[] getImage(String url) {
// 从网络或其他地方获取图片数据
return imageData;
}
这些方法中,使用Http缓存和使用Ehcache/Redis缓存的方式更适合大规模的应用,可以充分利用缓存来提高图片的访问速度。