关于eureka:聊聊如何对eureka管理界面进行定制化改造

3次阅读

共计 5387 个字符,预计需要花费 14 分钟才能阅读完成。

前言

在 nacos 还未面世之前,eureka 基本上就是 springcloud 全家桶体系注册核心的首选,随着 nacos 的横空出世,越来越多基于 springcloud 的微服务项目采纳 nacos 作为注册核心,但这是不是意味着 eureka 就没用武之地,其实并不是的,从 springcloud 截止目前最新版本 2020.0.2 来看,该版本废除了 netflix 诸如 hytrix、ribbon、zuul 等组件,而 eureka 依然坚挺着,这就阐明 eureka 作为注册核心,在 springcloud 体系中依然施展着重要的作用。明天就来聊聊如何对 eureka 治理界面进行定制化革新

自定义登陆页面

eureka 默认是没有登陆鉴权的,咱们能够引入 spring security 来为 eureka 增加登陆鉴权性能

1、pom 引入 spring security

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

2、在 application.yml 配置认证用户名明码

spring:
  security:
    user:
      # 认证的用户名
      name: lybgeek
      # 认证的明码
      password: lybgeek

仅需这两步,就能够实现一个带有登陆界面的 eureka 治理界面。然而 spring security 的登陆界面 css 援用

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css

在网络不好的状况下,会呈现 eureka 登陆页面款式会加载不进去,很影响用户体验。因而咱们要自定义登陆页面

ps: spring security 的页面生成,如果感兴趣的敌人,能够查看如下类

org.springframework.security.web.server.ui.LoginPageGeneratingWebFilter

它的登陆页面生成是通过该过滤器渲染生成。

3、自定义登陆页

因为不是业余前端,因而就把 spring security 默认页面拿来简略批改一下。

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title> 请登录 </title>
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/signin.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <form class="form-signin" method="post" action="/login">
        <!--<h2 class="form-signin-heading"> 请登录 </h2>-->
        <div class="alert alert-danger" role="alert" id="errorMsgAlert" style="display:none" ></div>
        <p>
            <label for="username" class="sr-only"> 用户名 </label>
            <input type="text" id="username" name="username" class="form-control" placeholder="Username" required=""autofocus="">
        </p>
        <p>
            <label for="password" class="sr-only"> 明码 </label>
            <input type="password" id="password" name="password" class="form-control" placeholder="Password"
                   required="">
        </p>
        <button class="btn btn-lg btn-primary btn-block" type="submit"> 登录 </button>
    </form>
</div>
</body>
<script src="../js/jquery-3.5.1.min.js"></script>

4、编写跳转登陆页 controller

@Controller
@Slf4j
public class LoginController {@GetMapping("/toLogin")
    public String login(HttpServletRequest request) {return "login";}

}

5、配置 WebSecurity

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/toLogin*","/login*","/css/*","/js/*","/actuator/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/toLogin")
                .permitAll();
        super.configure(http);
    }

注: loginPage(“/toLogin”)中的 toLogin,对应的就是咱们写的 LoginController 路由。

此时拜访 eureka,能够看到如下页面

6、配置登陆逻辑以及登陆失败配置

注: 登陆逻辑间接采纳 spring security 默认的登陆逻辑 login,自定义页面的用户名 name 要取名为 username,明码要取名为 password,不能自定义,比方 password 改成 pwd,这样就无奈走默认的登陆逻辑。其次因为咱们应用自定义登陆页面,原生自带校验失败的页面渲染逻辑会生效,因而咱们要自定义校验失败渲染逻辑

在原先的 WebSecurityConfig 加上登陆逻辑配置和登陆失败配置

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/toLogin*","/login*","/css/*","/js/*","/actuator/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/toLogin")
                .loginProcessingUrl("/login").failureUrl("/login/error").permitAll();
        super.configure(http);
    }

}

7、自定义登陆失败跳转逻辑 controller

@Controller
@Slf4j
public class LoginController {@GetMapping("/login/error")
    public String loginError(HttpServletRequest request) {AuthenticationException authenticationException = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        log.info("authenticationException={}", authenticationException);
        String errorMsg;

        if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {errorMsg = "用户名或明码谬误";} else if (authenticationException instanceof DisabledException) {errorMsg = "用户已被禁用";} else if (authenticationException instanceof LockedException) {errorMsg = "账户被锁定";} else if (authenticationException instanceof AccountExpiredException) {errorMsg = "账户过期";} else if (authenticationException instanceof CredentialsExpiredException) {errorMsg = "证书过期";} else {errorMsg = "登录失败";}
        request.setAttribute("errorMsg",errorMsg);
        return "login";
    }
    }

当用户名或者明码谬误,页面会有如下提醒

eureka 治理界面指定环境信息

上图是 eureka 原生自带的环境信息。但咱们在日常开发中,有时候会辨别 dev、sit、uat、prod 环境,显然上图是没法满足咱们要求。因而咱们能够在 application.yml 配置如下内容

eureka:
  #此处设置会扭转 eureka 控制台的显示
  datacenter: ${DATA_CENTER:LYBGEEK DATA CENTER}
  #此处设置会扭转 eureka 控制台的显示
  environment: ${ENV:dev}

此时再查看页面

自定义治理页面

eureka 的治理界面默认是应用应用 freemarker 来做模板渲染,其模板页面在

spring-cloud-netflix-eureka-server- 具体版本.jar

如图

因而咱们如果要进行定制,仅需把 eureka 的模板配置挪到咱们代码的 templates 中,如图

而后依据咱们的须要,进行批改,比方在本示例中,我就新增了一个登出按钮和一个版权信息列表,如下图

在进行定制时,可能踩到的坑

在自定义登陆页面时,呈现如下异样

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [eureka/status], template might not exist or might not be accessible by any of the configured Template Resolvers

解决方案有两种,一种是在 yml 文件配置如下内容

spring:
  freemarker:
    prefer-file-system-access: false

一种在把 eureka 的模板页面都搁置在如下下图的地位

总结

最近和敌人聊天,他晓得我所在的公司注册核心还是用 eureka 的时候,他就很惊讶说怎么不必 nacos,而后我就问他说为什么要用 nacos,他给我的答案是当初 eureka 曾经闭源了,nacos 当初很火,能够做配置核心也能够做注册核心,erueka 前面基本上不会有人用了。

其实所谓 eureka 的闭源,是指 eureka2 版本的闭源,而目前大部分用的 eureka 都是版本一,咱们能够去看 netflix 对 eureka 的最近更新

截止以后,他更新工夫是 11 天前,再来看看 spring-cloud-netflix-eureka 的最近更新


对技术选型,有时候并不是哪个火就用哪个,而是要满足以后业务须要,还有一点比方你正式环境曾经稳固运行我的项目,你会因为呈现更火的技术,就把以后我的项目技术栈替换掉吗?我所在项目组,eureka 作为注册核心,因为注册下来的业务我的项目就那么一些,用 eureka 就齐全满足需要了。

我这边并不是排挤 nacos 的意思,毕竟 nacos 也有一些其余注册核心所不具备的个性,比方动静 DNS 服务,同时反对 AP 和 CP,nacos2 的高性能,这些都是很值得去关注

demo 链接

https://github.com/lyb-geek/springboot-learning/tree/master/springboot-custom-eureka

正文完
 0