直接附上配置
本文主要讲解的是基于yml文件的方式实现分库分表和读写分离的实现。下一遍会讲解基于Config配置文件的方式实现分表分表和读写分离。
yml文件配置
#server
server:
port: 8081
#mybatis-plus
mybatis-plus:
typeEnumsPackage: com.modou.entity.enums
configuration:
cache-enabled: false
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
global-config:
db-column-underline: true
field-strategy: 0
id-type: 0
refresh-mapper: true
mapper-locations: classpath:/mapper/*.xml
typeAliasesPackage: com.modou.entity
# logging:
# level:
# com.hao.employment.dao: debug
#spring
spring:
main:
allow-bean-definition-overriding: true
profiles:
include: integration-test
redis:
# 0 数据库 切换数据库命令 select 0 *******
database: 0
host: 127.0.0.1
# password: ************
port: 6379
#resources
resources:
static-locations: classpath:/public/,classpath:/static/,classpath:/static/static
sharding:
jdbc:
dataSource:
names: db-test0,db-test1
db-test0: #org.apache.tomcat.jdbc.pool.DataSource
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://*********:3306/modou?useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT
username: root
password: ******
maxPoolSize: 20
db-test1:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://********:3306/modou?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT
username: root
password: *******
maxPoolSize: 20
props:
sql:
show: true
# 第一个需要分表的表名配置
sharding.jdbc.config.sharding.tables.order_post_addr.actual-data-nodes: ds_0.order_post_addr_$->{0..49}
# 第二个需要分表的表名配置
sharding.jdbc.config.sharding.tables.order_ext.actual-data-nodes: ds_0.order_ext_$->{0..49}
# 第一个需要分表的分表属性配置
sharding.jdbc.config.sharding.tables.order_post_addr.table-strategy.standard.sharding-column: sub
# 第二个需要分表的分表属性配置
sharding.jdbc.config.sharding.tables.order_ext.table-strategy.standard.sharding-column: sub
# 分库分表的算法类
sharding.jdbc.config.sharding.tables.order_post_addr.table-strategy.standard.precise-algorithm-class-name: com.modou.config.MyPreciseShardingAlgorithm
# 分库分表的算法类
sharding.jdbc.config.sharding.tables.order_ext.table-strategy.standard.precise-algorithm-class-name: com.modou.config.MyPreciseShardingAlgorithm
# 读写分离配置(主库标识)
sharding.jdbc.config.sharding.master-slave-rules.ds_0.master-data-source-name: db-test0
# 读写分离配置(从库标识)
sharding.jdbc.config.sharding.master-slave-rules.ds_0.slave-data-source-names: db-test1
分表算法类
public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
for (String tableName : availableTargetNames) {
if (tableName.endsWith(shardingValue.getValue() % 50 + "")) {
return tableName;
}
}
throw new IllegalArgumentException();
}
}