(说在前面,为保证代码能正确运行,在此说明一下实验环境)
IDEA+JDK8+Tomcat9
(之前用了jdk10代码一直报错,是因为jdk8里面有些东西到jdk10的时候路径发生了变化)
Spring Cloud Eureka 实现服务治理
微服务的本质是各种API接口的调用,那么这些接口是怎么产生的,产生之后如何调用的,如何进行管理?
Spring Cloud Eureka解决了这些问题。我们可以将自己定义的API接口注册到Spring Cloud Eureka上,Eureka负责服务的注册与发现。构成Eureka体系包括:服务注册中心、服务提供者、服务消费者
- 两台Eureka服务注册中心构成的服务注册中心的主从复制集群
- 然后服务提供者向注册中心进行注册、续约、下线服务
- 服务消费者向Eureka注册中心获取服务列表并维护在本地
- 服务消费者根据获取的服务列表选取一个服务提供者进行消费服务
Eureka Server :提供服务注册和发现
- 添加依赖
在项目中添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
- 开启服务注册
通过@EnableEurekaServer注解启动一个服务注册中心提供其他应用进行对话
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
- 添加配置
在默认配置下,该服务注册中心会将自己作为客户端注册,所以需要禁用他的客户端注册行为
eureka: instance: hostname: localhost client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ spring: application: name: eureka-service server: port: 8080
输入https://localhost:8080/
可以看到当前没有注册的服务
Service Provider:服务提供方,将自身服务注册到Eureka注册中心,从而使服务消费方可以找到
- 添加依赖
在项目eureka_provider中,在pom.xml中添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>
- 开启服务注册
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableEurekaClient @RestController public class EurekaProviderApplication { @RequestMapping("/") public String home() { return "Hello world"; } public static void main(String[] args) { SpringApplication.run(EurekaProviderApplication.class, args); } }
通过@EnableEurekaClient注解启动一个服务注册中心
- 添加配置
需要配置才能找到Eureka服务器
eureka: client: serviceUrl: defaultZone: http://localhost:8080/eureka/ spring: application: name: eureka-provider server: port: 8081
其中defaultZone是一个魔术字符串后备值,为任何不表示首选项的客户端提供URI,通过Spring_application_name属性,我们可以指定微服务的名称,后续在调用该服务时直接使用该名称就可以进行服务的访问了。
- 访问服务
可以看到服务eureka-provider被注册了
参考:https://www.w3cschool.cn/spring_cloud/spring_cloud-2hgl2ixf.html
附上原作者的源码
源码:https://github.com/souyunku/spring-cloud-examples/tree/master/spring-cloud-eureka