初步使用sharding-jdbc进行简单的读写分离和水平分片

一.水平分片:(单一表按照一列进行分片)

1.首先引入maven依赖:(已经更名为shardingsphere)

        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-core</artifactId>
            <version>3.0.0</version>
        </dependency>

2.编写yml配置文件:

dataSources:  #数据库连接信息
 ds0: !!com.zaxxer.hikari.HikariDataSource  #数据库连接池,这里引入了springboot的jdbc包
    driverClassName: org.postgresql.Driver
    jdbcUrl: jdbc:postgresql://localhost:5432/myuser?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: postgres
    password: 123456
shardingRule: #规则
  tables:
    user_info:  #逻辑表明,后面代码中sql里数据库名用这个
      actualDataNodes: ds0.user_info${1..2}  #节点名,这里下面详细说下
      tableStrategy:  #表策略
        inline:
          shardingColumn: id  #分片规则的列
          algorithmExpression: user_info${id}  #对应的实际表名
       # standard: #用于单分片键的标准分片场景
        #  shardingColumn: id
        #  preciseAlgorithmClassName: com.example.demo.Test
  #默认数据库分片策略
  #defaultDatabaseStrategy:
  #  shardingColumns: type
  #  algorithmExpression: ds0
   # t_order_item:
   #   actualDataNodes: ds${0..1}.t_order_item${0..1}
   #   tableStrategy:
   #     inline:
   #       shardingColumn: order_id
   #       algorithmExpression: t_order_item${order_id % 2}
  props:
    sql.show: true  #打印sql

注意:

(1)actualDataNodes: ds0.user_info${1..2}  这个对应的是数据库节点名;ds0代表上面配置的数据库,后面代表着递增的数据库,依次是user_info_1,user_info_2;当然在数据库中必须都实际存在,否则报错;当有这个配置项后,操作数据库的sql中如果不带有id列,则进行查询更新删除添加等都会操作全部表;

(2)如果不加以上的配置项,则不带id列的sql语句操作,默认会操作user_info表,所以实际数据库中需要有该表;如果进行其他操作数据库表,sql语句中必须带有id列;

(3)该版本中,如使用聚合函数例如count(*),max(),min()等,如果后面不带有别名则会报错,好像后面版本会更正;不报错则需返回别名如:count(*)as count

3.spring中注册datrasource

    @Bean
    public DataSource dataSource() throws IOException, SQLException {
        DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(ResourceUtils.getFile("classpath:sharding.yml"));
        return dataSource;
    }

二.读写分离

1.先自己实现数据库的主从等配置

2.编写配置:

dataSources:
  db_master: !!com.zaxxer.hikari.HikariDataSource
    driverClassName: org.postgresql.Driver
    jdbcUrl: jdbc:postgresql://192.168.134.131:5432/ceshi?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: postgres
    password: 123456
  db_slave: !!com.zaxxer.hikari.HikariDataSource
    driverClassName: org.postgresql.Driver
    jdbcUrl: jdbc:postgresql://192.168.134.131:5433/ceshi?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: postgres
    password: 123456
masterSlaveRule:
  name: db_ms
  masterDataSourceName: db_master
  slaveDataSourceNames: [db_slave]

3.注册数据源

 @Bean
    public DataSource dataSource() throws FileNotFoundException, SQLException, IOException {
        return MasterSlaveDataSourceFactory.createDataSource(ResourceUtils.getFile("classpath:sharding.yml"));
    }

猜你喜欢

转载自blog.csdn.net/myth_g/article/details/83504827