Using Cloud Instance Metadata
When Micronaut detects it is running on any of the cloud platforms listed above, such as Google Compute or AWS EC2, upon startup Micronaut will populate the interface ComputeInstanceMetadata.
As of Micronaut 2.1.x this logic depends on the presence of the appropriate core Cloud module for Oracle Cloud, AWS or GCP. |
All of this data is merged together into the metadata
property for the running ServiceInstance.
If you need to access the metadata for your application instance you can use the interface EmbeddedServerInstance, and call getMetadata()
which will get a map of all of the metadata.
If you are connecting remotely via client, the instance metadata can be referenced once you have retrieved a ServiceInstance from either the LoadBalancer or DiscoveryClient APIs.
The Netflix Ribbon client side load balancer can be configured to use the metadata to do zone aware client side load balancing. See Client Side Load Balancing |
To obtain metadata for a service via Service Discovery use the LoadBalancerResolver interface to resolve a LoadBalancer and obtain a reference to a service by identifier:
Obtaining Metadata for a Service instance
LoadBalancer loadBalancer = loadBalancerResolver.resolve("some-service");
Flowable.fromPublisher(
loadBalancer.select()
).subscribe((instance) ->
ConvertibleValues<String> metaData = instance.getMetadata();
...
);
The EmbeddedServerInstance is available through event listeners that listen for the ServiceReadyEvent. The @EventListener annotation makes it easy to listen for the event inside one of your existing beans.
To obtain metadata for the locally running server use an EventListener for the ServiceReadyEvent:
Obtaining Metadata for a Local Server
@EventListener
void onServiceStarted(ServiceReadyEvent event) {
ServiceInstance serviceInstance = event.getSource()
ConvertibleValues<String> metadata = serviceInstance.metadata
}