【springboot】spring boot配置总结

springboot配置

jpa

spring.jpa.hibernate.dialect

  • sqlserver:org.hibernate.dialect.SQLServer2012Dialect
  • mysql:org.hibernate.dialect.MySQL5Dialect

druid

基础配置

# SQL_SERVER
spring:
  datasource:
    #使用druid配置多数据源,此处配置了两个数据源
    druid:
      one:
        driver-class-name: net.sourceforge.jtds.jdbc.Driver
        url: jdbc:jtds:sqlserver://192.168.40.48:1433/HY_MIOT
        username: sa
        password: Admin2012
        #连接超时时间
        max-wait: 60000
        #初始化连接数
        initial-size: 5
        validation-query: select 'x'
        test-while-idle: true
        test-on-borrow: false
        test-on-return: false
        #配置监控统计拦截的filters
        filters: stat
        #最大连接数
        max-active: 20
        #最小连接数
        min-idle: 3
        #连接在池中的最小生成时间,单位毫秒
        min-evictable-idle-time-millis: 300000
        #配置检测需要关闭的空闲连接的间隔时间,单位毫秒
        time-between-eviction-runs-millis: 60000
        #以下两个是关闭druid连接发生异常时自动重连功能
        connection-error-retry-attempts: 0
        break-after-acquire-failure: true
      two:
        driver-class-name: net.sourceforge.jtds.jdbc.Driver
        url: jdbc:jtds:sqlserver://192.168.40.48:1433/qsb_test
        username: sa
        password: Admin2012
        max-wait: 60000
        initial-size: 5
        validation-query: select 'x'
        test-while-idle: true
        test-on-borrow: false
        test-on-return: false
        filters: stat
        max-active: 20
        min-idle: 3
        min-evictable-idle-time-millis: 300000
        time-between-eviction-runs-millis: 60000

druid在springboot中配置

/**
 * druid配置
 */
@Configuration
public class DruidConfiguration {

    @Primary
    @Bean
    @ConfigurationProperties("spring.datasource.druid.one")
    public DataSource dataSourceOne() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.two")
    public DataSource dataSourceTwo() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public StatFilter stateFilter() {
        StatFilter statFilter = new StatFilter();
        //是否记录慢sql
        statFilter.setLogSlowSql(true);
        //慢sql定义的查询时间,单位毫秒
        statFilter.setSlowSqlMillis(10000);
        return statFilter;
    }
}

logback日志配置

  1. 加一个配置文件logback-spring.xml
  2. 这是常见的配置文件,控制台输出和文件输出的定义。文件配置把INFO级别的和ERROR级别的分开,方便查找原因。
    文件内容:

<configuration  scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>qsb-dtcontextName>
    
    
    <property name="log.path" value="./log" />
    
    <property name="CONSOLE_LOG_PATTERN"
              value="%date{yyyy-MM-dd HH:mm:ss} | %highlight(%-5level) | %boldYellow(%thread) | %boldGreen(%logger) | %msg%n"/>
    
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        
        
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>${CONSOLE_LOG_PATTERN}pattern>
            
        layout>
    appender>

    
    <appender name="fileInfoLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            
            <level>ERRORlevel>
            
            <onMatch>DENYonMatch>
            
            <onMismatch>ACCEPTonMismatch>
        filter>
        
        <File>${log.path}/dt-info.logFile>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}/dt-info.%d{yyyy-MM-dd}.logfileNamePattern>
            
            <maxHistory>90maxHistory>
            
            
        rollingPolicy>
        <encoder>
            
            
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%npattern>
        encoder>
    appender>

    <appender name="fileErrorLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>Errorlevel>
        filter>
        
        <File>${log.path}/dt-error.logFile>
        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <FileNamePattern>${log.path}/dt-error.%d{yyyy-MM-dd}.logFileNamePattern>
            
            <maxHistory>90maxHistory>
            
            
        rollingPolicy>
        
        <encoder>
            
            <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%npattern>
        encoder>
    appender>

    
    <root level="info">
        <appender-ref ref="console" />
        <appender-ref ref="fileInfoLog" />
        <appender-ref ref="fileErrorLog" />
    root>

configuration>

springboot功能

开发环境热启动

  1. pom.xml 中添加依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-devtoolsartifactId>
    <optional>trueoptional>
dependency>
  1. 修改idea build project automatically (勾选)
    file->settings->build,execution,deployment -> compile

  2. alt+shift+ctrl+/ 设置register (勾选)
    compiler.automake.allow.when.app.running

获取ApplicationContext的方式

  • 说明:适用于web和非web方式
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public class ApplicationContextRegister implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextRegister.class);
    private static ApplicationContext APPLICATION_CONTEXT;

    /**  * 设置spring上下文  *  * @param applicationContext spring上下文  * @throws BeansException  */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LOGGER.debug("ApplicationContext registed-->{}", applicationContext);  APPLICATION_CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }
}

多数据源的配置和切面切换

  1. 添加多数据源的配置,需要druid依赖
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:jtds:sqlserver://192.168.40.1:1433/ds
    driver-class-name: net.sourceforge.jtds.jdbc.Driver
    username: sa
    password: xxx
  application:
    name: qsb-dt

# 更多数据源
custom:
  datasource:
    names: ds1,ds2
    ds1:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: net.sourceforge.jtds.jdbc.Driver
      url: jdbc:jtds:sqlserver://192.168.40.1:1433/ds1
      username: sa
      password: xxx
    ds2:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: net.sourceforge.jtds.jdbc.Driver
      url: jdbc:jtds:sqlserver://192.168.40.1:1433/ds2
      username: sa
      password: xxx
  1. 创建以下所有类
    • DynamicDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
 * 其实springboot已经集成了一个切换多数据源的方法,AbstractRoutingDataSource
 * 可以理解为一个map,它的key是数据源的名称,可以自己定义,它的value就是对应
 * 的数据源,底层的切换不需要关心,只需要告诉
 /
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }

}
  • DynamicDataSourceContextHolder
import java.util.ArrayList;
import java.util.List;

/**
 * 这是动态数据员的实际切换类。底层的切换不需要关心,只需要告诉需要的数据源
 * 的name就可以了。这边的保持当前数据源的name用的是ThreadLocal,为的是线程安
 * 全,保障线程安全。
 */
public class DynamicDataSourceContextHolder {

    private static final ThreadLocal contextHolder = new ThreadLocal();
    public static List dataSourceIds = new ArrayList<>();

    //切换数据源的方法
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    public static String getDataSourceType() {
        return contextHolder.get();
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }

    /**
     * 判断指定DataSrouce当前是否存在
     *
     * @param dataSourceId
     */
    public static boolean containsDataSource(String dataSourceId){
        return dataSourceIds.contains(dataSourceId);
    }
}
  • DynamicDataSourceRegister
/**
 * 动态数据源注册
* 启动动态数据源请在启动类中(如SpringBootSampleApplication) * 添加 @Import(DynamicDataSourceRegister.class) * */
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware { private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class); private ConversionService conversionService = new DefaultConversionService(); private PropertyValues dataSourcePropertyValues; // 如配置文件中未指定数据源类型,使用该默认值 private static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource"; // private static final Object DATASOURCE_TYPE_DEFAULT = // "com.zaxxer.hikari.HikariDataSource"; // 数据源 private DataSource defaultDataSource; private Map customDataSources = new HashMap<>(); @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map targetDataSources = new HashMap(); // 将主数据源添加到更多数据源中 targetDataSources.put("dataSource", defaultDataSource); DynamicDataSourceContextHolder.dataSourceIds.add("dataSource"); // 添加更多数据源 targetDataSources.putAll(customDataSources); for (String key : customDataSources.keySet()) { DynamicDataSourceContextHolder.dataSourceIds.add(key); } // 创建DynamicDataSource GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(DynamicDataSource.class); beanDefinition.setSynthetic(true); MutablePropertyValues mpv = beanDefinition.getPropertyValues(); mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource); mpv.addPropertyValue("targetDataSources", targetDataSources); registry.registerBeanDefinition("dataSource", beanDefinition); logger.info("Dynamic DataSource Registry"); } /** * 创建DataSource * * @return */ @SuppressWarnings("unchecked") public DataSource buildDataSource(Map dsMap) { try { Object type = dsMap.get("type"); if (type == null) type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource Class dataSourceType; dataSourceType = (Class) Class.forName((String) type); String driverClassName = dsMap.get("driver-class-name").toString(); String url = dsMap.get("url").toString(); String username = dsMap.get("username").toString(); String password = dsMap.get("password").toString(); DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url) .username(username).password(password).type(dataSourceType); return factory.build(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * 加载多数据源配置 */ @Override public void setEnvironment(Environment env) { initDefaultDataSource(env); initCustomDataSources(env); } /** * 初始化主数据源 * */ private void initDefaultDataSource(Environment env) { // 读取主数据源 RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource."); Map dsMap = new HashMap<>(); dsMap.put("type", propertyResolver.getProperty("type")); dsMap.put("driver-class-name", propertyResolver.getProperty("driver-class-name")); dsMap.put("url", propertyResolver.getProperty("url")); dsMap.put("username", propertyResolver.getProperty("username")); dsMap.put("password", propertyResolver.getProperty("password")); logger.info("{}", dsMap); defaultDataSource = buildDataSource(dsMap); dataBinder(defaultDataSource, env); } /** * 为DataSource绑定更多数据 * * @param dataSource * @param env */ private void dataBinder(DataSource dataSource, Environment env){ RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource); //dataBinder.setValidator(new LocalValidatorFactory().run(this.applicationContext)); dataBinder.setConversionService(conversionService); dataBinder.setIgnoreNestedProperties(false);//false dataBinder.setIgnoreInvalidFields(false);//false dataBinder.setIgnoreUnknownFields(true);//true if (dataSource instanceof DruidDataSource) { ((DruidDataSource) dataSource).setValidationQuery("select 'x'"); } if(dataSourcePropertyValues == null){ Map rpr = new RelaxedPropertyResolver(env, "spring.datasource").getSubProperties("."); Map values = new HashMap<>(rpr); // 排除已经设置的属性 values.remove("type"); values.remove("driver-class-name"); values.remove("url"); values.remove("username"); values.remove("password"); dataSourcePropertyValues = new MutablePropertyValues(values); } dataBinder.bind(dataSourcePropertyValues); } /** * 初始化更多数据源 * */ private void initCustomDataSources(Environment env) { // 读取配置文件获取更多数据源,也可以通过defaultDataSource读取数据库获取更多数据源 RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "custom.datasource."); String dsPrefixs = propertyResolver.getProperty("names"); for (String dsPrefix : dsPrefixs.split(",")) {// 多个数据源 Map dsMap = propertyResolver.getSubProperties(dsPrefix + "."); DataSource ds = buildDataSource(dsMap); customDataSources.put(dsPrefix, ds); dataBinder(ds, env); } }
  • TargetDataSource
import java.lang.annotation.*;

/**
 * 在方法上使用,用于指定使用哪个数据源
 *
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
    String name();
}
  • DynamicDataSourceAspect
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
        String dsId = ds.name();
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            logger.error("数据源[{}]不存在,使用默认数据源 > {}", ds.name(), point.getSignature());
        } else {
            logger.debug("Use DataSource : {} > {}", ds.name(), point.getSignature());
            DynamicDataSourceContextHolder.setDataSourceType(ds.name());
        }
    }

    @After("@annotation(ds)")
    public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
        logger.debug("Revert DataSource : {} > {}", ds.name(), point.getSignature());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}
  1. 用测试service进行测试
@Service
public class TestService {
    @Autowired private BdPersonMapper bdPersonMapper;

    /**
     * 指定数据源
     */
    @TargetDataSource(name="ds1")
    public List findAll1(){
        return bdPersonMapper.findAll();
    }

    /**
     * 指定数据源
     */
    @TargetDataSource(name="ds2")
    public List findAll2(){
        return bdPersonMapper.findAll();
    }
}

你可能感兴趣的:(开发框架)