依賴:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!--Mysql數(shù)據(jù)庫驅(qū)動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
</dependency>
主配置文件
server:
port: 8092
spring:
main:
# 允許Bean定義被后定義的Bean覆蓋
allow-bean-definition-overriding: true
application:
name: csip-admin
profiles:
include: sharding-master-slave
mybatis:
mapper-locations:
- classpath:dao/*.xml
- classpath*:com/**/mapper/*.xml
sharding-jdbc 讀寫分離的配置文件
#shardingsphere 讀寫分離
spring:
shardingsphere:
props:
sql:
show: true
datasource:
names: master,slave0
master:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/master?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
slave0:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/slave?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
masterslave:
load-balance-algorithm-type: round_robin
name: ms
master-data-source-name: master
slave-data-source-names: slave0
以上配置,啟動一直報錯,提示
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
但是當吧 數(shù)據(jù)源類型 從 druid 改成默認的 HikariDataSource 之后, 又可以正常啟動
也實現(xiàn)了 讀寫分離的效果, 不知道哪里錯了,嘗試了很多修改,最終都是不行,
druid 這個數(shù)據(jù)庫連接池,不知道是哪里的問題....
問題解決了:
原來是因為我使用了 druid-spring-boot-starter 內(nèi)置了自動裝配,
把依賴換成原生的就可以解決了
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
配之后,啟動,可以看到這里注入的 DataSource 已經(jīng)是 Druid了
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
這個類的 sqlSessionFactory 方法 bean定義

image.png