Service Discovery with Zookeeper
Service Discovery is one of the key tenets of a microservice based architecture. Trying to hand configure each client or some form of convention can be very difficult to do and can be very brittle. Curator(A java library for Zookeeper) provides Service Discovery services via Service Discovery Extension. Spring Cloud Zookeeper leverages this extension for service registration and discovery.
How to activate
Including a dependency on org.springframework.cloud:spring-cloud-starter-zookeeper-discovery
will enable auto-configuration that will setup Spring Cloud Zookeeper Discovery.
Note | You still need to include org.springframework.boot:spring-boot-starter-web for web functionality. |
---|---|
Registering with Zookeeper
When a client registers with Zookeeper, it provides meta-data about itself such as host and port, id and name.
Example Zookeeper client:
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class Application {
@RequestMapping("/")
public String home() {
return "Hello world";
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
(i.e. utterly normal Spring Boot app). If Zookeeper is located somewhere other than localhost:2181
, the configuration is required to locate the server. Example:
application.yml
spring: cloud: zookeeper: connect-string: localhost:2181
Caution | If you use Spring Cloud Zookeeper Config, the above values will need to be placed in bootstrap.yml instead of application.yml . |
---|---|
The default service name, instance id and port, taken from the Environment
, are ${spring.application.name}
, the Spring Context ID and ${server.port}
respectively.
@EnableDiscoveryClient
makes the app into both a Zookeeper "service" (i.e. it registers itself) and a "client" (i.e. it can query Zookeeper to locate other services).
Using the DiscoveryClient
Spring Cloud has support for Feign (a REST client builder) and also Spring RestTemplate
using the logical service names instead of physical URLs.
You can also use the org.springframework.cloud.client.discovery.DiscoveryClient
which provides a simple API for discovery clients that is not specific to Netflix, e.g.
@Autowired
private DiscoveryClient discoveryClient;
public String serviceUrl() {
List<ServiceInstance> list = discoveryClient.getInstances("STORES");
if (list != null && list.size() > 0 ) {
return list.get(0).getUri().toString();
}
return null;
}