1

I have a microservice written in Spring Boot and leveraging Spring Cloud Kubernetes that runs in Kubernetes as follows:

  • a Kubernetes service (foo-service)
  • two instances of foo-service (pods) sitting behind the service, each running the Spring Boot application

I can list all of the instances of the service by using the Spring Cloud Kubernetes DiscoveryClient as follows:

List<ServiceInstance> allInstances = discoveryClient.getInstances("foo-service")

How do I get the instanceId of the instance that is executing this code?

Mark
  • 4,970
  • 5
  • 42
  • 66
  • I am a little bit confused by "currently running instance"... can you elaborate a bit more please? – Eugene Oct 16 '21 at 16:55
  • I'm looking for the identifier of the instance of `foo-service` on which this code is executing. – Mark Oct 25 '21 at 23:42
  • you mean the actual pod where some code is executing? Im sorry, but why would that matter to you? – Eugene Oct 25 '21 at 23:50

2 Answers2

0

The instance name is the name of the Pod, the name of the pod is the same as the hostname.

So for example use

InetAddress.getLocalHost().getHostName()
Thomas
  • 11,272
  • 2
  • 24
  • 40
  • 1
    wasn't the question: _how to get it_ that name, actually, where the code is executing? But to be fair, I was really confused about the question too – Eugene Nov 01 '21 at 19:23
0

I have used a similar, yet different approach, going for the ip address:

ServiceInstance myInstance = discoveryClient.getInstances(serviceId)
    .find(instance -> {
        instance.host == InetAddress.getLocalHost().hostAddress
    })

Works for me.