写BUG的派大星

Patrick Star

  • 首页
  • 归档

  • 搜索
设计模式 Gis Kafka Druid 微信小程序 Java 开源项目源码 物体识别 机器学习 Mybatis 微服务 Feign OpenVPN CSS Streamsets CDH SpringCloud SpringBoot maven 分布式 Shell Tree Linux js WebSocket 多线程 集群 Hadoop 大数据 JDK ElasticSearch MySQL 数据库 Redis Http Nginx

SpringBoot Admin接入

发表于 2021-01-08 | 分类于 Java | 0 | 阅读次数 1049

监控平台部署

这里使用到的监控平台是Spring Boot Admin ,后面简称SBA。像他的名字一样,可以对SpringBoot的运行状态进行监控。

官网:Github地址:https://github.com/codecentric/spring-boot-admin

SBA有两种监控方法,均需要部署服务端,以下样例中也是在重点说明服务端的部署。

第一种方法是使用SpringBoot Admin Client,在项目中引入spring-boot-admin-client依赖,并在application.yml中增加一个配置: spring.boot.admin.client.url,url写SBA服务端的地址即可。

第二种方法则是将SBA服务端注册到微服务的注册中心,如nacos、eureka等。这样SBA就可以监控所有注册到该注册中心的服务了。下面具体以eureka为例进行说明。

部署步骤

新建一个Spring Boot项目。

以下maven依赖供参考

<?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">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>springboot-admin</artifactId>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR2</spring-cloud.version>
    </properties>

    <dependencyManagement>
        <dependencies>

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

        </dependencies>

    </dependencyManagement>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-starter-server -->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>2.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!--治理服务支持-->
        <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>

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

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>


            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>



</project>

配置文件:

注释中标明了可选的都是要根据自己需求选择的

spring:
  application:
    name: cloud-admin
  profiles:
    active: secure # 与代码中配置的安全策略相关联,是否启用帐号密码
  security:
    user:
      name: "root"
      password: "****"
  boot:
    admin:
      ui: # 可选,修改ui相关信息
        title: 服务健康监控
        brand: <img src="assets/img/icon-spring-boot-admin.svg"><span>服务健康监控</span>
        resource-locations: classpath:/ui/ # 资源所在位置
        template-location: classpath:/ui/  # 页面的模板文件所在位置
      monitor: # 可选,
        default-timeout: 5000
      notify: # 可选
        mail:
          from: xxxxx@126.com
          ignore-changes: UNKNOWN:UP # 不通知的状态变化,冒号前面是旧状态,后面是新状态。 如果写""代表所有状态都通知
          to: mawengang@cestc.cn
          template: classpath:/mail/status-changed.html # 手动修改预警邮件的模板
  mail: # 可选,如需发邮件才需要
    host: smtp.126.com
    password: *******
    test-connection: true
    username: xxxxxx@126.com
    protocol: smtps
    port: 465
    properties:
      mail.debug: false
      mail.smtp.auth: true

server:
  port: 8017

logging:
  config: 'classpath:logback-spring.xml'

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8013/eureka # eureka地址
    #设为true,开启健康检查(需要sping-boot-start-actuator依赖)
    healthcheck:
      enabled: true
    #加快从eureka服务器注册表中获取注册信息的时间间隔
    registryFetchIntervalSeconds: 5
  instance:
    #使用ip替代实例名
    prefer-ip-address: true
    leaseRenewalIntervalInSeconds: 10
    health-check-url-path: /actuator/health
    metadata-map:
      user.name: "root"         #These two are needed so that the server
      user.password: "****"     #can access the protected client endpoints

management:
  endpoints:
    web:
      #      由于 Spring Boot 2.0 的 Actuator 只暴露了 /health、/info 两个端口(为了安全考虑), 所以需要配置暴露的接口
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS

然后在启动类中加入@EnableAdminServer和@EnableEurekaClient两个注解。

如下图所示:

image-20210108150259560

增加安全权限配置:

@Configuration
public class SecurityConfiguration {

    @Profile("insecure")
    @Configuration
    public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().permitAll().and()
                    .csrf().disable();
        }
    }
    @Profile("secure")
    @Configuration
    public static class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
        private final String adminContextPath;

        public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
            this.adminContextPath = adminServerProperties.getContextPath();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
            successHandler.setTargetUrlParameter("redirectTo");

            http.authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                .logout().logoutUrl(adminContextPath + "/logout").and()
                .httpBasic().and()
                .csrf().disable();
            // @formatter:on
        }
    }

}

然后启动服务,就可以访问了

image-20210108165828245

image-20210108165923643

监控平台接入

修改所有被监控服务

  1. 修改pom.xml增加依赖(如果已有可以忽略):

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-actuator</artifactId>
       <version>2.0.0.RC1</version>
    </dependency>
    
  2. 修改配置文件,增加如下配置(如果已有可以忽略):

    需仔细核对,否则会有很多信息监控不到

    # 基础信息监控
    management:
      endpoints:
        web:
          exposure:
            include: "*" #暴露所有监控信息url 默认只有info,health,还需要logger、httptrace等等
      endpoint:
        health:
          show-details: always
    # 用于实时日志查看功能
    logging:
      config: 'classpath:logback-spring.xml'
      file: /usr/local/logs/gridmanagement/app.log #file的取值仅供示例使用,具体需要与logback-spring.xml中相同
    

    先在logback-spring.xml中配置好日志输出文件,然后同步修改application.yml中的logging.file参数,以在监控平台中查看实时日志。

  3. 参照样例修改logback-spring.xml

    这里仅仅提供示例,需结合自身项目修改。

    上面application.yml中写的文件,应该是一个较全的日志,而不是按级别分离的部分日志。

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <!--日志路径本地自行定义 -->
        <!--日志路径本地自行定义 -->
        <!--日志路径本地自行定义 -->
    	<property name="CONSOLE_LOG_PATTERN"
                  value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />
        <springProperty scope="context" name="LOG_FILE" source="logging.file" defaultValue="/usr/local/logs/gridmanagement/app.log" />
        <!-- 彩色日志依赖的渲染类 -->
        <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
        <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
        <conversionRule conversionWord="wEx"
                        converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
        <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->
        <!-- appender是configuration的子节点,是负责写日志的组件。 -->
        <!-- ConsoleAppender:把日志输出到控制台 -->
        <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
            <encoder>
                <pattern>${CONSOLE_LOG_PATTERN}</pattern>
                <charset>utf8</charset>
            </encoder>
        </appender>
        <!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
        <!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是sys.log -->
        <!--             2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->
        <appender name="APP_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${LOG_FILE}</file>
            <!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
            <!-- 滚动策略,基于时间和占用空间大小来制定 -->
            <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                <!-- 文件名 log/app.log.2020-01-01.0.log -->
                <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i</fileNamePattern>
                <!-- 活动文件的最大文件大小 500MB -->
                <maxFileSize>500MB</maxFileSize>
                <!-- 最长保存时间 10天 -->
                <maxHistory>10</maxHistory>
                <!-- 总大小5G -->
                <totalSizeCap>5GB</totalSizeCap>
            </rollingPolicy>
            <encoder>
                <!-- 日志格式 -->
                <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            </encoder>
        </appender>
    
        <!-- 控制台输出日志级别 -->
        <!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE  -->
        <root level="info">
            <appender-ref ref="STDOUT"/>
            <appender-ref ref="APP_FILE"/>
        </root>
        <!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->
        <!-- com.cesec.springboot.building_production.dao为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
        <logger name="com.cesec.springboot.building_production.dao" level="debug" additivity="false">
            <appender-ref ref="STDOUT"/>
            <appender-ref ref="APP_FILE"/>
        </logger>
    
        <logger name="com.cesec.springboot.system.dao" level="debug" additivity="false">
            <appender-ref ref="STDOUT"/>
            <appender-ref ref="APP_FILE"/>
        </logger>
        <!-- 除上面这些配置外,还需将错误日志收集到另外一个文件,便于ELK收集  -->
    </configuration>
    
    

监控平台效果:

image-20210107134609755

邮件预警(修改监控平台配置)

在服务的状态改变时,监控平台会发出预警邮件。

使用到的依赖是

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

需修改监控平台配置项如下:

spring:
  mail:
    test-connection: true
    username: xxxxxxx@126.com # 用于发件的邮箱
    password: ******          # 邮箱的授权码
    protocol: smtps           # 发件邮箱的协议,根据运营商设置,smtp/smtps/pop3等等
    host: smtp.126.com        # 邮箱的host地址 
    port: 465                 # 运营商给的端口
    properties:
      mail.debug: false
      mail.smtp.auth: true
 boot:
    admin:
      notify:
        mail:
          from: patr1ck@126.com                # 用于发件的邮箱,需要与上面的保持一致
          ignore-changes: UNKNOWN:UP           # 忽略的状态变化,即从unkonwn变为up时不发送邮件
          to: mawengang@cestc.cn               # 接收的邮箱,如有多个使用逗号隔开。
          template: classpath:/mail/status-changed.html # 模板地址,这里简单的修改成了中文,一般不用改变

邮件效果:

image-20210107134748251

  • 本文作者: Patrick
  • 本文链接: https://www.write1bug.cn/archives/springbootadmin接入
  • 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
# 设计模式 # Gis # Kafka # Druid # 微信小程序 # Java # 开源项目源码 # 物体识别 # 机器学习 # Mybatis # 微服务 # Feign # OpenVPN # CSS # Streamsets # CDH # SpringCloud # SpringBoot # maven # 分布式 # Shell # Tree # Linux # js # WebSocket # 多线程 # 集群 # Hadoop # 大数据 # JDK # ElasticSearch # MySQL # 数据库 # Redis # Http # Nginx
PostGis常用空间函数
  • 文章目录
  • 站点概览
Patrick

Patrick

不是在改BUG,就是在写BUG。

52 日志
9 分类
36 标签
RSS
E-mail
Creative Commons
© 2018 — 2023 Patrick
人生如逆旅|我亦是行人
鲁ICP备18043140号-1