这篇文章主要介绍如何使用Spring Cloud Eureka来实现服务治理 --服务注册与发现,是一个总结 记录 方便自己记忆。
文章知识 均来自以下系列文章,请参考原文
Spring Cloud构建微服务架构:服务注册与发现(Eureka、Consul)【Dalston版】
服务治理,Spring Cloud服务治理
服务治理:在微服务架构中,由于一个项目被分成多个微服务,那各个微服务之间可能需要 互相调用。服务治理框架就是解决这个问题。具体包括 服务注册,服务发现,服务调用。
目前有多种服务治理框架,比如:Netflix Eureka、Consul、Zookeeper。
Spring Clound为微服务治理做了抽象接口,所以可以在Spring Cloud项目中无缝切换 服务治理实现,并不会影响服务治理中的 服务注册 ,服务发现,服务调用等逻辑。Spring Cloud做这一层抽象,很好的解耦了服务治理体系,使得我们可以轻易的替换不同的服务治理设施。
Spring Cloud ,Spring Cloud Netflix ,Spring Cloud Netflix Eureka的关系
Spring Cloud Netflix项目 是 Spring Cloud的子项目,主要内容是对Netflix公司的一系列开源产品的包装,它为Spring Boot应用提供了自配置的Netflix OSS整合。它主要提供的模块包括:服务治理(Eureka),断路器(Hystrix),智能路由(Zuul),客户端负载均衡(Ribbon)等。
所以 Spring Cloud Netflix Eureka是Spring Cloud Netflix项目下的服务治理模块。
使用Spring Cloud Eureka来实现服务治理
1.服务注册:创建服务注册中心
具体代码等没有添加,请参考原文 Spring Cloud构建微服务架构:服务注册与发现(Eureka、Consul)【Dalston版】
step1:创建Spring Boot项目eureka-server,添加 spring-cloud-starter-netflix-eureka-server 起步依赖
step2:在Spring Boot项目入口添加@EnableEurekaServer
注解 启动一个服务注册中心提供给其他应用进行对话
step3:修改配置文件 application.properties文件
在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为,在application.properties
配置文件中增加如下信息:
#设置服务注册中心 微服务的名称和端口
spring.application.name=eureka-server
server.port=1001
#禁用客户端注册行为,防止 该服务注册中心 将自己作为客户端 尝试注册自己
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
step4:启动工程后,访问:http://localhost:1001/,可以看到Eureka服务注册中心页面,其中还没有发现任何服务。
2.服务注册与发现 : 创建 服务提供者 ---创建提供服务的客户端,并向服务注册中心注册自己
Step1:创建一个Spring Boot项目eureka-client,添加 spring-cloud-starter-netflix-eureka-server 起步依赖
Step2:在项目入口添加 @EnableDiscoveryClient 注解,该注解能激活Eureka中的DiscoveryClient实现,这样才能实现Controller中对服务信息的输出。
Step3:在application.properties文件中配置一下
#微服务的名称:后续在调用的时候只需要使用该名称就可以进行服务的访问
spring.application.name=eureka-client
#微服务端口
server.port=2001
#指定服务注册中心的位置
eureka.client.serviceUrl.defaultZone=http://localhost:1001/eureka/
Step4:添加一个 该微服务可以提供的功能,例如 通过 DiscoveryClient对象,在日志中打印出服务实例的相关内容
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DiscoveryClientController {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/discoveryClient")
public String discoveryClient() {
String services = "Services: " + discoveryClient.getServices();
System.out.println(services);
return services;
}
}
Step5:启动 eureka-client项目,再访问http://localhost:1001/就会在Instances currently registered with Eureka列表看到刚刚注册的eureka-client服务
Step6:
如果要访问eureka-client微服务提供的discoveryClient 服务,可以访问http://localhost:2001/discoveryClient。
那么我们其实需要的是 如何在其它微服务 访问 eureka-client eureka-client微服务提供的discoveryClient 服务。也就是 如何去消费服务提供者的接口 ,接着看 Spring Cloud Eureka 服务治理--服务消费