分庫分表之第二篇

2. Sharding-JDBC快速入門

2.1需求說明

使用Sharding-JDBC完成對訂單表的水平分表,經過快速入門程序的開發,快速體驗Sharding-JDBC的使用。人工建立兩張表,t_order_1和t_order_2,這張表是訂單表替換後的表,經過Shading-JDBC向訂單表插入數據,按照必定的分片規則,主鍵爲偶數的盡入t_order_1,另外一部分數據進入t_order_2,經過Shading-Jdbc查詢數據,根據SQL語句的內容從t_order_1或order_2查詢數據。java

2.2. 環境建設

2.2.1環境說明

操做系統:Win10數據庫:MySQL-5.7.25 JDK:64位jdk1.8.0_201應用框架:spring-boot-2.1.3.RELEASE,Mybatis3.5.0 Sharding-JDBC:sharding-jdbc-spring-boot-starter-4.0 .0-RC1node

2.2.2建立數據庫

建立訂單表mysql

CREATE DATABASE`order_db`字符集'UTF8'COLLATE'utf8_general_ci'; ```在order_db中建立t_order_1,t_order_2表若是存在java DROP TABLE t_order_1; CREATE TABLE`t_order_1`(`order_id` BIGINT(20)非空註釋'訂單ID',`price`十進制(10,2)非空註釋'訂單價格',`user_id` BIGINT(20)非空註釋「下一個單用戶id」,「狀態」 varchar(50)字符集utf8集合utf8_general_ci NOT NULL COMMENT「訂單狀態」,主鍵(`order_id`)使用BTREE)引擎= InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = 若是存在表t_order_2; CREATE TABLE`t_order_2`(`order_id` BIGINT(20)非空註釋'訂單ID',`price`十進制(10,2)非空註釋'訂單價格',`user_id` BIGINT(20)非空註釋'下一個單用戶id',`status` varchar(50)字符集utf8集合utf8_general_ci NOT NULL COMMENT'訂單狀態',主鍵(`order_id`)使用BTREE 
)ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT =動態;

2.2.3約會maven依賴

sharding-jdbc和SpringBoot整合的Jar包:web

<dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding‐jdbc‐spring‐boot‐starter</artifactId> <version>4.0.0‐RC1</version> </dependency> 

2.3 編寫程序

2.3.1 分片規則配置

分片規則配置是sharding-jdbc進行分庫分表操做的重要依據,配置內容包括 :數據源、主鍵生成策略等。
在application.properties中配置算法

server.port=56081 spring.application.name = sharding‐jdbc‐simple‐demo server.servlet.context‐path = /sharding‐jdbc‐simple‐demo spring.http.encoding.enabled = true spring.http.encoding.charset = UTF‐8 spring.http.encoding.force = true spring.main.allow‐bean‐definition‐overriding = true mybatis.configuration.map‐underscore‐to‐camel‐case = true # 如下是分片規則配置 # 定義數據源 spring.shardingsphere.datasource.names = m1 spring.shardingsphere.datasource.m1.type = com.alibaba.druid.pool.DruidDataSource spring.shardingsphere.datasource.m1.driver‐class‐name = com.mysql.jdbc.Driver spring.shardingsphere.datasource.m1.url = jdbc:mysql://localhost:3306/order_db?useUnicode=true spring.shardingsphere.datasource.m1.username = root spring.shardingsphere.datasource.m1.password = root # 指定t_order表的數據分佈狀況,配置數據節點 spring.shardingsphere.sharding.tables.t_order.actual‐data‐nodes = m1.t_order_$‐>{1..2} # 指定t_order表的主鍵生成策略爲SNOWFLAKE spring.shardingsphere.sharding.tables.t_order.key‐generator.column=order_id spring.shardingsphere.sharding.tables.t_order.key‐generator.type=SNOWFLAKE # 指定t_order表的分片策略,分片策略包括分片鍵和分片算法 spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.sharding‐column = order_id spring.shardingsphere.sharding.tables.t_order.table‐strategy.inline.algorithm‐expression = t_order_$‐>{order_id % 2 + 1} # 打開sql輸出日誌 spring.shardingsphere.props.sql.show = true swagger.enable = true logging.level.root = info logging.level.org.springframework.web = info logging.level.com.itheima.dbsharding = debug logging.level.druid.sql = debug 
  1. 首先定義數據源m1,並對m1進行實際的參數配置
  2. 指定t_order表的數據分佈狀況,它分佈在m1.t_order_一、m1.t_order_2
  3. 指定t_order表的主鍵生成策略爲SNOWFLAKE,SNOWFLAKE是一種分佈式自增算法,保證id全局惟一
  4. 定義t_order分片策略,order_id爲偶數的數據落在t_order_1,爲奇數的落在t_order_2,分表策略的表達式爲t_order_$->{order_id % 2 + 1}

2.3.2 數據操做

@Mapper @Component public interface OrderDao { /** * 新增訂單 * @param price 訂單價格 * @param userId 用戶id * @param status 訂單狀態 * @return */ @Insert("insert into t_order(price,user_id,status) value(#{price},#{userId},#{status})") int insertOrder(@Param("price") BigDecimal price, @Param("userId")Long userId, @Param("status")String status); /** * 根據id列表查詢多個訂單 * @param orderIds 訂單id列表 * @return */ @Select({"<script>" + "select " + "*"+ " from t_order t" + " where t.order_id in " + "<foreach collection='orderIds' item='id' open='(' separator=',' close=')'>" + " #{id} " + "</foreach>"+ "</script>"}) List<Map> selectOrderbyIds(@Param("orderIds")List<Long> orderIds); } 

2.3.3 測試

編寫單元測試 :spring

@RunWith(SpringRunner.class) @SpringBootTest(classes = {ShardingJdbcSimpleDemoBootstrap.class}) public class OrderDaoTest { @Autowired private OrderDao orderDao; @Test public void testInsertOrder(){ for (int i = 0 ; i<10; i++){ orderDao.insertOrder(new BigDecimal((i+1)*5),1L,"WAIT_PAY"); } } @Test public void testSelectOrderbyIds(){ List<Long> ids = new ArrayList<>(); ids.add(373771636085620736L); ids.add(373771635804602369L); List<Map> maps = orderDao.selectOrderbyIds(ids); System.out.println(maps); } } 

執行testInsertOrder:
https://img-blog.csdnimg.cn/20191219211246974.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW8xMjk5MDAyNzg4,size_16,color_FFFFFF,t_70
經過日誌能夠發現order_id爲奇數的被插入到t_order_2表,爲偶數的被插入到t_order_1表,達到預期目標。
執行testSelectOrderbyIds:
https://img-blog.csdnimg.cn /20191219211311247.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3poYW8xMjk5MDAyNzg4,size_16,color_FFFFFF,t_70
經過日誌能夠發現,根據傳入的order_id的奇偶不一樣,分片-JDBC分別去不一樣的表檢索數據,達到預期目標。sql

2.4. 流程分析

經過日誌分析,Sharding-JDBC在拿到用戶要執行的sql以後幹了那些事兒 :
(1)解析sql,獲取片鍵值,在本例中是order_id
(2)Sharding-JDBC經過規則配置t_order_$->{order_id% 2 + 1},知道類當order_id爲偶數時,應該往t_order_1表插數據,爲奇數時,往t_order_2插數據。
(3)因而Sharding-JDBC根據order_id的值改寫sql語句,改寫後的SQL語句是真實所要執行的SQL語句。
(4)執行改寫後的真實sql語句
(5)將全部真正執行sql的結果進行彙總合併,返回。數據庫

2.5 其餘集成方式

Sharding-JDBC不只能夠與Spring boot良好集成,它還支持其餘配置方式,共支持如下四種集成方式。
Spring Boot Yaml配置
定義application.yml,內容以下 :express

server: port: 56081 servlet: context‐path: /sharding‐jdbc‐simple‐demo spring: application: name: sharding‐jdbc‐simple‐demo http: encoding: enabled: true charset: utf‐8 force: true main: allow‐bean‐definition‐overriding: true shardingsphere: datasource: names: m1 m1: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/order_db?useUnicode=true username: root password: mysql sharding: tables: t_order: actualDataNodes: m1.t_order_$‐>{1..2} tableStrategy: inline: shardingColumn: order_id algorithmExpression: t_order_$‐>{order_id % 2 + 1} keyGenerator: type: SNOWFLAKE column: order_id props: sql: show: true mybatis: configuration: map‐underscore‐to‐camel‐case: true swagger: enable: true logging: level: root: info org.springframework.web: info com.itheima.dbsharding: debug druid.sql: debug 

若是使用application.yml則須要屏蔽原來的application.properties文件。
Java配置
添加配置類 :apache

@Configuration public class ShardingJdbcConfig { // 定義數據源 Map<String, DataSource> createDataSourceMap() { DruidDataSource dataSource1 = new DruidDataSource(); dataSource1.setDriverClassName("com.mysql.jdbc.Driver"); dataSource1.setUrl("jdbc:mysql://localhost:3306/order_db?useUnicode=true"); dataSource1.setUsername("root"); dataSource1.setPassword("root"); Map<String, DataSource> result = new HashMap<>(); result.put("m1", dataSource1); return result; } // 定義主鍵生成策略 private static KeyGeneratorConfiguration getKeyGeneratorConfiguration() { KeyGeneratorConfiguration result = new KeyGeneratorConfiguration("SNOWFLAKE","order_id"); return result; } // 定義t_order表的分片策略 TableRuleConfiguration getOrderTableRuleConfiguration() { TableRuleConfiguration result = new TableRuleConfiguration("t_order","m1.t_order_$‐> {1..2}"); result.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "t_order_$‐>{order_id % 2 + 1}")); result.setKeyGeneratorConfig(getKeyGeneratorConfiguration()); return result; } // 定義sharding‐Jdbc數據源 @Bean DataSource getShardingDataSource() throws SQLException { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); shardingRuleConfig.getTableRuleConfigs().add(getOrderTableRuleConfiguration()); //spring.shardingsphere.props.sql.show = true Properties properties = new Properties(); properties.put("sql.show","true"); return ShardingDataSourceFactory.createDataSource(createDataSourceMap(), shardingRuleConfig,properties); } } 

因爲採用類配置類因此須要屏蔽原來application.properties文件中spring.shardingsphere開頭的配置信息。還須要在SpringBoot啓動類中屏蔽使用spring.shardingsphere配置項的類 :

@SpringBootApplication(exclude = {SpringBootConfiguration.class}) public class ShardingJdbcSimpleDemoBootstrap {....} 

Spring命名空間配置 此方式使用xml方式配置,不推薦使用。

<?xml version="1.0" encoding="UTF‐8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sharding="http://shardingsphere.apache.org/schema/shardingsphere/sharding" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring‐beans.xsd http://shardingsphere.apache.org/schema/shardingsphere/sharding http://shardingsphere.apache.org/schema/shardingsphere/sharding/sharding.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring‐context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring‐tx.xsd"> <context:annotation‐config /> <!‐‐定義多個數據源‐‐> <bean id="m1" class="com.alibaba.druid.pool.DruidDataSource" destroy‐method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/order_db_1?useUnicode=true" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!‐‐定義分庫策略‐‐> <sharding:inline‐strategy id="tableShardingStrategy" sharding‐column="order_id" algorithm‐ expression="t_order_$‐>{order_id % 2 + 1}" /> <!‐‐定義主鍵生成策略‐‐> <sharding:key‐generator id="orderKeyGenerator" type="SNOWFLAKE" column="order_id" /> <!‐‐定義sharding‐Jdbc數據源‐‐> <sharding:data‐source id="shardingDataSource"> <sharding:sharding‐rule data‐source‐names="m1"> <sharding:table‐rules> <sharding:table‐rule logic‐table="t_order" table‐strategy‐ ref="tableShardingStrategy" key‐generator‐ref="orderKeyGenerator" /> </sharding:table‐rules> </sharding:sharding‐rule> </sharding:data‐source> </beans>
相關文章
相關標籤/搜索