0% found this document useful (0 votes)
12 views31 pages

Micronaut Declarative HTTPClient

Uploaded by

puneet.behl007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

Micronaut Declarative HTTPClient

Uploaded by

puneet.behl007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WEBINAR

HOME TO GRAILS & MICRONAUT

Micronaut Declarative HTTP Client


Presented By: Puneet Behl

© 2019, Object Computing, Inc. (OCI). All rights reserved. No part of these notes may be reproduced, stored in a retrieval system, or transmitted, in any [Link]
form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior, written permission of Object Computing, Inc. (OCI)
About Me

Software Engineer
Member of 2GM Team
@puneetbhl

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 2


Motivation

The motivation behind creating a new HTTP client for Micronaut centers
around providing a rich set of cloud native features that in total did not
exists in any solution at that time.

A non-blocking HTTP client based on Netty that has integration with


service-discovery, load-balancing and many more other features is the
result.

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 3


Dependency
To use the HTTP client, just add the following dependency:

[Link]
implementation “[Link]:micronaut-http-client"

<dependency> [Link]
<groupId>[Link]</groupId>
<artifactId>micronaut-http-client</artifactId>
<scope>compile</scope>
</dependency>

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 4


Usage
To inject the client use @Client with @Inject annotation with a URL of the API

@Client("[Link] @Inject RxHttpClient rxHttpClient;

[Link]([Link]("/v2/top-headlines?country=in")
.header("X-Api-Key", "API_KEY_VALUE"), [Link]([Link]));

@Singleton
public class NewsService { Create the Client via ApplicationContext
private final HttpClient httpClient;

public NewsService(ApplicationContext applicationContext) {


[Link] = [Link]([Link], "/news");
}
}

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 5


HttpRequest Factory

METHOD DESCRIPTION ALLOWS BODY

[Link]([Link]) Constructs an HTTP GET request FALSE

[Link]([Link]) Constructs an HTTP OPTIONS request FALSE

[Link]([Link]) Constructs an HTTP HEAD request FALSE

[Link]([Link],T) Constructs an HTTP POST request TRUE

[Link]([Link],T) Constructs an HTTP PUT request TRUE

[Link]([Link],T) Constructs an HTTP PATCH request TRUE

[Link]([Link]) Constructs an HTTP DELETE request TRUE

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 6


Errors

@Client("[Link] RxHttpClient rxHttpClient;

String uri = [Link]("/pet/{name}")


.expand([Link]("name", "dodo"))
.toString();

[Link]([Link], () -> {
[Link]().retrieve(uri, [Link]);
});

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 7


Debugging
<logger name="[Link]" level="TRACE" />

Client Specific
micronaut:
http: Logging
client: Configurations
logger-name: mylogger
services:
other-client:
logger-name: [Link]

<logger name="mylogger" level="DEBUG"/>


<logger name="[Link]" level="TRACE"/>

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 8


Demo
String uri = [Link]("/v2/top-headlines")
.queryParam("country", "in")
.queryParam("apiKey", NEWS_API_KEY) A Basic HTTP Client
.build() Request
.toString();

[Link]("/v2/top-headlines?
country=in&apiKey=837fe7ca80a34f48bdbdd2c64c9d91ad", uri);

Map newsApiResult = [Link]().retrieve(uri, [Link]);

[Link](
"ok",
[Link]("status")
);

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 9


Declarative Client

The declarative client can be created by annotating


any interface or abstract class with @Client annotation.

@Client(“[Link] @QueryValue is Optional


public interface NewsClient {

@Get("/v2/top-headlines{?country}")
Map fetchHeadlines(@QueryValue String country);
}

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 10


Client Configurations

1. Proxy 5. Logging

2. Thread Pool 6. SSL

3. Timeouts 7. Connection Pooling

4. Follow Redirects 8. More…

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 11


Validation

implementation "[Link]:micronaut-validation"

@Post
Single<Pet> save(@NotBlank String name, @Min(1L) int age);

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 12


JSON Streaming

@Client("/news")
public interface NewsSteamingClient {

@Get(value = "/headlines/{country}", processes = MediaType.APPLICATION_JSON_STREAM)


Flowable<NewsArticle> headlines(@PathVariable String country);
}

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 13


Customizing Headers
@Client("[Link]
@Header(name = "X-Api-Key", value = "${[Link]}")
public interface NewsClient {

@Get(value = "/v2/top-headlines", processes = MediaType.APPLICATION_JSON)


@Override
Flowable<HttpResponse<NewsArticleResult>> fetchLiveTopAndBreakingNewsHeadlines();

Alternatively you can supply a


NEWS_API_KEY environment
news: variable and the value will be
api:
key: 837fe7ca80a34f48bdbdd2c64c9d91ad
populated

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 14


Client Filter

@Filter(“/v2/top-headlines/**")
public class NewsApiFilter implements HttpClientFilter {

private String apiKey;

public NewsApiFilter(@Value("${[Link]}") String apiKey) {


[Link] = apiKey;
}

@Override
public Publisher<? extends HttpResponse<?>> doFilter(MutableHttpRequest<?>
request, ClientFilterChain chain) {
return [Link]([Link]("X-Api-Key", apiKey));
}

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 15


Multipart Upload

MultipartBody multipartBody = [Link]()


.addPart("file", "[Link]", new File("[Link]"))
.build()

@Client("[Link]
public interface PetClient {

@Post(uri = "/image", produces = MediaType.MULTIPART_FORM_DATA)


Single<HttpResponse<String>> uploadImage(@Body MultipartBody body);

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 16


Demo

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 17


Retry
Enable retries with a simple annotation. If all attempts fail the original
exception is thrown.

@Retryable(delay = "2s", attempts = "3")


@Client("[Link]
public interface PetClient extends PetApi {

@Override
@Get("{name}")
Single<HttpResponse<Pet>> get(@PathVariable String name);

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 18


Circuit Breaker

Same thing as @Retry but with reset option

@CircuitBreaker(delay = "2s", attempts = "3")


@Client("[Link]
public interface PetClient extends PetApi {

@Override
@Get("{name}")
Single<HttpResponse<Pet>> get(@PathVariable String name);

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 19


Fallback
The @Client annotation is annotated with @Recoverable
When an exception is thrown, a fallback is searched for and executed

@Fallback
public class PetFallback implements PetApi {

private static final Logger LOG = [Link]([Link]);


public static final int FALLBACK_PET_AGE = 10;

@Override
public Single<HttpResponse<Pet>> get(String name) {
if ([Link]()) {
[Link]("Fallback called for PetApi get method call");
}
return [Link]([Link](new Pet(name, FALLBACK_PET_AGE)));
}
}

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 20


Demo

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 21


Service Discovery

implementation ‘[Link]:micronaut-discovery-client'

@Client("pets-server")
public interface PetClient {

...

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 22


Load Balancing

Round robin by default


Static list or service discovery
Provide your own implementation through the LoadBalancer interface

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 23


Tracing

All tracing integrations automatically support the HTTP client; declarative and
imperative styles.

Zipkin, Jaeger

[Link]

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 24


Demo

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 25


Using Micronaut HTTP Client with Spring

@Client("[Link]
public interface PetClient {

@GetMapping(“/pet/{name}")
public Pet get(@PathVariable String name)

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 26


Using Micronaut HTTP Client with Grails

Micronaut is the parent application context of Grails 4 so you can take advantage of
many Micronaut features including HTTP Client.

@Client("[Link]
interface GrailsAppForgeClient {

@Get("/{version}/profiles")
List<Map> profiles(String version)
}

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 27


Questions?

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 28


Micronaut Resources

• [Link]/micronautfw

• [Link]

• [Link]

• [Link]/[Link]

• [Link]/micronaut-projects/micronaut-core

• [Link]/micronaut-projects/micronaut-examples

• [Link]/products/micronaut

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 29


LEARN MORE ABOUT OCI EVENTS AND TRAINING
HOME TO GRAILS & MICRONAUT

Events:
● [Link]/events

Training:
● [Link]/training
● [Link]
● [Link]

Or email info@[Link] to schedule a private tech talk or custom workshop for your team.
We can deliver these events on site, online, or in our state-of-the-art, Midwest training lab.

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 30


CONNECT WITH US

1+ (314) 579-0066

@objectcomputing

[Link]

© 2019, Object Computing, Inc. (OCI). All rights reserved. [Link] 31

You might also like