服务发现
随着微服务的日趋火爆,系统拆分之后,各个服务模块的Provider和Consumer之间需要能够查找到对方,我们称之为服务发现。
In SOA/distributed systems, services need to find each other. i.e. a web service might need to find a caching service, etc. DNS can be used for this but it is nowhere near flexible enough for services that are constantly changing. A Service Discovery system provides a mechanism for:
- Services to register their availability
- Locating a single instance of a particular service
- Notifying when the instances of a service change
Curator Service Discovery
Curator Service Discovery就是为了解决这个问题而生的,它对此抽象出了ServiceInstance、ServiceProvider、ServiceDiscovery三个接口,通过它我们可以很轻易的实现Service Discovery。
实践
假如我们需要对外提供一个服务(com.bytebeats.service.HelloService),为了保证服务的高可用行 HelloService服务部署在N台机器上,现在Consumer想要请求这个服务,如何保证HelloService可以灵活部署(随意 增加/删除 机器)?
思路
首先,HelloService Provider在启动时向Zookeeper 注册本机提供的 服务名称、端口号和地址;Consumer启动的时候先查询Zookeeper获取到服务Provider列表,然后通过负载均衡算法(随机、RoundRobin、一致性Hash) 选择一台机器去调用服务。
代码实现
Maven依赖
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-discovery</artifactId>
<version>2.11.1</version>
</dependency>
ServerApp.java
package com.bytebeats.zookeeper.curator.discovery;
import com.bytebeats.zookeeper.curator.CuratorUtils;
import com.bytebeats.zookeeper.curator.discovery.domain.ServerPayload;
import com.bytebeats.zookeeper.util.JsonUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.UriSpec;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
/**
* 模拟服务提供者
*
* @author Ricky Fung
* @create 2016-12-08 19:24
*/
public class ServerApp {
public static final String BASE_PATH = "services";
public static final String SERVICE_NAME = "com.bytebeats.service.HelloService";
public static void main(String[] args) {
CuratorFramework client = null;
ServiceRegistry serviceRegistry