如何写一个自己的springboot-starter项目

以动态多数据源为例

文件目录


image.png

pom.xml



    4.0.0

    com.oumiga.datasource
    spring-boot-starter-dynamic-datasource2
    1.0-SNAPSHOT
    
        3.5.7
        1.2.6
        2.0.6
        8.0.11
    

    
        
            org.springframework.boot
            spring-boot-autoconfigure
            compile
            2.3.12.RELEASE
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        

        
            org.mybatis
            mybatis
            ${mybatis-version}
        

        
            com.alibaba
            druid
            ${druid-version}
        

        
            org.mybatis
            mybatis-spring
            ${mybatis-spring}
        

        
            org.springframework
            spring-jdbc
            5.2.12.RELEASE
        
    

    
        
            
                
                    org.apache.maven.plugins
                    maven-compiler-plugin
                    
                        1.8
                        1.8
                    
                
            
        
    


MasterDateSourceProperties //主数据源参数

package com.oumiga.datasource.properties;


import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "spring.datasource.master")
public class MasterDateSourceProperties {

    private String driverClassName;

    private String url;

    private String username;

    private String password;

    private Integer maxActive = 1000;

    private Integer maxWait = 500;

    private Integer minIdle = 110;

    private Integer initialSize = 100;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }
}

SlaveDateSourceProperties //从数据源参数

package com.oumiga.datasource.properties;


import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "spring.datasource.slave")
public class SlaveDateSourceProperties {

    private String driverClassName;

    private String url;

    private String username;

    private String password;

    private Integer maxActive = 1000;

    private Integer maxWait = 500;

    private Integer minIdle = 110;

    private Integer initialSize = 100;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }
}

数据库切换枚举类

package com.oumiga.datasource.constant;

public enum DataSourceTypeEnum {

    MASTER,
    SLAVE

}

DataSourceContextHolder

package com.oumiga.datasource.config;

import com.oumiga.datasource.constant.DataSourceTypeEnum;

public class DataSourceContextHolder{

        private static final ThreadLocal contextHolder = new ThreadLocal<>();

        public static void addDataSource(DataSourceTypeEnum dataSourceTypeEnum){
                contextHolder.set(dataSourceTypeEnum);
        }

        public static DataSourceTypeEnum getDataSource(){
                return contextHolder.get();
        }

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

DynamicDataSource

package com.oumiga.datasource.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }
}

DatesourceConfig

package com.oumiga.datasource.config;

import com.alibaba.druid.DbType;
import com.alibaba.druid.pool.DruidDataSource;
import com.oumiga.datasource.constant.DataSourceTypeEnum;
import com.oumiga.datasource.properties.MasterDateSourceProperties;
import com.oumiga.datasource.properties.SlaveDateSourceProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties({MasterDateSourceProperties.class,SlaveDateSourceProperties.class})
public class DatesourceConfig {

    @Resource
    private MasterDateSourceProperties masterDateSourceProperties;
    @Resource
    private SlaveDateSourceProperties slaveDateSourceProperties;

    @Bean(name = "masterDruidDataSource")
    @Primary
    public DruidDataSource masterDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setMaxActive(masterDateSourceProperties.getMaxActive());
        dataSource.setMaxWait(masterDateSourceProperties.getMaxWait());
        dataSource.setMinIdle(masterDateSourceProperties.getMinIdle());
        dataSource.setInitialSize(masterDateSourceProperties.getInitialSize());
        dataSource.setDriverClassName(masterDateSourceProperties.getDriverClassName());
        dataSource.setDbType(DbType.mysql);
        dataSource.setUrl(masterDateSourceProperties.getUrl());
        dataSource.setUsername(masterDateSourceProperties.getUsername());
        dataSource.setPassword(masterDateSourceProperties.getPassword());
        return dataSource;
    }

    @Bean(name = "slaveDruidDataSource")
    public DruidDataSource slaveDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setMaxActive(slaveDateSourceProperties.getMaxActive());
        dataSource.setMaxWait(slaveDateSourceProperties.getMaxWait());
        dataSource.setMinIdle(slaveDateSourceProperties.getMinIdle());
        dataSource.setInitialSize(slaveDateSourceProperties.getInitialSize());
        dataSource.setDriverClassName(slaveDateSourceProperties.getDriverClassName());
        dataSource.setDbType(DbType.mysql);
        dataSource.setUrl(slaveDateSourceProperties.getUrl());
        dataSource.setUsername(slaveDateSourceProperties.getUsername());
        dataSource.setPassword(slaveDateSourceProperties.getPassword());
        return dataSource;
    }


    @Bean(name = "dynamicDataSource")
    public DynamicDataSource dataSource(@Qualifier("slaveDruidDataSource")DruidDataSource slaveDataSource,@Qualifier("masterDruidDataSource") DruidDataSource masterDruidDataSource){
        Map targetDataSource = new HashMap<>();
        targetDataSource.put(DataSourceTypeEnum.MASTER,masterDruidDataSource);
        targetDataSource.put(DataSourceTypeEnum.SLAVE,slaveDataSource);
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSource);
        dynamicDataSource.setDefaultTargetDataSource(masterDruidDataSource);
        return dynamicDataSource;
    }

    @Bean(name = "SqlSessionFactory")
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:*Mapper/*.xml"));
        return bean.getObject();
    }

}

spring.factories文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.oumiga.datasource.config.DatesourceConfig

application.yml

spring:
  datasource:
    master:
##我默认使用了druid连接池
      max-wait: 500
      min-idle: 110
      max-active: 1000
      initial-size: 100
#####################
      basePackages: com.oumiga.local.xianDao
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://192.168.91.110:3306/test1?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true
      username: root
      password: 123456
    slave:
      max-wait: 500
      min-idle: 110
      max-active: 1000
      initial-size: 100
      basePackages: com.oumiga.local.wlmqDao
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://192.168.91.110:3306/test2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true
      username: root
      password: 123456

在项目中引入jar包,还需要引入一下mybatis的相关jar包

        
            com.oumiga.datasource
            spring-boot-starter-dynamic-datasource2
            1.0-SNAPSHOT
        

使用方法

        //默认使用的master数据源,此处不用切换可直接使用
        masterDao.getUser();
        DataSourceContextHolder.addDataSource(DataSourceTypeEnum.SLAVE);
        slaveDao.getRole();
        DataSourceContextHolder.removeDataSource();

你可能感兴趣的:(如何写一个自己的springboot-starter项目)