如何使用 CXF、JAX-RS 和 HTTP Caching
2022-09-03 00:29:36
实际上,答案并非特定于 CXF - 它是纯 JAX-RS:
// IPersonService.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
@GET
@Path("/person/{id}")
Response getPerson(@PathParam("id") String id, @Context Request request);
// PersonServiceImpl.java
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
public Response getPerson(String name, Request request) {
Person person = _dao.getPerson(name);
if (person == null) {
return Response.noContent().build();
}
EntityTag eTag = new EntityTag(person.getUUID() + "-" + person.getVersion());
CacheControl cc = new CacheControl();
cc.setMaxAge(600);
ResponseBuilder builder = request.evaluatePreconditions(person.getUpdated(), eTag);
if (builder == null) {
builder = Response.ok(person);
}
return builder.cacheControl(cc).lastModified(person.getUpdated()).build();
}
在即将推出的 JAX-RS 2.0 中,将能够以声明方式应用高速缓存控制,如 http://jalg.net/2012/09/declarative-cache-control-with-jax-rs-2-0/
您至少可以在泽西岛进行测试。虽然不确定CXF和RESTEasy。