上一篇讲到了springBoot Admin 和 springBoot Client 的搭建,地址如下

http://www.5180it.com:8080/bbs/admin/1/70.html


但我们在项目一般会用到服务发现的机制,如Eureka、Zookeeper,因此我们可以不需要springBoot Client客户端的依赖,

只需将springBootAdmin Server 服务端注册到注册中心即可,其余的自动配置完成。


现在开始我们项目的搭建,这里我选择了Eureka作为注册中心


1、搭建Eureka服务端


1.1、 pom文件引入依赖

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-security</artifactId>

</dependency>

1.2、项目配置yml文件

server:

  port: 8999

spring:

  application:

    name: sb_AdminServer

  security:

    user:

      name: admin

      password: 123456

      roles: admin

  boot:

    admin:

      ui:

        title: 5180it

eureka:

  instance:

    metadata-map:

      user.name: ${spring.security.user.name}

      user.password: ${spring.security.user.password}

    easeRenewalIntervalInSeconds: 10

    health-check-url-path: /actuator/health

    ip-address: 127.0.0.1

    prefer-ip-address: true

    instance-id: ${eureka.instance.ip-address}:${server.port}

  client:

    registryFetchIntervalSeconds: 5

    serviceUrl:

      defaultZone: http://eurekaadmin:123456@127.0.0.1:8888/eureka/

 

management:

  endpoints:

    web:

      exposure:

        include: "*" #暴露所有节点

    health:

      sensitive: false #关闭过滤敏感信息

  endpoint:

    health:

      show-details: ALWAYS  #显示详细信息


1.3、启动类

package com.king;


import java.util.UUID;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.HttpMethod;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import org.springframework.security.web.util.matcher.AntPathRequestMatcher;


import de.codecentric.boot.admin.server.config.AdminServerProperties;

import de.codecentric.boot.admin.server.config.EnableAdminServer;


@EnableDiscoveryClient

@EnableAdminServer

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

public class SpringBootAdminServerApplication {


public static void main(String[] args) {

SpringApplication.run(SpringBootAdminServerApplication.class, args);

}


@Configuration

public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {



    private final AdminServerProperties adminServer;

 

     /**

      * Instantiates a new Security secure config.

      *

      * @param adminServer the admin server

      */

     public SecuritySecureConfig(AdminServerProperties adminServer) {

         this.adminServer = adminServer;

     }

 

     @Override

     protected void configure(HttpSecurity http) throws Exception {

         // @formatter:off

         SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();

         successHandler.setTargetUrlParameter("redirectTo");

         final String adminServerContextPath = this.adminServer.getContextPath();

         successHandler.setDefaultTargetUrl(adminServerContextPath+"/");

 

         http.authorizeRequests()

                 .antMatchers(adminServerContextPath + "/assets/**").permitAll() // <1>

                 .antMatchers(adminServerContextPath + "/login").permitAll()

                 .anyRequest().authenticated() // <2>

                 .and()

                 .formLogin().loginPage(adminServerContextPath + "/login").successHandler(successHandler).and() // <3>

                 .logout().logoutUrl(adminServerContextPath + "/logout").and()

                 .httpBasic().and() // <4>

                 .csrf()

                 .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) // <5>

                 .ignoringRequestMatchers(

                         new AntPathRequestMatcher(adminServerContextPath + "/instances", HttpMethod.POST.toString()),  // <6>

                         new AntPathRequestMatcher(adminServerContextPath + "/instances/*", HttpMethod.DELETE.toString()),  // <6>

                         new AntPathRequestMatcher(adminServerContextPath + "/actuator/**")  // <7>

                 )

                 .and()

                 .rememberMe().key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600);

 

     }

}

}


2、搭建Eureka客户端


2.1、 pom文件引入依赖

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>

</dependency>

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!--监控和管理Spring Boot应用 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

        <dependency>

        <groupId>org.projectlombok</groupId>

        <artifactId>lombok</artifactId>

    </dependency>


2.2、项目配置yml文件

server:

  port: 8601 #服务访问端口

  servlet:

    context-path: / #访问路径

spring:

  application:

    name: sb_EurekaClient #服务名

management:

  endpoints:

    web:

      exposure:

        include: "*" #暴露所有节点

    health:

      sensitive: false #关闭过滤敏感信息

  endpoint:

    health:

      show-details: ALWAYS  #显示详细信息

eureka:

  instance: #实例

    prefer-ip-address: true #是否使用IP地址进行访问

    #实例显示名

    instanceId: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@

  client:

    serviceUrl:

      defaultZone: http://eurekaadmin:123456@127.0.0.1:8888/eureka/

logging:

    file: /application.log

    pattern:

      file: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx'


2.3、启动类

package com.king;


import java.text.SimpleDateFormat;

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

import java.util.Date;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;


@Slf4j

@RestController

@SpringBootApplication

@EnableDiscoveryClient

public class SpringBootEurekaClientApplication {


public static void main(String[] args) {

SpringApplication.run(SpringBootEurekaClientApplication.class, args);

}


@RequestMapping("/ping")

public String ping(){

Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String time = sdf.format(date);


        LocalDateTime localDateTime = LocalDateTime.now();

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        String localTime = dtf.format(localDateTime);


log.info(">>>>>>>>>>>>>记录当前时间:普通时间: {}, 本地时间: {}",time, localTime);

log.error(">>>>>>>>>>>>>记录当前时间:普通时间: {}, 本地时间: {}",time, localTime);

return "pong";

}

}



这里注意有几点

1、使用 logging.file  我们可以在springBoot Admin 在线实时查看日志

2、我们在启动类上写了ping方法,作为测试日志打印

 

好了,到此为止项目已经搭建完成了

我们先启动Eureka服务端

启动完成打开地址 http://127.0.0.1:8888/login,这里我使用了spring-security,因此需要输入密码,密码配置见yml文件


输入账号和密码,即可看到下面熟悉的界面了



打开springBoot Admin地址 http://127.0.0.1:8999/login



输入账号admin,密码123456

打开日志界面,同时在浏览器打开 http://127.0.0.1:8601/ping发请求,在后台即可实时打印日志信息




到此为止,项目就搭建完成,后续的开发,我们可以基于在springBootEurekaClient下进行开发了。

在这过程我发现SpringBootAdmin 和 Eureka 不能同时登录,具体也不知道什么情况,项目中也存在不足,希望和大家交流学习


具体代码见附件