我有一个 spring-boot/netty 应用程序设置来提供来自
main/resource/static
的一些静态文件。该应用程序还设置了压缩。
server:
compression:
enabled: true
mime-types: application/geo+json, application/geo+json-seq, text/html, text/xml, text/plain, text/css, text/javascript, application/javascript, application/json, image/jpeg, application/vnd.geo+json
min-response-size: 2KB
其中一个文件是
World_Countries_Boundaries.geojson
,大约10MB,包含国家边界。
目标是让这个文件 gzip 编码。
这个文件应该被认为是
application/geo+json
但是响应头显示application/octet-stream
。它也应该是 gzip 编码的。
我怎样才能压缩这个文件?我的第一个想法是 spring 没有正确解析 mime 类型。这让我在这里回答。但是这个答案仅适用于 servlet 容器。我的应用程序正在使用 netty。所以我尝试了 netty 工厂。
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.MimeMappings;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CustomMimeMappings implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {
@Override
public void customize(NettyReactiveWebServerFactory factory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("geojson", "application/geo+json");
factory.setMimeMappings(mappings);
}
}
此解决方案无法编译,因为 netty 工厂没有 setMimeMappings
方法。这就是我被困的地方。如何配置应用程序以正确解析 mime 类型并压缩此 geojson 文件?
应用程序配置看起来正确,但您需要添加一个 WebFluxConfigurer...
@Configuration
public class GeodataConfigurer implements WebFluxConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
var mimeTypes = new HashMap<String, MediaType>();
mimeTypes.put("geojson", MediaType.parseMediaType("application/geo+json"));
registry.addResourceHandler("/World_Countries_Boundaries.geojson")
.addResourceLocations("classpath://internal/
World_Countries_Boundaries.geojson")
.setMediaTypes(mimeTypes);
}
}