Yaml使用sharding-jdbc

2,316 阅读1分钟

增加yaml配置文件

# 数据源配置
dataSources:
  #可配置多个: !!数据库连接池实现类
  ds_0: !!com.alibaba.druid.pool.DruidDataSource
    #数据库驱动类名
    driverClassName: com.mysql.jdbc.Driver
    #数据库url连接
    url: jdbc:mysql://127.0.0.1:3306/ds_0?nullNamePatternMatchesAll=true
    #数据库用户名
    username: root
    #数据库密码
    password: root
  ds_1: !!com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ds_1?nullNamePatternMatchesAll=true
    username: root
    password: root

#分库分表配置,可配置多个logic_table_name
shardingRule:
  tables:
    t_order:
      keyGeneratorColumnName: order_id
      actualDataNodes: ds_${0..1}.t_order_${0..1}
      databaseStrategy:
        inline:
          shardingColumn: user_id
          algorithmExpression: ds_${user_id % 2}
      tableStrategy:
        inline:
          shardingColumn: order_id
          algorithmExpression: t_order_${order_id % 2}

  #属性配置(可选)
  props:
    #是否开启SQL显示,默认值: false
    sql.show: true
    #executor.size: 工作线程数量,默认值: CPU核数

代码样例:

package com.xiaofeng.cn;
import io.shardingsphere.shardingjdbc.api.yaml.YamlShardingDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class App2 {

    public static void main(String[] args) throws SQLException, IOException {


        //1.获取DataSource
        //测试的时候发现,项目所在路径中有中文文件夹,然后就读取不到文件了,需注意要全英文.
        String filePath = App2.class.getResource("/sharding.yaml").getFile();
        DataSource dataSource = YamlShardingDataSourceFactory.createDataSource(new File(filePath));

        //2.通过DataSource获取Connection
        Connection connection = dataSource.getConnection();
        //3.定义一条SQL语句
        String sql = "insert into t_order(user_id,status) values (1008,'insert')";
//        String sql = "insert into t_order(order_id,user_id,status) values (10,1008,'insert')";
        //4.通过Connection获取到PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //5.执行SQL语句
        preparedStatement.execute();

        connection = dataSource.getConnection();
        sql = "insert into t_order(user_id,status) values (1008,'insert')";
//        sql = "insert into t_order(order_id,user_id,status) values (11,1008,'insert')";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.execute();

        //6. 关闭连接
        preparedStatement.close();
        connection.close();

    }

}