spring boot 2.0以上为Eureka添加用户认证-查看Eureka的元数据

Eureka Server(注册中心)是运行匿名访问的,本节为了安全,添加一个需要登陆才能访问的功能。同时在spring boot 2.0版本可以查看元数据。

一、添加用户认证

1、引入spring-boot-discovery-eureka依赖,提供用户认证的能力。

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

2、在application.properties配置文件中添加属性。

注意:spring boot 2.0 版本以上与之前的版本不一致,操作比较多。

#新版本开启权限
spring.security.user.name=jiankang
spring.security.user.password=123

3、我们需要设置一个配置类,否则登陆注册中心是总是用户名密码错误,无法登陆。

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.csrf().disable();
        super.configure(http);
    }
}

4、浏览器打开注册中心之前,会让输入在配置中设置的用户名和密码。

5、其他服务想要注册在该中心,我们需要修改其服务的defaultZone的值,增加用户名和密码,如下:

#设置Eureka Server交互的地址,查询和注册服务都需要依赖这个地址,与注册中心地址一致
eureka.client.service-url.defaultZone=http://jiankang:123@localhost:8080/eureka/

这样,其他服务就能够注册进来了。

二、查看元数据

标准元数据指的是主机名、IP地址、端口号等信息,这些信息都会发布在服务注册表中,用于服务之间的调用。

1、在服务的controller中注入下面的属性:

  @Autowired
  private DiscoveryClient discoveryClient;

2、在该controller中添加以下的请求地址:

(1)getInstances中的myprovider为在注册中心的注册名。

//    查看eureka的元数据
    @GetMapping("/user-instance")
    public List<ServiceInstance> showInfo(){
        return this.discoveryClient.getInstances("myprovider");
    }

3、开启服务,我们访问上面的请求地址,会得到如下页面内容:

三、查看健康数据

actuatorspring boot项目中非常强大一个功能,有助于对应用程序进行监视和管理.

1、在pom.xml中引入该依赖:

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

2、配置开启健康检查

eureka.client.healthcheck.enabled=true

3、spring boot 2.0以上访问的地址为项目地址+/actuator/health,实例:

4、actuator依赖,默认关闭了许多监控端点,想全部开启可以做一下配置。

management.endpoints.web.exposure.include=*

这时候health,info,beans等端口都可以访问了。

四、总结

以上是所有内容,更多精彩关注:

猜你喜欢

转载自blog.csdn.net/jiankang66/article/details/90296918