Implementing Connect- and Read Timeouts with JAX-RS 2.1 Client and Java EE 8

Java EE 8 with JAX-RS 2.1 comes with configuration for read and connect timeouts (in Java EE 7 you had to use vendor-specific properties):


import java.util.concurrent.TimeUnit;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class JAXRSClientTimeoutTest {

    @Rule
    public ExpectedException expected = ExpectedException.none();

    @Test
    public void connectTimeout() {
        expected.expect(ProcessingException.class);
        Client client = ClientBuilder.
                newBuilder().
                connectTimeout(1, TimeUnit.MILLISECONDS).
                build();
        //no one listens here
        client.target("http://127.0.0.1").
                request().
                get();
    }

    @Test
    public void readTimeout() {
        expected.expect(ProcessingException.class);
        Client client = ClientBuilder.
                newBuilder().
                readTimeout(1, TimeUnit.MILLISECONDS).
                build();
        //airhacks.com is too slow to answer in 1ms
        client.target("http://airhacks.com").
                request().
                get();
    }
}

See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License