1.创建两个库,每个库创建两个分表t_order_1,t_order_2

DROP TABLE IF EXISTS `t_order_1`;
CREATE TABLE `t_order_1` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`amount` int(255) NOT NULL,
`name` varchar(10) NOT NULL,
`user_id` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

  

2.引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath />
</parent> <groupId>org.example</groupId>
<artifactId>spring-shardingjdbc</artifactId>
<version>1.0-SNAPSHOT</version> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.0.0-RC2</version>
</dependency> </dependencies> </project>

  

3.创建sharding-jdbc的配置文件sharding-jdbc.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:sharding="http://shardingsphere.apache.org/schema/shardingsphere/sharding"
xmlns:master-slave="http://shardingsphere.apache.org/schema/shardingsphere/masterslave"
xmlns:bean="http://www.springframework.org/schema/util"
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://shardingsphere.apache.org/schema/shardingsphere/masterslave
http://shardingsphere.apache.org/schema/shardingsphere/masterslave/master-slave.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 http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd"> <bean id="ds0" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="username" value="root" />
<property name="password" value="root123456" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/sharding?serverTimezone=Asia/Shanghai&useSSL=false"/>
</bean>
<bean id="ds1" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="username" value="root" />
<property name="password" value="root123456" />
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/shard?serverTimezone=Asia/Shanghai&useSSL=false"/>
</bean> <sharding:data-source id="sharding-data-source">
<sharding:sharding-rule data-source-names="ds0,ds1">
<sharding:table-rules>
<sharding:table-rule logic-table="t_order" actual-data-nodes="ds$->{0..1}.t_order_$->{1..2}"
database-strategy-ref="databaseStrategy" table-strategy-ref="tableStrategy"
/>
<!-- 如果多个表需要分库,继续在此配置 -->
</sharding:table-rules>
</sharding:sharding-rule>
</sharding:data-source> <sharding:inline-strategy id="databaseStrategy" sharding-column="user_id"
algorithm-expression="ds$->{user_id%2}"/>
<sharding:inline-strategy id="tableStrategy" sharding-column="id"
algorithm-expression="t_order_$->{id%2+1}"/> <bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="sharding-data-source"/>
</bean> </beans>

 

4.编写代码及测试类

package com.sharding.pojo.vo;

public class Order {

    private int id;
private int amount;
private String name;
private int userId; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public int getAmount() {
return amount;
} public void setAmount(int amount) {
this.amount = amount;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getUserId() {
return userId;
} public void setUserId(int userId) {
this.userId = userId;
} @Override
public String toString() {
return "Order{" +
"id=" + id +
", amount=" + amount +
", name='" + name + '\'' +
", userId=" + userId +
'}';
}
}
package com.sharding.mapper;

import com.sharding.pojo.vo.Order;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import java.util.List; public interface OrderMapper { @Insert("insert into t_order values(#{item.id},#{item.amount},#{item.name},#{item.userId})")
public void insert(@Param("item") Order order); @Select("select " +
" id,amount,name,user_id as 'userId' from t_order where name=#{name}")
public List<Order> getOrderByName(String name);
}
package com.sharding;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource; @SpringBootApplication
@ImportResource("classpath*:sharding-jdbc.xml")
@MapperScan("com.sharding.mapper")
public class ShardingTest { public static void main(String[] args) {
SpringApplication.run(ShardingTest.class);
}
}
package com.sharding.test;

import com.sharding.mapper.OrderMapper;
import com.sharding.pojo.vo.Order;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class AppTest { @Autowired
private OrderMapper orderMapper; @Test
public void testInsert(){ Order order = new Order();
order.setId(10);
order.setUserId(20);
order.setAmount(200);
order.setName("Test");
orderMapper.insert(order);
} @Test
public void testQuery(){
List<Order> test = orderMapper.getOrderByName("Test");
System.out.println("查询结果:" + test);
}
}

  

spring整合sharding-jdbc实现分库分表的更多相关文章

  1. Sharding Sphere的分库分表

    什么是 ShardingSphere? 1.一套开源的分布式数据库中间件解决方案 2.有三个产品:Sharding-JDBC 和 Sharding-Proxy 3.定位为关系型数据库中间件,合理在分布 ...

  2. Spring Boot集成sharding-jdbc实现分库分表

    一.水平分割 1.水平分库 1).概念:以字段为依据,按照一定策略,将一个库中的数据拆分到多个库中.2).结果每个库的结构都一样:数据都不一样:所有库的并集是全量数据: 2.水平分表 1).概念以字段 ...

  3. 分库分表后跨分片查询与Elastic Search

    携程酒店订单Elastic Search实战:http://www.lvesu.com/blog/main/cms-610.html 为什么分库分表后不建议跨分片查询:https://www.jian ...

  4. 【大数据和云计算技术社区】分库分表技术演进&最佳实践笔记

    1.需求背景 移动互联网时代,海量的用户每天产生海量的数量,这些海量数据远不是一张表能Hold住的.比如 用户表:支付宝8亿,微信10亿.CITIC对公140万,对私8700万. 订单表:美团每天几千 ...

  5. java 取模运算% 实则取余 简述 例子 应用在数据库分库分表

    java 取模运算%  实则取余 简述 例子 应用在数据库分库分表 取模运算 求模运算与求余运算不同.“模”是“Mod”的音译,模运算多应用于程序编写中. Mod的含义为求余.模运算在数论和程序设计中 ...

  6. 分库分表技术演进&最佳实践

    每个优秀的程序员和架构师都应该掌握分库分表,这是我的观点. 移动互联网时代,海量的用户每天产生海量的数量,比如: 用户表 订单表 交易流水表 以支付宝用户为例,8亿:微信用户更是10亿.订单表更夸张, ...

  7. Sharding JDBC整合SpringBoot 2.x 和 MyBatis Plus 进行分库分表

    Sharding JDBC整合SpringBoot 2.x 和 MyBatis Plus 进行分库分表 交易所流水表的单表数据量已经过亿,选用Sharding-JDBC进行分库分表.MyBatis-P ...

  8. Sharding-JDBC基本使用,整合Springboot实现分库分表,读写分离

    结合上一篇docker部署的mysql主从, 本篇主要讲解SpringBoot项目结合Sharding-JDBC如何实现分库分表.读写分离. 一.Sharding-JDBC介绍 1.这里引用官网上的介 ...

  9. 转数据库分库分表(sharding)系列(二) 全局主键生成策略

    本文将主要介绍一些常见的全局主键生成策略,然后重点介绍flickr使用的一种非常优秀的全局主键生成方案.关于分库分表(sharding)的拆分策略和实施细则,请参考该系列的前一篇文章:数据库分库分表( ...

  10. 数据库分库分表(sharding)系列【转】

    原文地址:http://www.uml.org.cn/sjjm/201211212.asp数据库分库分表(sharding)系列 目录; (一) 拆分实施策略和示例演示 (二) 全局主键生成策略 (三 ...

随机推荐

  1. 如何修改Docker的默认网段?

    背景 公司的服务器全部都是购买的阿里云ECS主机,默认内网网段为172.16.0.0/12,测试服上的服务基本都是使用Docker部署的. 之前的同事在该机器上安装的Docker全部都是默认配置,网段 ...

  2. 生僻的mysql

    1.show table status like 'user' 2.alter table mytableEngine=InnoDB 需要执行很长时间,mysql会按行将数据从原表复制到一张新的表中, ...

  3. 浅谈Abp vNext的模块化设计

    abp的模块化给我留下深刻的印象,模块化不是什么新概念,大家都习以为常,但是为什么要模块化,模块化的意义或者说目的是什么?也许我们思考得并不深入.难得的是abp不仅完美的阐述了模块化概念,而且把模块化 ...

  4. 软件工程与UML 第一次个人作业

    这个作业属于哪个课程 https://edu.cnblogs.com/campus/fzzcxy/2018SE1/ 这个作业要求在哪里 https://edu.cnblogs.com/campus/f ...

  5. JZOJ8月10日提高组反思

    JZOJ8月10日提高组反思 T1 没想到怎么打 就去打暴力了 本来想拿个30不错了 结果\(AC\)了 话说回来,数据也挺小的 T2 不AC便爆0 就一个数据点 给不给打暴力的人活了 正解是状压DP ...

  6. 第8.1节 Python类的构造方法__init__深入剖析:语法释义

    一.    引言 凡是面向对象设计的语言,在类实例化时都有构造方法,很多语言的构造方法名与类名一致,Python中类的构造方法比较特殊,必须是__init__特殊方法. 二.    语法释义 1.   ...

  7. Python字符串学习相关问题

    Python中format_map与format字符串格式化的区别 Python中使用f字符串进行字符串格式化的方法 Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容有何不同? ...

  8. 建立SQL Server用户登录

    第一步:右击服务器名,点击"属性",选择"安全性",选中"Sql server和Windows身份验证模式". 第二步:鼠标右键点击安全性中 ...

  9. python xlsxwriter创建excel 之('Exception caught in workbook destructor. Explicit close() may be required for workbook.',)

    python2.7使用xlsxwriter创建excel ,不关闭xlsxwriter对象,会报错: Exception Exception: Exception('Exception caught ...

  10. ACM训练赛:第20次

    这次的题思维都很强,等之后的考试结束会集中精力重新训练一些思维题. A - A simple question CodeForces - 520B 思路: 直接看的话,很容易发现如果 \(n > ...