【问题标题】:Rapidoid. How to return response from lambda without rendering?快速样。如何在不渲染的情况下从 lambda 返回响应?
【发布时间】:2018-01-28 16:25:24
【问题描述】:

我需要从 lambda 返回一个响应,而不需要额外的渲染。我试着这样做:

On.post("/locations/{id:\\d+}").serve((Integer id, Req req, Resp resp) -> {
    if (!storageService.locationIsPresent(id)) {
        return resp.code(404).json("Location not found!");
    }
    try {
        String request = new String(req.body());
        Location location = mapper.readValue(request, Location.class);
        storageService.updateLocation(id, location.getCountry(), location.getCity(), location.getPlace(), location.getDistance() );
    } catch (Exception ex) {
        return resp.code(400).json("Bad request!");
    }
    return resp.code(200).body(EMPTY_RESP);
});

但结果我得到了一个例外:

ERROR | 20/Aug/2017 14:19:53:460 | executor2 | org.rapidoid.http.impl.lowlevel.LowLevelHttpIO | Error occurred when handling request! | error = java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.rapidoid.http.impl.RespImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.rapidoid.http.impl.RespImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

请告诉我如何正确操作。

而且我还想知道如何配置服务器,以便在每秒处理大量请求时获得更快的响应。因为在我的情况下它非常慢。

提前谢谢你!

【问题讨论】:

    标签: java http server


    【解决方案1】:

    尝试如下配置您的映射器, ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); 这是有关该问题的一些信息, http://www.baeldung.com/jackson-exception

    【讨论】:

    • 我的问题出在 Rapidoid,而不是 Jackson。我需要从 lambda 返回就绪响应,但 .serve() 试图再次将其呈现为 json,但我遇到了异常。
    【解决方案2】:

    遇到我的老问题并决定分享解决方案。 要返回预序列化的 JSON,可以这样做:

    On.get("/").serve((Integer id, Req req, Resp resp) -> {
       byte[] hardcodedJSON = "{\"x\": 123}".getBytes();
       return resp.contentType(MediaType.JSON).body(hardcodedJSON);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      相关资源
      最近更新 更多