Riptide noun, /ˈrɪp.taɪd/: strong flow of water away from the shore
Riptide is a library that implements client-side response routing. It tries to fill the gap between the HTTP protocol and Java. Riptide allows users to leverage the power of HTTP with its unique API.
- Technology stack: Based on
spring-web
and uses the same foundation as Spring's RestTemplate. - Status: Actively maintained and used in production.
- Riptide is unique in the way that it doesn't abstract HTTP away, but rather embrace it!
Usage typically looks like this:
http.get("/repos/{org}/{repo}/contributors", "zalando", "riptide")
.dispatch(series(),
on(SUCCESSFUL).call(listOf(User.class), users ->
users.forEach(System.out::println)));
Feel free to compare this e.g. to Feign or Retrofit.
- full access to the underlying HTTP client
- resilience built into it
- isolated thread pools, connection pools and bounded queues
- transient fault detection via riptide-faults
- retries and circuit breaker via Failsafe integration
- backup requests via riptide-backup
- timeouts
- encourages the use of
- fallbacks
- content negotiation
- robust error handling
- elegant syntax
- type-safe
- asynchronous by default
- synchronous return values on demand
application/problem+json
support- streaming
Most modern clients try to adapt HTTP to a single-return paradigm as shown in the following example. Even though this may be perfectly suitable for most applications it takes away a lot of the power that comes with HTTP. It's not easy to support multiple different return values, i.e. distinct happy cases. Access to response headers or manual content negotiation are also harder to do.
@GET
@Path("/repos/{org}/{repo}/contributors")
List<User> getContributors(@PathParam String org, @PathParam String repo);
Riptide tries to counter this by providing a different approach to leverage the power of HTTP. Go checkout the concept document for more details.
- Spring 5
Add the following dependency to your project:
<dependency>
<groupId>org.zalando</groupId>
<artifactId>riptide-core</artifactId>
<version>${riptide.version}</version>
</dependency>
Additional modules/artifacts of Riptide always share the same version number.
Alternatively, you can import our bill of materials...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>riptide-bom</artifactId>
<version>${riptide.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
... which allows you to omit versions:
<dependencies>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>riptide-core</artifactId>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>riptide-failsafe</artifactId>
</dependency>
<dependency>
<groupId>org.zalando</groupId>
<artifactId>riptide-faults</artifactId>
</dependency>
</dependencies>
Integration of your typical Spring Boot Application with Riptide, Logbook and Tracer can be greatly simplified by using the Riptide: Spring Boot Starter. Go check it out!
Http.builder()
.executor(Executors.newCachedThreadPool())
.requestFactory(new HttpComponentsClientHttpRequestFactory())
.baseUrl("https://api.github.com")
.converter(new MappingJackson2HttpMessageConverter())
.converter(new Jaxb2RootElementHttpMessageConverter())
.plugin(new OriginalStackTracePlugin())
.build();
The following code is the bare minimum, since a request factory is required:
Http.builder()
.executor(Executors.newCachedThreadPool())
.requestFactory(new HttpComponentsClientHttpRequestFactory())
.build();
This defaults to:
- no base URL
- same list of converters as
new RestTemplate()
OriginalStackTracePlugin
In order to configure the thread pool correctly, please refer to How to set an ideal thread pool size.
A full-blown request may contain any of the following aspects: HTTP method, request URI, query parameters, headers and a body:
http.post("/sales-order")
.queryParam("async", "false")
.contentType(CART)
.accept(SALES_ORDER)
.header("Client-IP", "127.0.0.1")
.body(cart)
//...
Riptide supports the following HTTP methods: get
, head
, post
, put
, patch
, delete
, options
and trace
respectively. Query parameters can either be provided individually using queryParam(String, String)
or multiple at
once with queryParams(Multimap<String, String>)
.
The following operations are applied to URI Templates (get(String, Object...)
) and URIs (get(URI)
) respectively:
- parameter expansion, e.g
/{id}
(seeUriTemplate.expand
) - encoding
- none, used as is
- expected to be already encoded
- after respective transformation
- resolved against Base URL (if present)
- Query String (merged with existing)
- Normalization
The URI Resolution table shows some examples how URIs are resolved against Base URLs, based on the chosen resolution strategy.
The Content-Type
- and Accept
-header have type-safe methods in addition to the generic support that is
header(String, String)
and headers(HttpHeaders)
.
Riptide is special in the way it handles responses. Rather than having a single return value, you need to register callbacks. Traditionally you would attach different callbacks for different response status codes, alternatively there are also built-in routing capabilities on status code families (called series in Spring) as well as on content types.
http.post("/sales-order")
// ...
.dispatch(series(),
on(SUCCESSFUL).dispatch(contentType(),
on(SALES_ORDER).call(SalesOrder.class, this::persist),
on(CLIENT_ERROR).dispatch(status(),
on(CONFLICT).call(this::retry),
on(PRECONDITION_FAILED).call(this::readAgainAndRetry),
anyStatus().call(problemHandling())),
on(SERVER_ERROR).dispatch(status(),
on(SERVICE_UNAVAILABLE).call(this::scheduleRetryLater))));
The callbacks can have the following signatures:
persist(SalesOrder)
retry(ClientHttpResponse)
scheduleRetryLater()
Riptide will return a CompletableFuture<ClientHttpResponse>
. That means you can choose to chain transformations/callbacks or block
on it.
If you need proper return values take a look at Riptide: Capture.
The only special custom exception you may get is UnexpectedResponseException
, if and only if there was no matching condition and
no wildcard condition either.
Riptide comes with a way to register extensions in the form of plugins.
OriginalStackTracePlugin
, preserves stack traces when executing requests asynchronouslyAuthorizationPlugin
, addsAuthorization
supportBackupRequestPlugin
, adds backup requestsFailsafePlugin
, adds retries and circuit breaker supportMetricsPlugin
, adds metrics for request durationTransientFaultPlugin
, detects transient faults, e.g. network issuesTimeoutPlugin
, applies timeouts to the whole call (including retries, network latency, etc.)
Whenever you encounter the need to perform some repetitive task on the futures returned by a remote call, you may consider implementing a custom Plugin for it.
Plugins are executed in phases:
Please consult the Plugin documentation for details.
Riptide is built on the same foundation as Spring's RestTemplate
and AsyncRestTemplate
. That allows us, with a small
trick, to use the same testing facilities, the MockRestServiceServer
:
RestTemplate template = new RestTemplate();
MockRestServiceServer server = MockRestServiceServer.createServer(template);
ClientHttpRequestFactory requestFactory = template.getRequestFactory();
Http.builder()
.requestFactory(requestFactory)
// continue configuration
We basically use an intermediate RestTemplate
as a holder of the special ClientHttpRequestFactory
that the
MockRestServiceServer
manages.
If you are using the Spring Boot Starter the test setup is provided by a convenient annotation @RiptideClientTest
,
see here.
If you have questions, concerns, bug reports, etc., please file an issue in this repository's Issue Tracker.
To contribute, simply make a pull request and add a brief description (1-2 sentences) of your addition or change. For more details check the contribution guidelines.