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

以动态多数据源为例

文件目录


image.png

pom.xml

<?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.oumiga.datasource</groupId>
    <artifactId>spring-boot-starter-dynamic-datasource2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <mybatis-version>3.5.7</mybatis-version>
        <druid-version>1.2.6</druid-version>
        <mybatis-spring>2.0.6</mybatis-spring>
        <mysql.version>8.0.11</mysql.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <scope>compile</scope>
            <version>2.3.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis-version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid-version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

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<DataSourceTypeEnum> 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<Object,Object> 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包

        <dependency>
            <groupId>com.oumiga.datasource</groupId>
            <artifactId>spring-boot-starter-dynamic-datasource2</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

使用方法

        //默认使用的master数据源,此处不用切换可直接使用
        masterDao.getUser();
        DataSourceContextHolder.addDataSource(DataSourceTypeEnum.SLAVE);
        slaveDao.getRole();
        DataSourceContextHolder.removeDataSource();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容