【发布时间】:2021-05-16 04:46:49
【问题描述】:
我正在使用 Jerseys 客户端过滤器进行缓存。 请求读取和响应缓存值。 如何从客户端响应过滤器中读取实体主体,在使用来自客户端构建器的普通客户端调用时没有读取、getEntity 等方法。 我发现可能有用的唯一方法是 getEntityStream 但运气不佳。 使用 EhCache 缓存即时消息。 我是新手用户帮助:)
请求:
公共类ClientCacheResponseFilter实现ClientResponseFilter
private Ehcache ehcache;
public ClientCacheRequestFilter(Ehcache ehcache) {
this.ehcache = ehcache;
}
@Override
public void filter(ClientRequestContext request) throws IOException {
System.out.println("REQUEST FILTER");
if (!request.getMethod().equalsIgnoreCase("GET")) {
return;
}
String key = request.getUri().toString();
System.out.println("REQ KEY: " + key);
System.out.println("LOOKING FOR CACHE");
if (!ehcache.getClientCache().containsKey(key)) {
System.out.println("EMPTY CACHE");
return;
}
Cache<String, Object> cache = ehcache.getClientCache();
Object value = cache.get(key);
if (value != null) {
System.out.println("REQUEST FILTER - SECOND TIME READING CACHE");
System.out.println("CACHE ENTRY VALUE: " + value);
Response response = Response.ok()
.entity(value)
.type(MediaType.APPLICATION_JSON)
.build();
System.out.println("SENDING ENTITY");
request.abortWith(response);
}
}
回应:
private Ehcache ehcache;
public ClientCacheResponseFilter(Ehcache ehcache) {
this.ehcache = ehcache;
}
@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
System.out.println("RESPONSE FILTER");
if (!request.getMethod().equalsIgnoreCase("GET")) {
return;
}
if (response.getStatus() == 200) {
System.out.println("CACHING VALUE");
String key = request.getUri().toString();
ehcache.getClientCache().put(key, ?); // GET ENTITY FROM RESPONSE ?
}
}
客户来电:
WebTarget webTarget = CLIENT.target(API_URL).path("games");
Invocation.Builder builder = webTarget.request(MediaType.APPLICATION_JSON);
try (Response response = builder.get()) {
if (response.getStatus() == 200) {
return response.readEntity(new GenericType<List<Game>>() {
});
}
}
return Collections.EMPTY_LIST;
}
【问题讨论】:
-
嗨@bojan985,如果您可以提供一些代码以便我们了解您正在尝试(尝试)做什么,那将很有帮助。
标签: java jersey jersey-client