Skip to content

ResourceTemplate related APIs in ribbon module

allenxwang edited this page Sep 12, 2014 · 6 revisions

Using ribbon APIs, you can access HTTP resource (typically a REST endpoint on a server like http://localhost:/foo) programmatically using RequestTemplate

Step 1: Create an HttpResourceGroup

HttpResourceGroup httpResourceGroup = Ribbon.createHttpResourceGroup("movieServiceClient",
            ClientOptions.create()
                    .withMaxAutoRetriesNextServer(3)
                    .withConfigurationBasedServerList("localhost:" + RxMovieServer.DEFAULT_PORT));

The HttpResourceGroup is used to govern common attributes (like ClientOptions) that will be shared by HttpRequestTemplate created from it.

Step 2: Create an HttpRequestTemplate from HttpResourceGroup

HttpRequestTemplate<ByteBuf> recommendationsByUserIdTemplate = httpResourceGroup.newTemplateBuilder("recommendationsByUserId", ByteBuf.class)
            .withMethod("GET")
            .withUriTemplate("/users/{userId}/recommendations")
            .withHeader("X-Auth-Token", "abc")
            .withFallbackProvider(new RecommendationServiceFallbackHandler())
            .withResponseValidator(new RecommendationServiceResponseValidator())
            .build();

At this step, you can specify HTTP method, URI template, cache providers, Hystrix fallback and response validator for a particular HTTP resource. The response validator is responsible for checking the HTTP response and gives indication to Hystrix whether a fallback should be served.

Note that you use variable name like “{id}” instead of its real value in all APIs that support template. These variables will be later substituted with real values when the actual request is created.

Step 3: Create RequestBuilder and supply values for variables

  RibbonRequest<ByteBuf> request = recommendationsByUserIdTemplate.requestBuilder()
                      .withRequestProperty("userId", TEST_USER)
                      .build();

You can also supply the content of the Http request if it is request with payload like a POST request.

Step 4: Invoke RibbonRequest API

  Observable<ByteBuf> result = request.observe();