Eureka服务治理
下面请听第一个话题,母。。。咳咳,拿错书了。
Eureka简介
eureka是什么呢?
简单来说呢,当我的微服务应用多了起来,一个一个写死再程序里是件很不优雅的事情,而且同一服务可能会多个实例存在,来对服务分流,就是负载均衡。
所以,我们需要一个位置来存放服务的访问列表,以供消费端来使用,这个东西呢,就可以用eureka来实现。
我们来看一下eureka的相关概念:
? 相关概念
服务注册(Register)
eureka客户端向Eureka服务器注册时,它提供自身的元数据,比如IP地址,端口信息
服务续约(Renew)
客户端每隔30秒发送一次心跳来进行服务续约。
服务下线(Cancel)
客户端在程序关闭时向服务器发送取消请求,成功该实例将会从服务器注册列表中删除
服务剔除(Eviction)
默认情况下,当客户端连续90秒没有发送心跳请求,服务器就会将该服务实例从服务列表中删除,剔除该服务
获取服务注册列表信息(Fetch Registriers)
客户端从服务器获取服务注册列表信息,并将其缓存在本地。列表信息定期(30秒)更新一次。
不太理解也没关系,我们可以先把架子搭建起来,之后慢慢悟把。
Eureka角色
Eureka中存在三种角色,注册中心,服务提供者,服务消费者。
其中注册中心是Eureka服务端,服务提供者与服务消费者都是客户端。
注册中心服务器
主要进行,服务注册,服务续约和服务下线。就是维护服务列表的东东啦。
让我们一步一步的开始把
- 相关依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
- 启动类配置,使用
@EnableEurekaServer
注解,启用Eureka服务
@SpringBootApplication @EnableEurekaServer public class EurekacenteralApplication { public static void main(String[] args) { SpringApplication.run(EurekacenteralApplication.class, args); } }
- 属性配置
server: port: 9090 ##UI界面端口 eureka: instance: hostname: localhost ##主机名称 client: register-with-eureka: false ##是否注册到服务中心,因为本身就是服务中心,不需要注册 fetch-registry: false ##是否发现服务 service-url: ##注册中心服务地址 defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动服务,这样一个简单的注册中心就启动起来,浏览器访问http://localhost:9090 就可以看到eureka的监控界面了。
服务提供者
eureka客户端,向外提供服务
- 相关依赖,作为Euraka客户端
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
- 启动类配置,使用
@EnableEurekaClient
注解,启动Eureka客户端
@SpringBootApplication @EnableEurekaClient public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } }
- 属性配置(单机时可以通过设置不同端口,来启动多个服务)
server: port: 8080 eureka: instance: prefer-ip-address: true ##使用IP注册服务 client: register-with-eureka: true #默认就是true,可以不用设置 fetch-registry: true #默认是true,可以不用设置 service-url: defaultZone: http://localhost:9090/eureka/ spring: application: name: microservice-provider
- 服务接口
@RestController @RequestMapping("/") public class TestController { @GetMapping("hi/{name}") public String hi(@PathVariable String name, HttpServletRequest request){ try { Thread.sleep(2010); } catch (InterruptedException e) { e.printStackTrace(); } return "hi,welcome "+name+" from port:"+request.getServerPort(); } }
服务消费者
本质上与提供者为同一类客户端,会在本地缓存一份服务列表信息,会定期更新缓存
- 相关依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
- 启动类配置
@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); } }
- 属性配置
server: port: 8090 eureka: client: service-url: defaultZone: http://localhost:9090/eureka/ register-with-eureka: false ##仅仅作为消费者 fetch-registry: true #默认是true,可以不用设置 ## 多