1、其实很简单
2、创建mysql主从实例
3、创建sprigboot项目
3.1 加入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>io.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>3.1.0.M1</version>
</dependency>
3.2 配置
sharding:
jdbc:
dataSource:
names: db-test0,db-test1
db-test0:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.11.110:35555/cool?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
username: root
password: root
maxPoolSize: 20
db-test1:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.11.110:26384/cool?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT
username: root
password: root
maxPoolSize: 20
config:
masterslave:
load-balance-algorithm-type: round_robin
name: db1s2
master-data-source-name: db-test0
slave-data-source-names: db-test1
props:
sql:
show: true
server.port: 8085
mybatis.config-location: classpath:META-INF/mybatis-config.xml
3.3 正常使用mybatis
3.4 读写分离结果
2021-03-02 18:10:32.983 [http-nio-8085-exec-8] INFO ShardingSphere-SQL - Rule Type: master-slave
2021-03-02 18:10:32.984 [http-nio-8085-exec-8] INFO ShardingSphere-SQL - SQL: SELECT u.* FROM user u ::: DataSources: db-test1
2021-03-02 18:10:33.164 [http-nio-8085-exec-10] INFO ShardingSphere-SQL - Rule Type: master-slave
2021-03-02 18:10:33.165 [http-nio-8085-exec-10] INFO ShardingSphere-SQL - SQL: SELECT u.* FROM user u ::: DataSources: db-test1
2021-03-02 18:10:42.122 [http-nio-8085-exec-4] INFO ShardingSphere-SQL - Rule Type: master-slave
2021-03-02 18:10:42.123 [http-nio-8085-exec-4] INFO ShardingSphere-SQL - SQL: INSERT INTO user (
id, username, password
)
VALUES (
?,
?,
?
) ::: DataSources: db-test0