【发布时间】:2011-11-26 09:10:10
【问题描述】:
澄清:这个问题是关于 GZIPping 一个基于 JAX-WS 的 REST 服务,但我决定更改主题以便更容易找到 p>
我正在通过 JAX-WS Provider <Source> 实现 REST 服务,并使用标准 Endpoint 发布它(原因是我想避免使用 servlet 容器或应用程序服务器)。
如果存在Accept-Encoding: gzip,有没有办法让服务器对响应内容进行gzip 压缩?
如何做
nicore 提供的示例确实有效,它允许您在没有 servlet 容器的嵌入式轻量级服务器之上制作 JAX-RS 样式的服务器,但需要考虑的时间不多。
如果您更喜欢自己管理课程(并在启动期间节省时间),您可以使用以下方法:
示例
JAX-RS 你好世界级:
@Path("/helloworld")
public class RestServer {
@GET
@Produces("text/html")
public String getMessage(){
System.out.println("sayHello()");
return "Hello, world!";
}
}
主要方法:
对于Simple 服务器:
public static void main(String[] args) throws Exception{
DefaultResourceConfig resourceConfig = new DefaultResourceConfig(RestServer.class);
// The following line is to enable GZIP when client accepts it
resourceConfig.getContainerResponseFilters().add(new GZIPContentEncodingFilter());
Closeable server = SimpleServerFactory.create("http://0.0.0.0:5555", resourceConfig);
try {
System.out.println("Press any key to stop the service...");
System.in.read();
} finally {
server.close();
}
}
对于Grizzly2:
public static void main(String[] args) throws Exception{
DefaultResourceConfig resourceConfig = new DefaultResourceConfig(RestServer.class);
// The following line is to enable GZIP when client accepts it
resourceConfig.getContainerResponseFilters().add(new GZIPContentEncodingFilter());
HttpServer server = GrizzlyServerFactory.createHttpServer("http://0.0.0.0:5555" , resourceConfig);
try {
System.out.println("Press any key to stop the service...");
System.in.read();
} finally {
server.stop();
}
}
已解决的依赖关系:
简单:
灰熊:
球衣:
通知
确保 javax.ws.rs 存档没有进入您的类路径,因为它与 Jersey 的实现冲突。这里最糟糕的是没有记录的无声 404 错误 - 仅记录了 FINER 级别的小注释。
【问题讨论】:
-
这不就是靠容器(Tomcat、Jetty等)来整理的吗?
-
我们目前没有使用 servlet 容器,而这个 REST 服务可能是我们唯一需要它的地方。我真的不认为为了压缩这个小家伙而检查、设置和调整整个 servlet 容器是不值得的。所以我想避免使用一个,如果可能的话。
-
为清楚起见,这些示例适用于 Jersey 1.x,不适用于 Jersey 2.x。后一种情况参见文档:jersey.java.net/documentation/latest/…
标签: java rest jax-rs embedded-server