8.2 Service Discovery

Using the CLI

If you are creating your project using the Micronaut CLI, supply either of discovery-consul or discovery-eureka features to enable service-discovery in your project:

  1. $ mn create-app my-app features discovery-consul

Service Discovery enables the ability for Microservices to find each other without necessarily knowing the physical location or IP address of associated services.

There are many ways Service Discovery can be implemented, including:

  • Manually implement Service Discovery using DNS without requiring a third party tool or component.

  • Use a discovery server such as Eureka, Consul or ZooKeeper.

  • Delegate the work to a container runtime, such as Kubernetes.

With that in mind, Micronaut tries to flexible to support all of these approaches. As of this writing, Micronaut features integrated support for the popular Service Discovery servers:

  • Eureka

  • Consul

To include Service Discovery in your application simply the first step is to add the discovery-client dependency to your application:

  1. implementation("io.micronaut:micronaut-discovery-client")
  1. <dependency>
  2. <groupId>io.micronaut</groupId>
  3. <artifactId>micronaut-discovery-client</artifactId>
  4. </dependency>

The discovery-client dependency provides implementations of the DiscoveryClient interface.

The DiscoveryClient is fairly simple and provides two main entry points:

Both methods return Publisher instances since the operation to retrieve service ID information may result in a blocking network call depending on the underlying implementation.

If you are using Micronaut’s cache module, the default implementation of the DiscoveryClient interface is CachingCompositeDiscoveryClient which merges all other DiscoveryClient beans into a single bean and provides caching of the results of the methods. The default behaviour is to cache for 30 seconds. This cache can be disabled in application configuration:

Disabling the Discovery Client Cache

  1. micronaut:
  2. caches:
  3. discovery-client:
  4. enabled: false

Alternatively you can alter the cache’s expiration policy:

Configuring the Discovery Client Cache

  1. micronaut:
  2. caches:
  3. discovery-client:
  4. expire-after-access: 60s

See the DiscoveryClientCacheConfiguration class for available configuration options.