Spring Cloud服务注册中心

以Netflix Eureka做为服务注册中心(Service Registration and Discovery)。

配置

@EnableEurekaServer

启用:

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaServiceApplication.class, args);
    }
}

配置文件

/src/main/resources/application.properties

server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

logging.level.com.netflix.eureka=OFF
logging.level.com.netflix.discovery=OFF

客户端

@EnableDiscoveryClient

使用Spring Cloud DiscoveryClient查询注册中心,获得主机(自己)和端口。

@EnableDiscoveryClient同样适用于Consul、Zookeeper。

EurekaClientApplication.java

package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }
}

@RestController
class ServiceInstanceRestController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplicationName(
            @PathVariable String applicationName) {
        return this.discoveryClient.getInstances(applicationName);
    }
}

在配置文件指定应用名称:

/src/main/resources/bootstrap.properties

spring.application.name=a-bootiful-client

说明:ServiceInstanceRestController中定义了一个Spring MVC REST端点,返回注册中心所有ServiceInstance实例。

测试

启动eurek服务中心、eurek客户端,测试端到端的调用。

eurek客户端在注册中心注册自己大约需要一分钟,并从注册中心获取实例列表更刷新。