最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot mybatis druid配置多數(shù)據(jù)源教程

 更新時(shí)間:2021年11月17日 10:50:32   作者:liuhmmjj  
這篇文章主要介紹了springboot mybatis druid配置多數(shù)據(jù)源教程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

1、項(xiàng)目代碼結(jié)構(gòu)

2、導(dǎo)入基本依賴

記得需要導(dǎo)入mysql驅(qū)動(dòng)mysql-connector-java

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.2</version>
		</dependency>
		<dependency> <!-- MySql驅(qū)動(dòng) -->
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!--druid 依賴-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.10</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

3、配置多數(shù)據(jù)源

注意:Spring Boot 2.X 版本不再支持配置繼承,多數(shù)據(jù)源的話每個(gè)數(shù)據(jù)源的所有配置都需要單獨(dú)配置,否則配置不會(huì)生效。

spring:
  datasource:
    db1:
      url: jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
      username: root
      password:
      driver-class-name: com.mysql.cj.jdbc.Driver
 
      # 初始化時(shí)建立物理連接的個(gè)數(shù)。初始化發(fā)生在顯示調(diào)用 init 方法,或者第一次 getConnection 時(shí)
      initialSize: 5
      # 最小連接池?cái)?shù)量
      minIdle: 5
      # 最大連接池?cái)?shù)量
      maxActive: 10
      # 獲取連接時(shí)最大等待時(shí)間,單位毫秒。配置了 maxWait 之后,缺省啟用公平鎖,并發(fā)效率會(huì)有所下降,如果需要可以通過配置 useUnfairLock 屬性為 true 使用非公平鎖。
      maxWait: 60000
      # Destroy 線程會(huì)檢測連接的間隔時(shí)間,如果連接空閑時(shí)間大于等于 minEvictableIdleTimeMillis 則關(guān)閉物理連接。
      timeBetweenEvictionRunsMillis: 60000
      # 連接保持空閑而不被驅(qū)逐的最小時(shí)間
      minEvictableIdleTimeMillis: 300000
      # 用來檢測連接是否有效的 sql 因數(shù)據(jù)庫方言而異, 例如 oracle 應(yīng)該寫成 SELECT 1 FROM DUAL
      validationQuery: SELECT 1
      # 建議配置為 true,不影響性能,并且保證安全性。申請連接的時(shí)候檢測,如果空閑時(shí)間大于 timeBetweenEvictionRunsMillis,執(zhí)行 validationQuery 檢測連接是否有效。
      testWhileIdle: true
      # 申請連接時(shí)執(zhí)行 validationQuery 檢測連接是否有效,做了這個(gè)配置會(huì)降低性能。
      testOnBorrow: false
      # 歸還連接時(shí)執(zhí)行 validationQuery 檢測連接是否有效,做了這個(gè)配置會(huì)降低性能。
      testOnReturn: false
      # 是否自動(dòng)回收超時(shí)連接
      removeAbandoned: true
      # 超時(shí)時(shí)間 (以秒數(shù)為單位)
      remove-abandoned-timeout: 1800
 
    db2:
      url: jdbc:mysql://127.0.0.1:3306/db02?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
      username: root
      password:
      driver-class-name: com.mysql.cj.jdbc.Driver
 
      # 初始化時(shí)建立物理連接的個(gè)數(shù)。初始化發(fā)生在顯示調(diào)用 init 方法,或者第一次 getConnection 時(shí)
      initialSize: 6
      # 最小連接池?cái)?shù)量
      minIdle: 6
      # 最大連接池?cái)?shù)量
      maxActive: 10
      # 獲取連接時(shí)最大等待時(shí)間,單位毫秒。配置了 maxWait 之后,缺省啟用公平鎖,并發(fā)效率會(huì)有所下降,如果需要可以通過配置 useUnfairLock 屬性為 true 使用非公平鎖。
      maxWait: 60000
      # Destroy 線程會(huì)檢測連接的間隔時(shí)間,如果連接空閑時(shí)間大于等于 minEvictableIdleTimeMillis 則關(guān)閉物理連接。
      timeBetweenEvictionRunsMillis: 60000
      # 連接保持空閑而不被驅(qū)逐的最小時(shí)間
      minEvictableIdleTimeMillis: 300000
      # 用來檢測連接是否有效的 sql 因數(shù)據(jù)庫方言而異, 例如 oracle 應(yīng)該寫成 SELECT 1 FROM DUAL
      validationQuery: SELECT 1
      # 建議配置為 true,不影響性能,并且保證安全性。申請連接的時(shí)候檢測,如果空閑時(shí)間大于 timeBetweenEvictionRunsMillis,執(zhí)行 validationQuery 檢測連接是否有效。
      testWhileIdle: true
      # 申請連接時(shí)執(zhí)行 validationQuery 檢測連接是否有效,做了這個(gè)配置會(huì)降低性能。
      testOnBorrow: false
      # 歸還連接時(shí)執(zhí)行 validationQuery 檢測連接是否有效,做了這個(gè)配置會(huì)降低性能。
      testOnReturn: false
      # 是否自動(dòng)回收超時(shí)連接
      removeAbandoned: true
      # 超時(shí)時(shí)間 (以秒數(shù)為單位)
      remove-abandoned-timeout: 1800
 
    # WebStatFilter 用于采集 web-jdbc 關(guān)聯(lián)監(jiān)控的數(shù)據(jù)。
    web-stat-filter:
      # 是否開啟 WebStatFilter 默認(rèn)是 true
      enabled: true
      # 需要攔截的 url
      url-pattern: /*
      # 排除靜態(tài)資源的請求
      exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
 
    # Druid 內(nèi)置提供了一個(gè) StatViewServlet 用于展示 Druid 的統(tǒng)計(jì)信息。
    stat-view-servlet:
      #是否啟用 StatViewServlet 默認(rèn)值 true
      enabled: true
      # 需要攔截的 url
      url-pattern: /druid/*
      # 允許清空統(tǒng)計(jì)數(shù)據(jù)
      reset-enable: true
      login-username: druid
      login-password: druid

4、配置類

主數(shù)據(jù)源配置類:

package com.study.multisource.config; 
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.sql.DataSource;
 
/**
 * @author liuhui
 * @date 2020/5/14 16:56
 */
@Configuration
@MapperScan(basePackages = "com.study.multisource.mybatis.oneDao",sqlSessionFactoryRef = "oneSqlSessionFactory")
public class DataSourceConfig1 {
    // 將這個(gè)對象放入Spring容器中
    @Bean(name = "oneDataSource")
    // 表示這個(gè)數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
    @Primary
    // 讀取application.properties中的配置參數(shù)映射成為一個(gè)對象
    // prefix表示參數(shù)的前綴
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource getDateSource1()
    {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "oneSqlSessionFactory")
    // 表示這個(gè)數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
    @Primary
    // @Qualifier表示查找Spring容器中名字為oneDataSource的對象
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 設(shè)置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/one/*.xml"));
        return bean.getObject();
    }
 
    @Bean("oneSqlSessionTemplate")
    // 表示這個(gè)數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
    @Primary
    public SqlSessionTemplate oneSqlSessionTemplate(
            @Qualifier("oneSqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
 
}

次數(shù)據(jù)源配置類:

package com.study.multisource.config; 
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.sql.DataSource;
 
/**
 * @author liuhui
 * @date 2020/5/14 17:07
 */
@Configuration
@MapperScan(basePackages = "com.study.multisource.mybatis.twoDao",sqlSessionFactoryRef = "twoSqlSessionFactory")
public class DataSourceConfig2 {
    // 將這個(gè)對象放入Spring容器中
    @Bean(name = "twoDataSource")
    // 讀取application.properties中的配置參數(shù)映射成為一個(gè)對象
    // prefix表示參數(shù)的前綴
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource getDateSource1()
    {
        return DataSourceBuilder.create().type(DruidDataSource.class).build();
    }
 
    @Bean(name = "twoSqlSessionFactory")
    // 表示這個(gè)數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
    @Primary
    // @Qualifier表示查找Spring容器中名字為oneDataSource的對象
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("twoDataSource") DataSource datasource)
            throws Exception
    {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 設(shè)置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/two/*.xml"));
        return bean.getObject();
    }
 
    @Bean("twoSqlSessionTemplate")
    // 表示這個(gè)數(shù)據(jù)源是默認(rèn)數(shù)據(jù)源
    @Primary
    public SqlSessionTemplate oneSqlSessionTemplate(
            @Qualifier("twoSqlSessionFactory") SqlSessionFactory sessionFactory)
    {
        return new SqlSessionTemplate(sessionFactory);
    }
 
}

5、啟動(dòng)類

注意:不需要使用自動(dòng)配置,那么需要取消加載對應(yīng)的自動(dòng)配置類。

在啟動(dòng)類關(guān)閉 Spring Boot 對數(shù)據(jù)源的自動(dòng)化配置,由我們手動(dòng)進(jìn)行多數(shù)據(jù)源的配置:

package com.study.multisource; 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
 
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MultisourceApplication { 
	public static void main(String[] args) {
		SpringApplication.run(MultisourceApplication.class, args);
	} 
}

6、測試使用的表

#建在db01庫下
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
#建在db02庫下
CREATE TABLE `t_item_order` (
  `id` int(9) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `item_id` int(4) NOT NULL COMMENT '商品id',
  `item_name` varchar(50) NOT NULL DEFAULT '' COMMENT '商品名稱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='商品表';

7、測試表對應(yīng)的實(shí)體類

package com.study.multisource.entity; 
import lombok.Data;
import lombok.ToString;
 
/**
 * @author liuhui
 * @date 2020/5/14 17:32
 */
@Data
@ToString
public class ItemOrder {
    private Integer id;
    private Integer itemId;
    private String itemName;
}
package com.study.multisource.entity; 
import lombok.Data;
import lombok.ToString;
 
/**
 * @author liuhui
 * @date 2020/5/14 17:29
 */
@Data
@ToString
public class User {
    private Long id;
    private String name;
}

8、持久層:dao層接口

(注意:我將其放在不同目錄下方便區(qū)分管理):

package com.study.multisource.mybatis.oneDao; 
import com.study.multisource.entity.User; 
import java.util.List; 
public interface UserMapper {
    List<User> getAllUser();
}
package com.study.multisource.mybatis.twoDao; 
import com.study.multisource.entity.ItemOrder; 
import java.util.List; 
public interface ItemOrderMapper {
    List<ItemOrder> getAllItemOrder();
}

dao層對應(yīng)的xml配置文件:

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.multisource.mybatis.oneDao.UserMapper">
    <select id="getAllUser" resultType="com.study.multisource.entity.User">
        select *
        from `user`
    </select>
</mapper>

ItemOrderMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.study.multisource.mybatis.twoDao.ItemOrderMapper">
    <resultMap id="BaseResultMap" type="com.study.multisource.entity.ItemOrder">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="item_id" jdbcType="INTEGER" property="itemId" />
        <result column="item_name" jdbcType="VARCHAR" property="itemName" />
    </resultMap>
    <select id="getAllItemOrder" resultMap="BaseResultMap">
        select *
        from t_item_order
    </select>
</mapper>

service層:

接口:

package com.study.multisource.service; 
import com.study.multisource.entity.ItemOrder;
import com.study.multisource.entity.User; 
import java.util.List;
 
/**
 * @author liuhui
 * @date 2020/5/14 17:24
 */
public interface TestService {
    public List<User> getAllUser();
    public List<ItemOrder> getAllItemOrder();
}

實(shí)現(xiàn)類:

package com.study.multisource.service.impl; 
import com.study.multisource.entity.ItemOrder;
import com.study.multisource.entity.User;
import com.study.multisource.mybatis.oneDao.UserMapper;
import com.study.multisource.mybatis.twoDao.ItemOrderMapper;
import com.study.multisource.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; 
import java.util.List;
 
/**
 * @author liuhui
 * @date 2020/5/14 17:25
 */
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    ItemOrderMapper itemOrderMapper;
    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
 
    @Override
    public List<ItemOrder> getAllItemOrder() {
        return itemOrderMapper.getAllItemOrder();
    } 
}

下面進(jìn)行測試:

package com.study.multisource.multisource; 
import com.study.multisource.service.TestService;
import lombok.ToString;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
@SpringBootTest
class MultisourceApplicationTests { 
	@Autowired
	TestService testService;
	@Test
	void contextLoads() {
	}
	@Test
	void testS(){
		System.out.println(testService.getAllItemOrder());
		System.out.println(testService.getAllUser()); 
	} 
}

結(jié)果:

2020-05-16 08:54:17.566  INFO 12556 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
[ItemOrder(id=1, itemId=101, itemName=泡泡糖)]
--------------------------
2020-05-16 08:54:17.752  INFO 12556 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} inited
[User(id=2, name=Lucy), User(id=4, name=Lina)]

當(dāng)然也可以不用向上面分的那么細(xì),也可以把多個(gè)數(shù)據(jù)源下面的XxxMapper.xml放在同一個(gè)目錄下,同時(shí)就可以把多個(gè)數(shù)據(jù)源的配置類解析的xml路徑寫成同一個(gè)了

new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

桐柏县| 介休市| 涪陵区| 湟中县| 曲周县| 津市市| 南宁市| 镶黄旗| 安平县| 图木舒克市| 铁岭市| 察哈| 曲水县| 邢台市| 甘德县| 芦山县| 永丰县| 唐海县| 渝北区| 武义县| 渭源县| 峨眉山市| 苍溪县| 涟水县| 广灵县| 花垣县| 图片| 凤凰县| 车险| 从化市| 台中市| 青川县| 陇南市| 锡林郭勒盟| 浦县| 阜康市| 玉林市| 富蕴县| 安新县| 广丰县| 英德市|