Skeleton's Initial Knowledge of Spring Boot

Keywords: Spring Druid log4j MySQL

Understanding Spring Boot

Spring Boot official website

SpringBoot makes it easy to create independent, production-level Spring-based applications that you can "run only".

We have a unique view of the Spring platform and third-party libraries so that you can start with minimal hassle. Most Spring boot applications require very little Spring configuration.

Characteristic

  • Create a stand-alone Spring application
  • Embedding Tomcat, Jetty, or Underow directly (without deploying war files)
  • Provide fixed "starter" dependencies to simplify build configuration
  • Automatically configure Spring and third-party libraries as much as possible
  • Provide production ready features such as metrics, performance checks, and external configuration
  • Absolutely no code generation and no XML configuration is required

The first Spring Book project

Core dependence

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

Project Startup Class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Project Startup Class
 *
 * @author Tellsea
 * @date 2019/7/13
 */
@SpringBootApplication
public class SkeletonApplication {

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

Druid data source

Alibaba Druid data source, related source code and documentation. Alibaba Druid Link

It is suggested that Baidu first compare the performance of connection pools and check some relevant information. Why do we use Druid as data source? Here I go straight to the case.

Configure Druid

Step 1: Relevant dependencies

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.14</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

Relevant dependencies, where you need to add a jar package for log4j, fail to find the class of the log when you start the project

Step 2: application.yml

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    platform: mysql
    url: jdbc:mysql://127.0.0.1:3306/skeleton?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT1FROMDUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    filters: stat,wall,log4j
    logSlowSql: true

Step 3:

package cn.tellsea.skeleton.core.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Druid Connection pool configuration
 *
 * @author Tellsea
 * @date 2019/7/13
 */
@Slf4j
@Configuration
public class DruidConfig {

    private static final String DB_PREFIX = "spring.datasource";

    @Bean
    public ServletRegistrationBean druidServlet() {
        log.info("Initialization druid servlet To configure ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP White List
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // IP Blacklist(When coexisting, deny takes precedence over allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        //Console Management Users
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        //Can you reset data to disable "Reset All" functionality on HTML pages
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    /**
     * Solve the problem that spring.datasource.filters=stat,wall,log4j can't be registered properly
     */
    @Data
    @Component
    @ConfigurationProperties(prefix = DB_PREFIX)
    class IDataSourceProperties {
        private String url;
        private String username;
        private String password;
        private String driverClassName;
        private int initialSize;
        private int minIdle;
        private int maxActive;
        private int maxWait;
        private int timeBetweenEvictionRunsMillis;
        private int minEvictableIdleTimeMillis;
        private String validationQuery;
        private boolean testWhileIdle;
        private boolean testOnBorrow;
        private boolean testOnReturn;
        private boolean poolPreparedStatements;
        private int maxPoolPreparedStatementPerConnectionSize;
        private String filters;
        private String connectionProperties;

        @Bean
        @Primary
        public DataSource dataSource() {
            DruidDataSource datasource = new DruidDataSource();
            datasource.setUrl(url);
            datasource.setUsername(username);
            datasource.setPassword(password);
            datasource.setDriverClassName(driverClassName);

            //configuration
            datasource.setInitialSize(initialSize);
            datasource.setMinIdle(minIdle);
            datasource.setMaxActive(maxActive);
            datasource.setMaxWait(maxWait);
            datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            datasource.setValidationQuery(validationQuery);
            datasource.setTestWhileIdle(testWhileIdle);
            datasource.setTestOnBorrow(testOnBorrow);
            datasource.setTestOnReturn(testOnReturn);
            datasource.setPoolPreparedStatements(poolPreparedStatements);
            datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
            try {
                datasource.setFilters(filters);
            } catch (SQLException e) {
                System.err.println("ruid Configuration initialization filter: " + e);
            }
            datasource.setConnectionProperties(connectionProperties);
            return datasource;
        }
    }
}

After the configuration is completed, the project also needs a persistence layer framework to perform database-related operations.

Expanding Knowledge: Learn how to configure multiple data sources, go ahead, Sao Nian

Posted by juschillinnow on Fri, 06 Sep 2019 00:54:10 -0700