SpringCloud-Eureka-02架构原理

2019-06-27  本文已影响0人  小亮__

Eureka包含两个组件:Eureka Server 和 Eureka Client,它们的作用如下:

工作原理:

自我保护模式

自我保护模式

默认情况下,如果Eureka Server在一定时间内没有接收到某个微服务实例的心跳,Eureka Server将会注销该实例(默认90秒)。但是当网络分区故障发生时,微服务与Eureka Server之间无法正常通信,以上行为可能变得非常危险了——因为微服务本身其实是健康的,此时本不应该注销这个微服务。

Eureka通过“自我保护模式”来解决这个问题——当Eureka Server节点在短时间内丢失过多客户端时(可能发生了网络分区故障),那么这个节点就会进入自我保护模式。一旦进入该模式,Eureka Server就会保护服务注册表中的信息,不再删除服务注册表中的数据(也就是不会注销任何微服务)。当网络故障恢复后,该Eureka Server节点会自动退出自我保护模式。

综上,自我保护模式是一种应对网络异常的安全保护措施。它的架构哲学是宁可同时保留所有微服务(健康的微服务和不健康的微服务都会保留),也不盲目注销任何健康的微服务。使用自我保护模式,可以让Eureka集群更加的健壮、稳定。

可以通过以下的命令禁用自我保护模式

eureka.server.enable-self-preservation = false

不踢出已关停的节点问题

在开发过程中,我们常常希望Eureka Server能够迅速有效地踢出已关停的节点,但是新手由于Eureka自我保护模式,以及心跳周期长的原因,常常会遇到Eureka Server不踢出已关停的节点的问题。解决方法如下:

eureka.server.enable-self-preservation=false            # 设为false,关闭自我保护
eureka.server.eviction-interval-timer-in-ms=     # 清理间隔(单位毫秒,默认是60*1000)
eureka.client.healthcheck.enabled=true          # 开启健康检查(需要spring-boot-starter-actuator依赖)
eureka.instance.lease-renewal-interval-in-seconds=      # 续约更新时间间隔(默认30秒)
eureka.instance.lease-expiration-duration-in-seconds=   # 续约到期时间(默认90秒)

增加安全访问策略

Eureka本身不具备安全认证的能力,Spring Cloud使用Spring Security为Eureka Server进行了增强
增加配置

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

修改配置

 # 配置登录的账号是user(账号默认是user,密码是一个随机值,该值会在启动时打印出来)
spring.security.user.name=user
# 配置登录的密码是password123
spring.security.user.password=password123
# 服务端-增加如下配置
eureka.client.service-url.defaultZone=http://user:password123@localhost:8761/eureka/
# 客户端-增加如下配置
eureka.client.serviceUrl.defaultZone=http://user:password123@localhost:8761/eureka/

增加代码-Adapter

/**
 * Spring Cloud Finchley及更高版本,必须添加如下代码,部分关闭掉Spring Security
 * 的CSRF保护功能,否则应用无法正常注册!
 * @author 
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().ignoringAntMatchers("/eureka/**");
    super.configure(http);
  }
}

访问界面的时候就已经有账号和密码的输入了


上一篇下一篇

猜你喜欢

热点阅读