springboot项目接入springbootAdmin搭建流程

目录

springbootadmin server 搭建

springbootadmin client 搭建

springbootadmin 配置在线日志查看功能


本次搭建流程基于版本springboot 2.4.9,springbootadmin 2.3.1

springbootadmin server 搭建

 第一步,首先搭建一个标准的spring boot项目。

 第二步,修改pom.xml文件,添加相应jar

    <properties>
        <java.version>1.8</java.version>
        <spring-boot-admin.version>2.3.1</spring-boot-admin.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-server</artifactId>
            <version>${spring-boot-admin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

第三步,修改yml文件

server:
  port: 8000
spring:
  application:
    name: admin-server
  security:
    user:
      name: admin
      password: admin

#Actuator配置:暴露敏感路径,默认情况下,敏感路径并不暴露
management:
  endpoints:
    web:
      exposure:
        # 暴露xxx端点,如需暴露多个,用,分隔;如需暴露所有端点,用'*'
        include: "*"
  endpoint:
    health:
      # 是否展示健康检查详情
      show-details: ALWAYS

# info信息会显示到SpringBootAdmin的server端,这里取的是pom文件中的数据
info:
  version: @project.version@
  groupId: @project.groupId@
  artifactId: @project.artifactId@

第四步,开启springbootadmin的注解

@EnableAdminServer
@SpringBootApplication
public class SpringadminApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringadminApplication.class, args);
    }

}

至此,springbootadmin简单的server端已经搭建完毕,启动即可。

如果我们需要给server端添加登录的账号和密码登录需要添加一下类至项目中。

第五步,添加服务端登录security认证配置

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
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;

@EnableWebSecurity
@Configuration(proxyBeanMethods = false)
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {

    private final String adminContextPath;

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

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

        http.authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                .antMatchers(adminContextPath + "/instances/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and()
                .logout().logoutUrl(adminContextPath + "/logout").and()
                .httpBasic().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(
                        adminContextPath + "/instances",
                        adminContextPath + "/actuator/**"
                );
        // @formatter:on
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/actuator/**");
    }
}

启动服务访问http://localhost:8000,输入你设置的账号密码即可登录。



springbootadmin client 搭建

这一端也就是我们的服务端,需要被监测的服务。需要改造的基本上在于配置,对项目影响不是很大。

第一步,引入相关jar,这里我们的spring-boot-admin.version的版本跟server端尽量保持一致。

<properties>
    <spring-boot-admin.version>2.3.1</spring-boot-admin.version>
</properties>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>${spring-boot-admin.version}</version>
</dependency>

第二步,修改yml文件

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: ALWAYS
spring:
  boot:
    admin:
      client:
        #springbootadmin server端服务器的部署地址
        url: http://localhost:8000
        instance:
          prefer-ip: true
        username: admin
        password: admin

第三步,判断项目中是否接入了shrio权限验证或者其他拦截过滤策略,如果接入,请过滤springbootadmin的健康地址,如果没有请忽略此步骤。下面以shrio举例

@Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        shiroFilter.setLoginUrl("/login.html");
        shiroFilter.setUnauthorizedUrl("/");
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/swagger/**", "anon");
        filterMap.put("/v2/api-docs", "anon");
        filterMap.put("/swagger-ui.html", "anon");
        filterMap.put("/webjars/**", "anon");
        filterMap.put("/swagger-resources/**", "anon");
        filterMap.put("/statics/**", "anon");
        filterMap.put("/login.html", "anon");
        filterMap.put("/sys/login", "anon");
        filterMap.put("/favicon.ico", "anon");
        filterMap.put("/captcha.jpg", "anon");
        // 过滤健康检查,否则监控中心无法上线
        filterMap.put("/actuator/**", "anon");
        filterMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

完成以上操作,启动服务,登录http://localhost:8000/(springbootadmin的server端的地址)即可看到自己的服务已经被健康。



springbootadmin 配置在线日志查看功能

以下配置均在client端进行,server端无需修改

第一步,添加相关jar

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

第二步,在application.yml平级文件夹中添加logback-spring.xml配置文件,红色字体内容根据自己实际情况修改,修改APP_Name 和LOG_HOME的value值,根据自己情况修改。如果是Windows本地测试地址请改为对应的盘符。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
       <property name="APP_Name" value="springbootTest" />
   <contextName>${APP_Name}</contextName>
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径,请根据需求配置路径-->  
    <property name="LOG_HOME" value="/data/springbootadmin/logs" />  
    
    <!-- 彩色日志依赖的渲染类 -->
    <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" />
    <!-- 彩色日志格式 -->
    <property name="CONSOLE_LOG_PATTERN"
              value="adminTest >> ${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(LN:%L){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />
    
    <!-- 控制台输出 -->   
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>
    
    <!-- 按照每天生成日志文件 -->   
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_HOME}/output.log</file>   
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/output-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>   
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n</pattern>   
        </encoder>
    </appender>
    
    <!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
    <logger name="org.hibernate.type.descriptor.sql.BasicBinder"  level="WARN" />  
    <logger name="org.hibernate.type.descriptor.sql.BasicExtractor"  level="WARN" />  
    <logger name="org.hibernate.SQL" level="WARN" />  
    <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
    <logger name="org.hibernate.engine.query.HQLQueryPlan" level="WARN" />  
    
    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="WARN"/>
    <logger name="java.sql.Connection" level="WARN"/>
    <logger name="java.sql.Statement" level="WARN"/>
    <logger name="java.sql.PreparedStatement" level="WARN"/>
    <logger name="org.apache.shiro" level="WARN"/>
    <!--可以添加自己监控的包  -->
    <logger name="com.xxx.xxx" level="WARN"/>


    <!-- 日志输出级别  ,注意:如果不写<appender-ref ref="FILE" /> ,将导致springbootadmin找不到文件,无法查看日志 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

第三步,修改项目yml文件。根据时间版本配置log文件的参数

logging:
    file: 
     name: /data/springbootadmin/logs/output.log

完成以上步骤,重启服务即可看到以下效果

至此搭建过程全部结束! 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值