一、简介
1.包含组件:
- Eureka Server
- Eureka client
2.Eureka Server
- Eureka Server提供注册服务,节点服务启动后,会在Eureka Server进行注册,并且在Eureka Server的服务注册表中会存储所有可用服务节点的信息
- Eureka Server本身也是一个服务,默认会自动注册到Eureka注册中心
- Eureka Server通过Register、GET、Renew等接口提供服务的注册、发现和心跳检测等服务
3.Eureka Client
- Eureka Client是一个java客户端,在应用启动后,会向Eureka Server发送心跳,来进行心跳续约。
- 发送心跳的默认周期为30秒,若没接受到,则服务节点移除的周期为90秒。
二、Eureka Server
1.架构原理
- Register(服务注册):把自己的IP和端口注册给Eureka Server
- Renew(服务续约)
- Cancel(服务下线)
- GET Register(获取服务注册列表)
- Replicate(集群中数据同步)
- Make Remote(call远程调用服务)
- Application Service(服务提供方):是注册到Eureka Server中的服务
- Application Client(服务消费方):通过Eureka Server发现服务,并消费
2.Server集群
Eureka集群中所有节点都是平等的(不同于zookeeper中的主从关系),节点之间可以相互注册当前节点中已注册的服务,并发现其他节点中已注册的服务
三、Eureka Client
- client在注册服务时,会根据节点列表一次访问Eureka Server集群中的节点,只要注册成功,不再访问后续的Eureka Server。
- 同时Eureka Server集群中每个节点对服务都使用连带责任,比如从某个Server1节点发现了服务A,当该Server1节点宕机时,则A服务同时从当前服务列表中删除。
四、Eureka Demo
1.Application Service(服务提供者)
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
注解配置
@EnableEurekaClient
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
配置文件编写
spring:
application:
name: eureka-application-service
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://test:123456@eurekaserver1:8761/eureka/,http://test:123456@eurekaserver2:8761/eureka/
instance:
preferIpAddress: true
根据业务,提供服务接口(略)
2.Application Client(服务消费者)
依赖和主类注解配置和服务提供者相同
使用RestTemplate进行负载均衡并发送HTTP请求,先将该Bean进行注册,注意使用@LoadBalanced注解
@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
客户端使用该服务
@RestController
public class TestClientController {
@Autowired
public RestTemplate restTemplate;
@RequestMapping("/test1")
public void test1(){
//地址使用的是服务的service名称,经过负载均衡会自动转为ip地址
String url = "http://eureka-application-service/test2";
String s = restTemplate.getForObject(url, String.class);
System.out.println(s);
}
}
优雅关闭服务
可以通过http请求的方式,通知EurekaClient优雅停止服务
1.需要添加一些的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
2.并在client中配置
# 启用shutdown,优雅停服功能
endpoints.shutdown.enabled=true
# 禁用密码验证
endpoints.shutdown.sensitive=false
3.发起shutdown请求
使用POST请求向Eureka Client发起一个shutdown请求。请求路径为:http://ip:port/shutdown。
可以通过httpclient、Ajax、form表单等实现