spring-boot-admin笔记

spring-boot-admin笔记

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

搭建spring-boot-admin的server端app

pom配置


<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.0modelVersion>
    <name>dftjkname>
    <description>Demo project for Spring Bootdescription>


    <groupId>cn.mtgroupId>
    <artifactId>dftjkartifactId>
    <version>1.0-SNAPSHOTversion>

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

    properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>de.codecentricgroupId>
            <artifactId>spring-boot-admin-starter-serverartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-dependenciesartifactId>
                <version>${spring-boot.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>

            <dependency>
                <groupId>de.codecentricgroupId>
                <artifactId>spring-boot-admin-dependenciesartifactId>
                <version>2.3.0version>
                <type>pomtype>
                <scope>importscope>
            dependency>

        dependencies>
    dependencyManagement>

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

project>

启动类配置

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);
    }
}

内置访问认证配置

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配置

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"



测试启动后的访问效果

  1. 访问localhost:8814
    spring-boot-admin笔记_第1张图片

登录密码是 root / root

  1. 登录进入主页
    spring-boot-admin笔记_第2张图片

因为此时还没有服务注册到spring-boot-admin-server,所以这里暂时没有应用记录

搭建spring-boot-admin的client端app

部分pom配置

 <dependencies>
		<dependency>
            <groupId>de.codecentricgroupId>
            <artifactId>spring-boot-admin-starter-clientartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
dependencies>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-dependenciesartifactId>
                <version>${spring-boot.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>

            <dependency>
                <groupId>de.codecentricgroupId>
                <artifactId>spring-boot-admin-dependenciesartifactId>
                <version>2.3.0version>
                <type>pomtype>
                <scope>importscope>
            dependency>

        dependencies>
    dependencyManagement>

部分application.yml配置

# 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 #服务器端的访问密码

测试启动后的spring-boot-admin效果

  1. 启动刚刚建的client服务,然后访问spring-boot-admin服务器端-访问localhost:8814
    spring-boot-admin笔记_第3张图片

  2. 查看应用列表
    spring-boot-admin笔记_第4张图片

  3. 查看应用详情
    spring-boot-admin笔记_第5张图片

  4. 查看实时日志
    spring-boot-admin笔记_第6张图片

你可能感兴趣的:(SpringBoot技术笔记,SpringCloud技术笔记,开源技术,笔记,java,SpringBootAdmin,微服务监控,springboot,springcloud)