介紹MyBatis專案中如何配置多個資料源連接資料庫,以及設定sql文的二級快取功能,配置多資料源與資料連接池等功能,為大家開發和平時練習的時候提供參考和查詢的工具文章,
代碼下載百度網盤下載:https://pan.baidu.com/s/1Q6pbC2SR70HKCeVXgOGUPQ
提取碼:1234
本站資源下載
Springboot + MyBatis入門培訓 1 專案運行環境配置
Springboot + MyBatis入門培訓 2 增改洗掉與查詢 in like foreach操作
MyBatis多資料源設定
在實際的專案開發中通常會遇到業務資料保存在不同的資料庫中,而我們需要操作多個資料資料庫進行業務操作的情況,在MyBati中是可以同時使用多個資料源連接資料庫的,專案中匯入dynamic-datasource 插件就可以配置多個資料源的連接,使用起來非常的簡單,操作與維護性非常的高,dynamic-datasource可以封裝成Spring Starter方式引入,支持Mybatis讀寫分離,支持通過注解動態切換切換資料源,
pom.xml
<!--多資料源需要-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.6</version>
</dependency>
spring boot application.yml文配置
? 配置多資料源唯一技術難度就是配置上,配置正確呼叫起來非常簡單,
資料源在yml檔案中的結構
- datasource: 資料源根節點
- dynamic: 多資料源配置頭節點
- primary : 默認主資料名稱
- datasource: 資料節點
- master:默認節點
- 子節點: 自定義節點名稱
配置層級
spring: spring頂層標記
datasource: 1級
dynamic: 2級
primary: master 3級
strict: false 3級
datasource: 3級
master: 4級
子節點名稱: 4級
找到目錄中的application.yml 組態檔,添加如下內容到application.yml 檔案中,
- 資料源配置要在spring節點下建立
- 默認節點與子資料庫節點下配置資料庫連接內容
配置2個資料源,在專案工程中可以使用MyBatis訪問這兩資料庫來進行sql文操作,
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/db1 #資料庫一
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
zht:
url: jdbc:mysql://localhost:3306/db2 #資料庫二
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
支持在專案中同時配置不同資料庫的資料連接
- oracle 資料庫
- mysql資料庫
- postgresql資料庫
- sqlserver資料庫
- h2資料庫
多資料庫配置
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/db1 #mysql
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
zht:
url: jdbc:oracle:thin:@localhost:1521:orcl #oracle
username: root
password: 123456
driver-class-name: oracle.jdbc.driver.OracleDriver
同時配置兩個不同的資料庫連接源,
切換資料源 @Mapper 容器操作
在檔案目錄中找到 UserSql.xml檔案,定義兩資料庫連接的 sql文方法,
- UserList 方法的中的use表在資料庫localhost:3306/db1 中
- towlist 方法中的userdb2表在資料庫localhost:3306/db2 中
UserSql.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="cn.core.my.app.dao.UserDao">
<select id="UserList" resultType="map">
select * from user
</select>
<select id="towlist" resultType="map">
select * from userdb2
</select>
</mapper>
@DS 注解打在要執行的MyBatis 執行方法上,@DS 標注要執行的資料庫連接的名稱,方法在執行的時候就執行標注的資料庫連接,
如果MyBatis 執行方法上沒有標注@DS,方法執行默認的資料庫連接,
UserDao介面
@Mapper
public interface UserDao {
//沒有定義@DS 表示執行默認資料庫
List<Map> UserList(Map map);
//強制方法訪問資料庫localhost:3306/db2來執行
@DS("zht")
List<Map> towlist(Map map);
}
MyBatisTest測驗類
@RunWith(SpringRunner.class)
@SpringBootTest(classes=OnApp.class)
public class MyBatisTest {
@Test
public void TestAddDB(){
//第一個資料庫連接表測驗 user表
userdao.UserList(new HashMap());
//第二個資料庫連接表測驗 userdb2表
userdao.towlist(new HashMap());
}
}
在測驗類中定義對應的測驗方法,
運行結果
-----------主資料庫user表 -----------------
==> Preparing: select * from user WHERE id in (?) and user like '%%'
==> Parameters: null
<== Total: 0
-----------子資料庫sys_user表-----------------
==> Preparing: select * from sys_user
==> Parameters:
<== Columns: id, acc, paw, u_name, u_post, u_edu, birthday, notes, deptid, isamdin
不同資料庫操作同表 @Service容器操作
如果兩個資料庫中有同一張表,在UserSql.xml中定義同一張表的sql文業務操作,我們要怎么做呢?我們需要定義一個spring @Service容器,在容器中使用**@DS** 注解來區分不同資料庫的操作,
UserSql.xml
<select id="addlist" resultType="map">
select * from user
</select>
在資料庫一和資料庫二中同時創建一個表user,在UserSql.xml中定義個 select * from user 業務的sql文方法,
UserDao介面
@Mapper
public interface UserDao {
//所有資料庫共同使用一張表
List<Map> addlist(Map map);
}
UserDao介面中定義這個表查詢的MyBatis 執行方法
UserServer 業務類
在@Service容器類中定義兩個執行方法,一個沒有**@DS** 注解的方法執行查詢默認資料庫中user表,別一個定義@DS(“zht”)查詢資料庫二中的user表資訊,
@Service
public class UserServer {
@Autowired
UserDao user;
public List getOne(Map map){
return user.addlist(map);
}
@DS("zht")
public List getTow(Map map){
return user.addlist(map);
}
}
MyBatisTest測驗類
@RunWith(SpringRunner.class)
@SpringBootTest(classes=OnApp.class)
public class MyBatisTest {
@Autowired
UserServer us;//業務容器引入
@Test
public void AddDB(){
//第一個資料庫連接user表
us.getOne(new HashMap());
//第二個資料庫連接user表
us.getTow(new HashMap());
}
}
運行結果
-----------主資料庫查詢 -----------------
==> Preparing: select * from user
==> Parameters:
<== Columns: id, user
<== Row: 1, username
<== Row: 2, zht
<== Total: 2
-----------子資料庫查詢 -----------------
==> Preparing: select * from user
==> Parameters:
<== Columns: id, name
<== Row: 1, 資料庫2
<== Total: 1
MyBatis快取 ehcache設定
MyBatis為了提高資料庫的使用效率,我們通常會使用到二級快取,通過二級快取來操作常用的業務數來達到減輕資料庫壓力提高效率,java中現在有大量的快取框架,我們選擇ehcache是應為它非常的成熟,和MyBatis結合的度是最好的,最最最重要的是它操作特別簡單,基本可以一看就會很容易上手,實際專案使用起來非常方便,
pom.xml
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
在需要使用快取的 MyBatis業務sql.xml 中寫入 ehcache 快取配置xml元素,快取分為兩種,1普通快取EhcacheCache,2阻塞快取 EhBlockingCache,
-
org.mybatis.caches.ehcache.EhcacheCache 普通快取
-
org.mybatis.caches.ehcache.EhBlockingCache 阻塞快取
UserSql.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="cn.core.my.app.dao.UserDao">
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<select id="addlist" resultType="map">
select * from user
</select>
</mapper>
MyBatis業務sql.xml 中默認設定, 這樣就可以簡單的宣告快取了,
快取應用于每個陳述句
- 一旦在 xml 中宣告了快取,快取將應用于 xml 中的所有sql陳述句,
- 如果不想使用快取,在陳述句上添加 useCache=“false” 作為元素屬性,
<!-- 如果不想使用快取,簡單的設定一下 useCache="false" -->
<select id="addlist" resultType="map" useCache="false">
select * from user
</select>
<!-- 不設定useCache="false" 操作的資料資訊將保持在快取中 -->
<insert id="saveuser">
INSERT INTO user(id, user)
VALUES(#{id}, #{name})
</insert>
ehcache 快取池大小設定
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.core.my.app.dao.UserDao">
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="3600"/>
<property name="timeToLiveSeconds" value="3600"/>
<property name="maxEntriesLocalHeap" value="10000"/>
<property name="maxEntriesLocalDisk" value="10000000"/>
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
一般在中小型專案中以上的快取池配置基本可以滿足業務需求,在常用的業務 sql.xml中加入以下配置就可以了,
引數串列
| 名稱 | 內容 |
|---|---|
| timeToIdleSeconds | 設定允許物件處于空閑狀態的最長時間 |
| timeToLiveSeconds | 設定物件允許存在于快取中的最長時間 |
| maxEntriesLocalHeap | 快取可以在本地堆記憶體中使用的最大快取條目 |
| maxEntriesLocalDisk | 獨立快取可以在本地磁盤上使用的最大快取條目 |
| memoryStoreEvictionPolicy | 當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理記憶體,可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數) |
資料連接池設定
我們使用阿里的druid作為資料連接池,阿里的東西不用說做的真的很強,易用性非常的好,而且功能強大我用過那么多的資料池,它的綜合性價比是最高的,而且上手成本非常的低,只要yml檔案配對了資料池就可用,它的學習和維護成本就在怎么配置yml中的對應引數,
pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
資料池 application.yml 中的層級
- 全域資料池設定,與datasource下的dynamic元素同級為全域資料池
- 獨立的資料庫連接池設定,在多資料源的資料庫連接下面設定自己獨立的資料連接池,這個池只能這個個對應的資料自己使用
全域池層級關系
spring:
datasource:
dynamic:
type: com.alibaba.druid.pool.DruidDataSource
druid://與dynamic同級別 表示是全域資料池所有資料源使用
獨立池層級關系
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
主資料庫:
type: com.alibaba.druid.pool.DruidDataSource
druid://單獨的資料連接池設定
子資料庫:
type: com.alibaba.druid.pool.DruidDataSource
druid://單獨的資料連接池設定
資料池 application.yml 中的設定
全域池例子
server:
port: 8888
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/systext?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
zht:
url: jdbc:mysql://localhost:3306/zhtsys?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
mybatis:
mapperLocations: classpath*:/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- type 元素表示連接的資料池驅動,如果是其他池下面的標簽就換成對應池的元素標簽
個資料庫的獨立池例子
server:
port: 8888
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/systext?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
zht:
url: jdbc:mysql://localhost:3306/zhtsys?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
mybatis:
mapperLocations: classpath*:/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
druid 配置引數
| 屬性 | 說明 | 備注 |
|---|---|---|
| initialSize | 啟動程式時,在連接池中初始化多少個連接 | 100 |
| maxActive | 連接池中最多支持多少個活動會話 | |
| maxWait | 程式向連接池中請求連接時,超過maxWait的值后,認為本次請求失敗,即連接池沒有可用連接,單位毫秒,設定-1時表示無限等待 | 100 |
| minEvictableIdleTimeMillis | 池中某個連接的空閑時長達到 N 毫秒后, 連接池在下次檢查空閑連接時,將回收該連接,要小于防火墻超時設定net.netfilter.nf_conntrack_tcp_timeout_established的設定 | |
| timeBetweenEvictionRunsMillis | 檢查空閑連接的頻率,單位毫秒, 非正整數時表示不進行檢查 | |
| keepAlive | 程式沒有close連接且空閑時長超過 minEvictableIdleTimeMillis,則會執行validationQuery指定的SQL,以保證該程式連接不會池kill掉,其范圍不超過minIdle指定的連接個數, | true |
| minIdle | 回收空閑連接時,將保證至少有minIdle個連接. | 與initialSize相同 |
| removeAbandoned | 要求程式從池中get到連接后, N 秒后必須close,否則druid 會強制回收該連接,不管該連接中是活動還是空閑, 以防止行程不會進行close而霸占連接, | 當發現程式有未正常close連接時設定為true |
| removeAbandonedTimeout | 設定druid 強制回收連接的時限,當程式從池中get到連接開始算起,超過此值后,druid將強制回收該連接,單位秒, | 應大于業務運行最長時間 |
| logAbandoned | 當druid強制回收連接后,是否將stack trace 記錄到日志中 | true |
| testWhileIdle | 當程式請求連接,池在分配連接時,是否先檢查該連接是否有效,(高效) | true |
| validationQuery | 檢查池中的連接是否仍可用的 SQL 陳述句,drui會連接到資料庫執行該SQL, 如果 | |
| testOnBorrow | 程式 申請 連接時,進行連接有效性檢查(低效,影響性能) | false |
| testOnReturn | 程式 返還 連接時,進行連接有效性檢查(低效,影響性能) | false |
| poolPreparedStatements | 快取通過以下兩個方法發起的SQL | |
| maxPoolPrepareStatementPerConnectionSize 每個連接最多快取多少個SQL | 20 | |
| connectProperties | 連接屬性,比如設定一些連接池統計方面的配置, |
druid 是個功能很強大的資料池,提供很多其他功能如果有需要加入其他功能的可以參考一下,下面中的配置內容,
server:
port: 8888
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/systext?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
zht:
url: jdbc:mysql://localhost:3306/zhtsys?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 連接池的配置資訊
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 20
# 配置獲取連接等待超時的時間
maxWait: 60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打開PSCache,并且指定每個連接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用于防火墻
filters: stat,wall,slf4j
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
# 配置DruidStatFilter
web-stat-filter:
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
# 配置DruidStatViewServlet
stat-view-servlet:
enabled: true
url-pattern: "/druid/*"
# IP白名單(沒有配置或者為空,則允許所有訪問)
allow: 127.0.0.1,192.168.3.25
# IP黑名單 (存在共同時,deny優先于allow)
# deny: localhost
# 禁用HTML頁面上的“Reset All”功能
reset-enable: false
# 登錄名
login-username: admin
# 登錄密碼
login-password: 123456
mybatis:
mapperLocations: classpath*:/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/290949.html
標籤:其他
上一篇:史上最全 SQL 基礎知識語法
下一篇:SSM 快速搭建筆記
