spring-boot-admin notes

spring-boot-admin notes

本篇教程是基于springboot 2.3.8.RELEASE版本
和spring-boot-admin-dependencies 2.3.0版本

Build the server-side app of spring-boot-admin

pom configuration

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <name>dftjk</name>
    <description>Demo project for Spring Boot</description>


    <groupId>cn.mt</groupId>
    <artifactId>dftjk</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.8.RELEASE</spring-boot.version>

    </properties>

    <dependencies>

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

        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-dependencies</artifactId>
                <version>2.3.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>cn.mt.dft.App</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Startup class configuration

package cn.mt.dft;


import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableScheduling;


@EnableAdminServer
@SpringBootApplication
public class App {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(App.class, args);
    }
}

Built-in access authentication configuration

package cn.mt.dft;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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 java.util.UUID;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    

    private final AdminServerProperties adminServerProperties;

    public SecurityConfig(AdminServerProperties adminServerProperties) {
    
    
        this.adminServerProperties = adminServerProperties;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServerProperties.path("/"));

        http.authorizeRequests(
                (authorizeRequests) -> authorizeRequests.antMatchers(this.adminServerProperties.path("/assets/**")).permitAll()
                        .antMatchers(this.adminServerProperties.path("/login")).permitAll().anyRequest().authenticated()
        ).formLogin(
                (formLogin) -> formLogin.loginPage(this.adminServerProperties.path("/login")).successHandler(successHandler).and()
        ).logout((logout) -> logout.logoutUrl(this.adminServerProperties.path("/logout"))).httpBasic(Customizer.withDefaults())
                .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .ignoringRequestMatchers(
                                new AntPathRequestMatcher(this.adminServerProperties.path("/instances"),
                                        HttpMethod.POST.toString()),
                                new AntPathRequestMatcher(this.adminServerProperties.path("/instances/*"),
                                        HttpMethod.DELETE.toString()),
                                new AntPathRequestMatcher(this.adminServerProperties.path("/actuator/**"))
                        ))
                .rememberMe((rememberMe) -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));

    }
}

application.yml configuration

server:
  port: 8814
  compression:
    enabled: true  # 开启Gzip压缩,响应数据超过1kb时触发gzip自动压缩,以提高前端响应时间
    min-response-size: 1KB
  servlet:
    session:
      timeout: PT30M  #默认会话过期时间30分钟
    encoding:
      enabled: true
      charset: UTF-8
      force: true
  tomcat:
    uri-encoding: UTF-8




# http://localhost:8811/actuator/info 查看info端点会返还自定义的info信息
info:
  appname: dftjk
  ver: 1.0

# http://localhost:8811/actuator 查看暴露的所有可访问的端点
# http://localhost:8811/actuator/health 查看health端点
management:
  endpoints:
    web:
      exposure:

        include: [health,info,mappings] #开启health,info,mappings端点, 若配置*表示暴露所有端点
  endpoint:
    health:
      show-details: always # health端点展示详细信息



spring:
  security:
    user:
      name: root
      password: root
  application:
    name: dftjk
  servlet:
    multipart:
      max-file-size: 50MB  #单个文件的最大上限
      max-request-size: 200MB  #单个请求的文件总大小限制
      location: ${
    
    user.home}/.${
    
    spring.application.name}/tempDir





logging:
  file:
    #最终的存储路径是:  系统用户目录/.应用名称/logs/端口号/spring.log
    path: ${
    
    user.home}/.${
    
    spring.application.name}/logs/${
    
    server.port}
    max-history: 7
    max-size: 10MB
  pattern:
    console: "%date  %clr(%level) [${PID}]  [%thread] [%magenta(%X{traceId})] %cyan(%logger{10}) [%file : %line] %msg%n"
    file: "%date %level [${PID}]   [%thread] [%X{traceId}] %logger{10} [%file : %line] %msg%n"



Test the access effect after startup

  1. Visit localhost:8814
    Please add image description

The login password is root/root

  1. Log in to the homepage
    Please add image description

Because no service has been registered to spring-boot-admin-server at this time, there is no application record here.

Build the client app of spring-boot-admin

Part of the pom configuration

 <dependencies>
		<dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
</dependencies>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>de.codecentric</groupId>
                <artifactId>spring-boot-admin-dependencies</artifactId>
                <version>2.3.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

Part of application.yml configuration

# http://localhost:8811/actuator/info 查看info端点会返还自定义的info信息
info:
  appname: dft
  ver: 1.0

# http://localhost:8811/actuator 查看暴露的所有可访问的端点
# http://localhost:8811/actuator/health 查看health端点
management:
  endpoints:
    web:
      exposure:
        include: '*'
#        include: [health,info,mappings] #开启health,info,mappings端点, 若配置*表示暴露所有端点
  endpoint:
    health:
      show-details: always # health端点展示详细信息
    shutdown:
      enabled: true #允许优雅停机
logging:
  file:
    #最终的存储路径是:  系统用户目录/.应用名称/logs/端口号/spring.log
    path: ${
    
    user.home}/.${
    
    spring.application.name}/logs/${
    
    server.port}
    max-history: 7
    max-size: 10MB
  pattern:
    console: "%date  %clr(%level) [${PID}]  [%thread] [%magenta(%X{traceId})] %cyan(%logger{10}) [%file : %line] %msg%n"
    file: "%date %level [${PID}]   [%thread] [%X{traceId}] %logger{10} [%file : %line] %msg%n"


spring:
  application:
    name: dft
  boot:
    admin:
      client:
        enabled: true #启用spring-boot-admin
        url: http://127.0.0.1:8814 #服务器端的访问地址
        username: root #服务器端的访问账号
        password: root #服务器端的访问密码

Test the effect of spring-boot-admin after startup

  1. Start the client service you just created, and then access the spring-boot-admin server-visit localhost:8814
    Please add image description

  2. View application list
    Please add image description

  3. View app details
    Please add image description

  4. View real-time logs
    Please add image description

Guess you like

Origin blog.csdn.net/ThinkPet/article/details/132307313