Spring cloud Eureka 服务治理(注册服务提供者)


搭建完成服务注册中心,下一步可以创建服务提供者并向注册中心注册服务。

接下来我们创建Spring Boot 应用将其加入Eureka服务治理体系中去。

直接使用签名章节创建hello服务项目改造:

1. 添加Eureka服务治理依赖配置


    org.springframework.cloud
    spring-cloud-starter-eureka-server





org.springframework.cloud
spring-cloud-dependencies
Brixton.SR5
pom
import


2. 改造RestController服务接口的/hello服务

/**
 * Created by Administrator on 2017/5/9.
 */

@RestController
public class HelloController {

    private final Logger log = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index(){

        ServiceInstance instance = client.getLocalServiceInstance();

        log.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());

        return "Hello World !";
    }

}

3. 激活Eureka 的DiscoveryClient实现,添加 @EnableDiscoveryClient 注解

@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan("com.net263")
public class HelloworldApplication {

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

4. 配置application.properties 关键参数

# 指定应用名称
spring.application.name= hello-service

# 构建服务中心的地址
eureka.client.serviceUrl.defaultZone= http://localhost:1111/eureka/

改造完毕,下面我们分别启动注册中心服务和提供服务者程序。启动成功后会打印如下日志信息说明注册服务成功。

也可以去服务注册中心信息面板去查看。

通过访问:http://wmlocal.263.net:8888/hello 向服务发起请求,在控制台中可以看到如下输出