Client

To create a client in Micronaut for calling a Micronaut server, you can leverage Micronaut's HTTP client capabilities which are built into the framework. Micronaut's HTTP client allows for the creation of declarative clients using annotations, making it both easy to use and efficient. Here's a step-by-step guide to create a declarative HTTP client in Micronaut:

Example App Creation

# https://guides.micronaut.io/latest/micronaut-http-client-maven-kotlin.html
main() {
  # Changed to gradle from the original maven in tutorial
  mn create-app example.micronaut.micronautguide \
      --features=http-client,graalvm \
      --build=gradle_kotlin \
      --lang=kotlin \
      --test=junit

}

main "${@}" || exit 1

1. Define the Client Interface

Example with GET

Example with GET

First, define an interface that represents the client. Use annotations to configure the client's target path and any default configurations.

import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.annotation.Client;

@Client("/api") // Base path of your server endpoints
public interface MyServerClient {

    @Get("/resource")
    String getResource();
}

In this example, @Client is used to indicate that this interface is an HTTP client and /api is the base path of your server endpoints. @Get("/resource") defines a method to fetch a resource from the server's /api/resource endpoint.

Example with POST

Example with POST

To create a POST request with a Micronaut client, define a @Post method in your client interface. Use @Body to annotate a method parameter that should be sent as the request body. Here's a basic example:

import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.client.annotation.Client;

@Client("/api")
public interface MyServerClient {

    @Post("/submit")
    MyResponse submitData(@Body MyRequest requestData);
}

In this example, @Post("/submit") defines a method for sending data to the server's /api/submit endpoint. The @Body annotation indicates that requestData should be serialized and sent as the request body. You'll need to replace MyRequest and MyResponse with the actual classes representing your request and response data structures.

2. Inject and Use the Client

2. Inject and Use the Client

You can inject this client into any bean managed by Micronaut's dependency injection container, such as a controller or a service, and then call its methods to communicate with the server.

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

import javax.inject.Inject;

@Controller("/client")
public class MyClientController {

    @Inject
    private MyServerClient myServerClient;

    @Get("/call")
    public String callServer() {
        return myServerClient.getResource();
    }
}

3. Configuration (Optional)

Configuration (Optional)

For local development or default settings, you might not need additional configuration. However, for production or specific environments, you can configure your client in application.yml:

micronaut:
  http:
    services:
      myserver: # Should match the name or value in @Client if specified
        urls:
          - http://localhost:8080
        read-timeout: 10s
        connection-pool:
          max-connections: 10
          max-life-time: 30m

This configuration specifies the base URL for the client, along with other settings like read timeout and connection pool options.

Best Practices

  • Interface Segregation & Single Responsibility: Define different client interfaces for different parts of your server API to keep your clients focused and modular.
  • Error Handling: Implement a consistent error handling strategy for your clients. Use @Error handling in your client interface to manage different types of server responses.
  • Performance: Utilize Micronaut's built-in features like reactive programming support to handle requests efficiently.

Conclusion

By following these steps, you create a Micronaut HTTP client that is capable of calling your Micronaut server. This approach leverages Micronaut's compile-time DI and AOP capabilities to create efficient, type-safe HTTP clients.

References


Children
  1. Dependencies
  2. If Running Slow