关于java:肝了一周总结的SpringBoot实战教程太实用了

天天在用SpringBoot,但有些SpringBoot的实用知识点却不是很分明!最近又对SpringBoot中的实用知识点做了个总结,置信对从Spring过渡到SpringBoot的敌人会很有帮忙!

SpringBoot实战电商我的项目mall(40k+star)地址:https://github.com/macrozheng/mall

前言

首先咱们来理解下为什么要有SpringBoot?

Spring作为J2EE的轻量级代替品,让咱们无需开发重量级的Enterprise JavaBean(EJB),通过依赖注入和面向切面编程,应用简略的Java对象(POJO)即可实现EJB的性能。

尽管Spring的组件代码是轻量级的,但它的配置却是重量级的。即便起初Spring引入了基于注解的组件扫描和基于Java的配置,让它看上去简洁不少,但Spring还是须要不少配置。除此之外,我的项目的依赖治理也很麻烦,咱们无奈确保各个版本的依赖都能兼容。

为了简化Spring中的配置和对立各种依赖的版本,SpringBoot诞生了!

简介

SpringBoot从实质上来说就是Spring,它通过了一些本人的个性帮忙咱们简化了Spring应用程序的开发。次要有以下三个外围个性:

  • 主动配置:对于很多Spring应用程序常见的利用性能,SpringBoot能主动提供相干配置,集成性能开发者仅需很少的配置。
  • 起步依赖:通知SpringBoot须要什么性能,它就能引入对应的库,无需思考该性能依赖库的版本问题。
  • Actuator:能够深刻理解SpringBoot应用程序外部状况,比方创立了哪些Bean、主动配置的决策、应用程序的状态信息等。

开始应用

创立利用

创立SpringBoot利用的形式有很多种,这里应用最风行的开发工具IDEA来创立利用。

  • 首先通过File->New Project来创立一个我的项目;

  • 而后抉择通过Spring Initializr来创立一个SpringBoot利用;

  • 填写好Maven我的项目的groupIdartifactId及抉择好Java版本;

  • 抉择好起步依赖,这里抉择的是开启Web性能的起步依赖;

  • 抉择好我的项目的寄存地位即可顺利创立一个SpringBoot利用。

查看利用

我的项目构造

一个新创建的SpringBoot利用根本构造如下。

mall-tiny-boot
├─pom.xml # Maven构建文件
└─src
   ├─main
   │  ├─java
   │  │  └─MallTinyApplication.java # 应用程序启动类
   │  └─resources
   │     └─application.yml # SpringBoot配置文件
   └─test
       └─java
           └─MallTinyApplicationTests.java # 根本的集成测试类

利用启动类

MallTinyApplication在SpringBoot利用中有配置和疏导的作用,通过@SpringBootApplication注解开启组件扫描和主动配置,通过SpringApplication.run()疏导应用程序启动;

//开启组件扫描和利用拆卸
@SpringBootApplication
public class MallTinyApplication {

    public static void main(String[] args) {
        //负责疏导应用程序启动
        SpringApplication.run(MallTinyApplication.class, args);
    }

}

@SpringBootApplication注解是三个注解的结合体,领有以下三个注解的性能:

  • @Configuration:用于申明Spring中的Java配置;
  • @ComponentScan:启用组件扫描,当咱们申明组件时,会主动发现并注册为Spring利用上下文中的Bean;
  • @EnableAutoConfiguration:开启SpringBoot主动配置性能,简化配置编写。

测试利用

能够应用@RunWith@SpringBootTest来创立Spring利用上下文,通过@Test注解来申明一个测试方法。

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MallTinyApplicationTests {
    @Autowired
    private PmsBrandService pmsBrandService;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testMethod() {
        List<PmsBrand> brandList = pmsBrandService.listAllBrand();
        log.info("testMethod:{}", brandList);
    }

}

编写利用配置

当咱们须要微调主动配置的参数时,能够在application.yml文件中进行配置,比方微调下端口号。

server:
  port: 8088

我的项目构建过程

SpringBoot我的项目能够应用Maven进行构建,首先咱们须要继承spring-boot-starter-parent这个父依赖,父依赖能够管制所有SpringBoot官网起步依赖的版本,接下来当咱们应用官网起步依赖时,就不必指定版本号了。咱们还须要应用SpringBoot的插件,该插件次要用于将利用打包为可执行Jar。

<?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>
    <groupId>com.macro.mall</groupId>
    <artifactId>mall-tiny-boot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>mall-tiny-boot</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <skipTests>true</skipTests>
    </properties>
    
    <!--继承SpringBoot父我的项目,管制所有依赖版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <!--SpringBoot起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <!--SpringBoot插件,能够把利用打包为可执行Jar-->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

应用起步依赖

应用起步依赖的益处

在应用起步依赖之前,咱们先来理解下应用起步依赖的益处,当咱们应用SpringBoot须要整合Web相干性能时,只需在pom.xml中增加一个起步依赖即可。

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

如果是Spring我的项目的话,咱们须要增加很多依赖,还须要思考各个依赖版本的兼容性问题,是个相当麻烦的事件。

指定基于性能的依赖

当咱们须要开发一个Web利用,须要应用MySQL数据库进行存储,应用Swagger生成API文档,增加如下起步依赖即可。须要留神的是只有官网的起步依赖不须要指定版本号,其余的还是须要自行指定的。

<dependencies>
    <!--SpringBoot Web性能起步依赖-->
    <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>
    <!--MyBatis分页插件-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.10</version>
    </dependency>
    <!--集成druid连接池-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <!--Mysql数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.15</version>
    </dependency>
    <!--springfox swagger官网Starter-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>

笼罩起步依赖中的库

其实起步依赖和你平时应用的依赖没什么区别,你能够应用Maven的形式来排除不想要的依赖。比方你不想应用tomcat容器,想应用undertow容器,能够在Web性能依赖中排除掉tomcat。

<dependencies>
    <!--SpringBoot Web性能起步依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <!--排除tomcat依赖-->
            <exclusion>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <groupId>org.springframework.boot</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <!--undertow容器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
</dependencies>

应用主动配置

SpringBoot的主动配置是一个运行时(更精确地说,是应用程序启动时)的过程,思考了泛滥因素,才决定Spring配置应该用哪个,不该用哪个。

举个例子,当咱们应用Spring整合MyBatis的时候,须要实现如下几个步骤:

  • 依据数据库连贯配置,配置一个dataSource对象;
  • 依据dataSource对象和SqlMapConfig.xml文件(其中蕴含mapper.xml文件门路和mapper接口门路配置),配置一个sqlSessionFactory对象。

当咱们应用SpringBoot整合MyBatis的时候,会主动创立dataSource和sqlSessionFactory对象,只需咱们在application.yml和Java配置中增加一些自定义配置即可。

application.yml中配置好数据库连贯信息及mapper.xml文件门路。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

mybatis:
  mapper-locations:
    - classpath:mapper/*.xml
    - classpath*:com/**/mapper/*.xml

应用Java配置,配置好mapper接口门路。

/**
 * MyBatis配置类
 * Created by macro on 2019/4/8.
 */
@Configuration
@MapperScan("com.macro.mall.tiny.mbg.mapper")
public class MyBatisConfig {
}

应用主动配置当前,咱们整合其余性能的配置大大减少了,能够更加专一程序性能的开发了。

自定义配置

自定义Bean笼罩主动配置

尽管主动配置很好用,但有时候主动配置的Bean并不能满足你的须要,咱们能够本人定义雷同的Bean来笼罩主动配置中的Bean。

例如当咱们应用Spring Security来爱护利用平安时,因为主动配置并不能满足咱们的需要,咱们须要自定义基于WebSecurityConfigurerAdapter的配置。这里咱们自定义了很多配置,比方将基于Session的认证改为应用JWT令牌、配置了一些门路的无受权拜访,自定义了登录接口门路,禁用了csrf性能等。

/**
 * SpringSecurity的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        List<String> urls = ignoreUrlsConfig.getUrls();
        String[] urlArray = ArrayUtil.toArray(urls, String.class);
        httpSecurity.csrf()// 因为应用的是JWT,咱们这里不须要csrf
                .disable()
                .sessionManagement()// 基于token,所以不须要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,urlArray) // 容许对于网站动态资源的无受权拜访
                .permitAll()
                .antMatchers("/admin/login")// 对登录注册要容许匿名拜访
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)//跨域申请会先进行一次options申请
                .permitAll()
                .anyRequest()// 除下面外的所有申请全副须要鉴权认证
                .authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 增加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //增加自定义未受权和未登录后果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> {
            AdminUserDetails admin = adminService.getAdminByUsername(username);
            if (admin != null) {
                return admin;
            }
            throw new UsernameNotFoundException("用户名或明码谬误");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

主动配置微调

有时候咱们只须要微调下主动配置就能满足需要,并不需要笼罩主动配置的Bean,此时咱们能够在application.yml属性文件中进行配置。

比方微调下利用运行的端口。

server:
  port: 8088

比方批改下数据库连贯信息。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

读取配置文件的自定义属性

有时候咱们会在属性文件中自定义一些属性,而后在程序中应用。此时能够将这些自定义属性映射到一个属性类里来应用。

比如说咱们想给Spring Security配置一个白名单,拜访这些门路无需受权,咱们能够先在application.yml中添增加如下配置。

secure:
  ignored:
    urls:
      - /
      - /swagger-ui/
      - /*.html
      - /favicon.ico
      - /**/*.html
      - /**/*.css
      - /**/*.js
      - /swagger-resources/**
      - /v2/api-docs/**

之后创立一个属性类,应用@ConfigurationProperties注解配置好这些属性的前缀,再定义一个urls属性与属性文件绝对应即可。

/**
 * 用于配置白名单资源门路
 * Created by macro on 2018/11/5.
 */
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "secure.ignored")
public class IgnoreUrlsConfig {

    private List<String> urls = new ArrayList<>();

}

Actuator

SpringBoot Actuator的要害个性是在应用程序里提供泛滥Web端点,通过它们理解利用程序运行时的外部情况。

端点概览

Actuator提供了大略20个端点,罕用端点门路及形容如下:

门路 申请形式 形容
/beans GET 形容应用程序上下文里全副的Bean,以及它们之间关系
/conditions GET 形容主动配置报告,记录哪些主动配置失效了,哪些没失效
/env GET 获取全副环境属性
/env/{name} GET 依据名称获取特定的环境属性
/mappings GET 形容全副的URI门路和控制器或过滤器的映射关系
/configprops GET 形容配置属性(蕴含默认值)如何注入Bean
/metrics GET 获取应用程序度量指标,比方JVM和过程信息
/metrics/{name} GET 获取指定名称的应用程序度量值
loggers GET 查看应用程序中的日志级别
/threaddump GET 获取线程流动的快照
/health GET 报告应用程序的衰弱指标,这些值由HealthIndicator的实现类提供
/shutdown POST 敞开应用程序
/info GET 获取应用程序的定制信息,这些信息由info打头的属性提供

查看配置明细

  • 间接拜访根端点,能够获取到所有端点拜访门路,根端点拜访地址:http://localhost:8088/actuator
{
    "_links": {
        "self": {
            "href": "http://localhost:8088/actuator",
            "templated": false
        },
        "beans": {
            "href": "http://localhost:8088/actuator/beans",
            "templated": false
        },
        "caches-cache": {
            "href": "http://localhost:8088/actuator/caches/{cache}",
            "templated": true
        },
        "caches": {
            "href": "http://localhost:8088/actuator/caches",
            "templated": false
        },
        "health": {
            "href": "http://localhost:8088/actuator/health",
            "templated": false
        },
        "health-path": {
            "href": "http://localhost:8088/actuator/health/{*path}",
            "templated": true
        },
        "info": {
            "href": "http://localhost:8088/actuator/info",
            "templated": false
        },
        "conditions": {
            "href": "http://localhost:8088/actuator/conditions",
            "templated": false
        },
        "configprops": {
            "href": "http://localhost:8088/actuator/configprops",
            "templated": false
        },
        "env": {
            "href": "http://localhost:8088/actuator/env",
            "templated": false
        },
        "env-toMatch": {
            "href": "http://localhost:8088/actuator/env/{toMatch}",
            "templated": true
        },
        "loggers": {
            "href": "http://localhost:8088/actuator/loggers",
            "templated": false
        },
        "loggers-name": {
            "href": "http://localhost:8088/actuator/loggers/{name}",
            "templated": true
        },
        "heapdump": {
            "href": "http://localhost:8088/actuator/heapdump",
            "templated": false
        },
        "threaddump": {
            "href": "http://localhost:8088/actuator/threaddump",
            "templated": false
        },
        "metrics-requiredMetricName": {
            "href": "http://localhost:8088/actuator/metrics/{requiredMetricName}",
            "templated": true
        },
        "metrics": {
            "href": "http://localhost:8088/actuator/metrics",
            "templated": false
        },
        "scheduledtasks": {
            "href": "http://localhost:8088/actuator/scheduledtasks",
            "templated": false
        },
        "mappings": {
            "href": "http://localhost:8088/actuator/mappings",
            "templated": false
        }
    }
}
  • 通过/beans端点,能够获取到Spring利用上下文中的Bean的信息,比方Bean的类型和依赖属性等,拜访地址:http://localhost:8088/actuator/beans
{
    "contexts": {
        "application": {
            "beans": {
                "sqlSessionFactory": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.apache.ibatis.session.defaults.DefaultSqlSessionFactory",
                    "resource": "class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]",
                    "dependencies": [
                        "dataSource"
                    ]
                },
                "jdbcTemplate": {
                    "aliases": [],
                    "scope": "singleton",
                    "type": "org.springframework.jdbc.core.JdbcTemplate",
                    "resource": "class path resource [org/springframework/boot/autoconfigure/jdbc/JdbcTemplateConfiguration.class]",
                    "dependencies": [
                        "dataSource",
                        "spring.jdbc-org.springframework.boot.autoconfigure.jdbc.JdbcProperties"
                    ]
                }
            }
        }
    }
}
  • 通过/conditions端点,能够获取到以后利用的主动配置报告,positiveMatches示意失效的主动配置,negativeMatches示意没有失效的主动配置。
{
    "contexts": {
        "application": {
            "positiveMatches": {
                "DruidDataSourceAutoConfigure": [{
                    "condition": "OnClassCondition",
                    "message": "@ConditionalOnClass found required class 'com.alibaba.druid.pool.DruidDataSource'"
                }]
            },
            "negativeMatches": {
                "RabbitAutoConfiguration": {
                    "notMatched": [{
                        "condition": "OnClassCondition",
                        "message": "@ConditionalOnClass did not find required class 'com.rabbitmq.client.Channel'"
                    }],
                    "matched": []
                }
            }
        }
    }
}
  • 通过/env端点,能够获取全副配置属性,包含环境变量、JVM属性、命令行参数和application.yml中的属性。
{
    "activeProfiles": [],
    "propertySources": [{
            "name": "systemProperties",
            "properties": {
                "java.runtime.name": {
                    "value": "Java(TM) SE Runtime Environment"
                },
                "java.vm.name": {
                    "value": "Java HotSpot(TM) 64-Bit Server VM"
                },
                "java.runtime.version": {
                    "value": "1.8.0_91-b14"
                }
            }
        },
        {
            "name": "applicationConfig: [classpath:/application.yml]",
            "properties": {
                "server.port": {
                    "value": 8088,
                    "origin": "class path resource [application.yml]:2:9"
                },
                "spring.datasource.url": {
                    "value": "jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai",
                    "origin": "class path resource [application.yml]:6:10"
                },
                "spring.datasource.username": {
                    "value": "root",
                    "origin": "class path resource [application.yml]:7:15"
                },
                "spring.datasource.password": {
                    "value": "******",
                    "origin": "class path resource [application.yml]:8:15"
                }
            }
        }
    ]
}
  • 通过/mappings端点,能够查看全副的URI门路和控制器或过滤器的映射关系,这里能够看到咱们本人定义的PmsBrandControllerJwtAuthenticationTokenFilter的映射关系。
{
    "contexts": {
        "application": {
            "mappings": {
                "dispatcherServlets": {
                    "dispatcherServlet": [{
                        "handler": "com.macro.mall.tiny.controller.PmsBrandController#createBrand(PmsBrand)",
                        "predicate": "{POST /brand/create}",
                        "details": {
                            "handlerMethod": {
                                "className": "com.macro.mall.tiny.controller.PmsBrandController",
                                "name": "createBrand",
                                "descriptor": "(Lcom/macro/mall/tiny/mbg/model/PmsBrand;)Lcom/macro/mall/tiny/common/api/CommonResult;"
                            },
                            "requestMappingConditions": {
                                "consumes": [],
                                "headers": [],
                                "methods": [
                                    "POST"
                                ],
                                "params": [],
                                "patterns": [
                                    "/brand/create"
                                ],
                                "produces": []
                            }
                        }
                    }]
                }
            },
            "servletFilters": [{
                "servletNameMappings": [],
                "urlPatternMappings": [
                    "/*",
                    "/*",
                    "/*",
                    "/*",
                    "/*"
                ],
                "name": "jwtAuthenticationTokenFilter",
                "className": "com.macro.mall.tiny.component.JwtAuthenticationTokenFilter"
            }]
        }
    }
}

查看运行时度量

  • 通过/metrics端点,能够获取应用程序度量指标,不过只能获取度量的名称;
{
    "names": [
        "http.server.requests",
        "jvm.buffer.count",
        "jvm.buffer.memory.used",
        "jvm.buffer.total.capacity",
        "jvm.classes.loaded",
        "jvm.classes.unloaded",
        "jvm.gc.live.data.size",
        "jvm.gc.max.data.size",
        "jvm.gc.memory.allocated",
        "jvm.gc.memory.promoted",
        "jvm.gc.pause",
        "jvm.memory.committed",
        "jvm.memory.max",
        "jvm.memory.used",
        "jvm.threads.daemon",
        "jvm.threads.live",
        "jvm.threads.peak",
        "jvm.threads.states",
        "logback.events",
        "process.cpu.usage",
        "process.start.time",
        "process.uptime",
        "system.cpu.count",
        "system.cpu.usage"
    ]
}
  • 须要增加指标名称能力获取对应的值,比方获取以后JVM应用的内存信息,拜访地址:http://localhost:8088/actuator/metrics/jvm.memory.used
{
    "name": "jvm.memory.used",
    "description": "The amount of used memory",
    "baseUnit": "bytes",
    "measurements": [
        {
            "statistic": "VALUE",
            "value": 3.45983088E8
        }
    ],
    "availableTags": [
        {
            "tag": "area",
            "values": [
                "heap",
                "nonheap"
            ]
        },
        {
            "tag": "id",
            "values": [
                "Compressed Class Space",
                "PS Survivor Space",
                "PS Old Gen",
                "Metaspace",
                "PS Eden Space",
                "Code Cache"
            ]
        }
    ]
}
  • 通过loggers端点,能够查看应用程序中的日志级别信息,能够看出咱们把ROOT范畴日志设置为了INFO,而com.macro.mall.tiny包范畴的设置为了DEBUG。
{
    "levels": [
        "OFF",
        "ERROR",
        "WARN",
        "INFO",
        "DEBUG",
        "TRACE"
    ],
    "loggers": {
        "ROOT": {
            "configuredLevel": "INFO",
            "effectiveLevel": "INFO"
        },
        "com.macro.mall.tiny": {
            "configuredLevel": "DEBUG",
            "effectiveLevel": "DEBUG"
        }
    }
}
  • 通过/health端点,能够查看利用的衰弱指标。
{
    "status": "UP"
}

敞开利用

通过POST申请/shutdown端点能够间接敞开利用,然而须要将endpoints.shutdown.enabled属性设置为true才能够应用。

{
    "message": "Shutting down, bye..."
}

定制Actuator

有的时候,咱们须要自定义一下Actuator的端点能力满足咱们的需要。

  • 比如说Actuator有些端点默认是敞开的,咱们想要开启所有端点,能够这样设置;
management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 比如说咱们想自定义Actuator端点的根底门路,比方改为/monitor,这样咱们咱们拜访地址就变成了这个:http://localhost:8088/monitor
management:
  endpoints:
    web:
      base-path: /monitor

罕用起步依赖

起步依赖不仅能让构建利用的依赖配置更简略,还能依据提供给应用程序的性能将它们组织到一起,这里整顿了一些罕用的起步依赖。

官网依赖

<dependencies>
    <!--SpringBoot整合Web性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--SpringBoot整合Actuator性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--SpringBoot整合AOP性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <!--SpringBoot整合测试性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--SpringBoot整合注解解决性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <!--SpringBoot整合Spring Security平安性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!--SpringBoot整合Redis数据存储性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!--SpringBoot整合Elasticsearch数据存储性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    <!--SpringBoot整合MongoDB数据存储性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <!--SpringBoot整合AMQP音讯队列性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    <!--SpringBoot整合Quartz定时工作性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-quartz</artifactId>
    </dependency>
    <!--SpringBoot整合JPA数据存储性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!--SpringBoot整合邮件发送性能依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</dependencies>

第三方依赖

<dependencies>
    <!--SpringBoot整合MyBatis数据存储性能依赖-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis-version.version}</version>
    </dependency>
    <!--SpringBoot整合PageHelper分页性能依赖-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>${pagehelper-starter.version}</version>
    </dependency>
    <!--SpringBoot整合Druid数据库连接池性能依赖-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>${druid.version}</version>
    </dependency>  
    <!--SpringBoot整合Springfox的Swagger API文档性能依赖-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>${springfox-version}</version>
    </dependency>
    <!--SpringBoot整合MyBatis-Plus数据存储性能依赖-->  
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>${mybatis-plus-version}</version>
    </dependency>
    <!--SpringBoot整合Knife4j API文档性能依赖--> 
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>${knife4j-version}</version>
    </dependency>        
</dependencies>

我的项目源码地址

https://github.com/macrozheng…

本文 GitHub https://github.com/macrozheng/mall-learning 曾经收录,欢送大家Star!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理