spring整合sharding-jdbc实现分库分表
2024-10-18 19:38:33
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);
}
}
最新文章
- Js Map 实现
- javase基础复习攻略《三》
- leofs存储总结
- “NOT_IN”与“NULL”的邂逅
- linux 安装 easygui
- infoWindowRenderer之个人见解
- RecordWriter接口解析
- Delphi Idhttp Post提交 Aspx/Asp.net 时 500错误的解决办法。
- Android-xUtils框架介绍(四)
- SQL 中With as 的用法
- linux上 安装并 运行opencv
- 解决windows7搜索不了txt文本内容的问题
- Python3网络爬虫
- GCD之barrier
- Struts2【拦截器】就是这么简单
- 项目中常用的MySQL 优化
- 关于Sublime Text 3的几个问题总结
- python字符串面试题:找出一个字符串中第一个字母和最后一个字符是第一次重复,中间没有重复且最长的子串
- Docker Compose 一键部署Nginx代理Tomcat集群
- office2016如何激活
热门文章
- Free-Form Image Inpainting with Gated Convolution
- charles 常用功能(七)简易接口压力测试(repeat advance 功能)
- 通过Apache Hudi和Alluxio建设高性能数据湖
- Python中使用f字符串进行字符串格式化的方法
- 第11.16节 Python正则元字符“()”(小括号)与组(group)匹配模式
- 降本增效利器!趣头条Spark Remote Shuffle Service最佳实践
- kaggle——Bag of Words Meets Bags of Popcorn(IMDB电影评论情感分类实践)
- 题解-CmdOI2019 口头禅
- AcWing 309. 装饰围栏
- 算法——n皇后问题