Eureka健康检查和安全配置
Eureka 健康检查
由于server和client通过心跳保持 服务状态,而只有状态为UP的服务才能被访问。看eureka界面中的status。
比如心跳一直正常,服务一直UP,但是此服务DB连不上了,无法正常提供服务。
此时,我们需要将微服务的健康状态也同步到server。只需要启动eureka的健康检查就行。这样微服务就会将自己的健康状态同步到eureka。配置如下即可。
eureka.client.healthcheck.enabled=true
可以改变服务的状态,只需实现HealthIndicator接口即可。需要添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
HealthStatusService
@Service
public class HealthStatusService implements HealthIndicator {
private Boolean status = true;
public void setStatus(Boolean status) {
this.status = status;
}
@Override
public Health health() {
if (status)
return new Health.Builder().up().build();
return new Health.Builder().down().build();
}
public String getStatus() {
return this.status.toString();
}
}
测试Controller:
@GetMapping("/health")
public String health(@RequestParam("status") Boolean status) {
healthStatusSrv.setStatus(status);
return healthStatusSrv.getStatus();
}
访问http://localhost:8001/health?status=false,在访问http://localhost:8761/,等待30秒左右即可看到:
consumer服务的状态变为down。
访问http://localhost:8001/health?status=true,在访问http://localhost:8761/,等待30秒左右即可看到:
可以通过这种方式控制服务的状态。
安全配置
如果Eureka Service加入了Spring Security依赖,那么客户端访问的时候必须携带用户名和密码。比如:eureka.client.service-url.defaultZone=http://user:123@localhost:8761/eureka/。
并且Eureka Service必须关闭Spring Security的csrf配置:
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
super.configure(http);
}
}
否则注册服务会报错。