gpt4 book ai didi

java - 缓存 REST 方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:20 25 4
gpt4 key购买 nike

我正在尝试缓存 REST 方法,但服务器始终返回 200,并且响应不包含 Cache-Control header 。当缓存正常工作时,服务器应该返回 304。

休息方法

@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id, @Context Request request) {
TypedQuery<User> findByIdQuery = em
.createQuery(
"SELECT DISTINCT u FROM Product u WHERE u.id = :entityId ORDER BY u.id",
User.class);
findByIdQuery.setParameter("entityId", id);
User entity;
try {
entity = findByIdQuery.getSingleResult();
} catch (NoResultException nre) {
entity = null;
}
if (entity == null) {
return Response.status(Status.NOT_FOUND).build();
}

CacheControl cc= new CacheControl();
cc.setMaxAge(86400);

EntityTag etag= new EntityTag(Integer.toString(entity.hashCode()));
ResponseBuilder builder=request.evaluatePreconditions(etag);

if(builder==null)
{
builder=Response.ok(entity);
builder.tag(etag);
}


builder.cacheControl(cc);

return builder.build();
}

休息电话

  $scope.performSearchById = function() {

$http({
url: 'rest/product/' + $scope.search.id,
method: 'GET'
}).then(function(data){
$scope.searchResults = [data.data];

})

};

正确获取此信息的方法是什么?

最佳答案

我的一个较早的例子。请求应在 If-None-Match header 中包含 eTag。从缓存值服务器端计算的 eTag 将与请求 evaluatePreconditions 中的 If-None-Match header 中的值相匹配。如果两者相等,生成的构建器中将出现 304。如果不存在 header 或不匹配,则返回资源并发送 eTag

@GET
@Path("{id}")
public Response personFromId(@PathParam("id") final UUID id, @Context Request request) throws NoSuchAlgorithmException {
EntityTag eTag = null;
final Optional<Person> person = fromCache(id);
if (person.isPresent()) {
eTag = eTagFromPerson(person.get());
}

Response response;
ResponseBuilder responseBuilder = null;
if (null != eTag) {
responseBuilder = request.evaluatePreconditions(eTag);
}
if (null != responseBuilder) {
response = responseBuilder.build();
}
else {
response = personResponseFromId(id).tag(eTag).build();
}

return response;
}

eTag 可以通过以下方式计算:

private EntityTag eTagFromPerson(final Person person) throws NoSuchAlgorithmException {
return new EntityTag(DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-256")
.digest(person.toString().getBytes(StandardCharsets.UTF_8))));
}

或者通过toString(), hashCode()

关于java - 缓存 REST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49464752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com