简体   繁体   中英

Jackson JSON how to set http connection and read timeout

(jersey-common=2.21.0, jackson-core=2.6.1)

How do I set http connection timeouts (connect, read) if createParser(URL url) was invoked? What is the default values used?

    JsonFactory jsonF = new JsonFactory();
    jsonF.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
    JsonParser jsonP = jsonF.createParser(url); // URL instance
    try {
        JsonToken token;
        while ( (token=jsonP.nextToken()) != null) {
           if (token == JsonToken.START_OBJECT)
           ..rest "json sax" parser code...
        }
    } finally {
        jsonP.close();
    }

I have few times a week recurring problem when webapp stops reading json sources, task is autorun every 30 minutes. I suspect this http call stalls and starts piling up until JVM goes down.

Should I not use createParser(URL) function in production apps?

You could hack the values

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

More on the settings can be found on https://docs.oracle.com/javase/7/docs/technotes/guides/net/properties.html

Or you can instead do a proper call and then pass the result into the json parser. I would go with the latter.

So to put it simply while URL is great light weight alternative I suggest switching to apache http client or some high level solution.

That particular read method is for convenience, but not configurable and generally not that useful for most production usage.

Instead, you may want to obtain InputStream from URL endpoints using other means, then pass it to ObjectMapper / ObjectReader ; this allows for full control over details of connection, timeouts and so forth. It allows lets you use other HTTP clients than the default one JDK comes equipped with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM