sharding-jdbc读写分离实战

news2024/9/22 23:38:31

一、读写分离介绍

Sharding-JDBC读写分离则是根据SQL语义的分析,将读操作和写操作分别路由至主库与从库。它提供透明化读写分离,让使用方尽量像使用一个数据库一样使用主从数据库集群。

 为了实现Sharding-JDBC的读写分离,首先,要进行mysql的主从同步配置。mysql的主从同步配置请参考mysql主从同步搭建

在主数据库的course_db1库中建立如下表:

CREATE TABLE `products` (
  `pid` bigint(32) NOT NULL AUTO_INCREMENT,
  `pname` varchar(50) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `flag` varchar(2) DEFAULT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

由于已经搭建好主从同步,那么会在从库中同步创建好products表。

二、创建springboot项目

 环境说明:SpringBoot2.3.7+ MyBatisPlus + ShardingSphere-JDBC 5.1 + Hikari+ MySQL 5.7

1) 创建项目

项目名称: sharding-jdbc-write-read

2)引入以下POM文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>top.hdsw</groupId>
<artifactId>sharding-jdbc-write-read</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sharding-jdbc-write-read</name>
<description>sharding-jdbc-write-read</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.1.1</version>
</dependency>

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.mashibing.shardingjdbc.ShardingjdbcWriteReadApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>

 3)、创建实体类

@TableName("products")
@Data
public class Products {

    @TableId(value = "pid",type = IdType.AUTO)
    private Long pid;

    private String pname;

    private int  price;

    private String flag;

}

4) 创建Mapper

@Mapper
public interface ProductsMapper extends BaseMapper<Products> {
}

 三、配置读写分离

https://shardingsphere.apache.org/document/current/cn/user-manual/shardingsphere-jdbc/spring-boot-starter/rules/readwrite-splitting/

 application.properties

# 应用名称
spring.application.name=shardingjdbc-write-read

# 打印SQl
spring.shardingsphere.props.sql-show=true

# 定义读写分离的数据源
spring.shardingsphere.datasource.names = master,slave

#数据源1
spring.shardingsphere.datasource.master.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.master.jdbc-url=jdbc:mysql://192.168.19.3:3306/course_db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.master.username=root
spring.shardingsphere.datasource.master.password=MyNewPass4!

#数据源2
spring.shardingsphere.datasource.slave.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.slave.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.slave.jdbc-url=jdbc:mysql://192.168.19.4:3306/course_db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
spring.shardingsphere.datasource.slave.username=root
spring.shardingsphere.datasource.slave.password=MyNewPass4!
#读写分离 主从关系
# 读写分离类型,如: Static,Dynamic, ms1 包含了 m1 和 s1
spring.shardingsphere.rules.readwrite-splitting.data-sources.ms1.type=Static

# 写数据源名称
spring.shardingsphere.rules.readwrite-splitting.data-sources.ms1.props.write-data-source-name=master

# 读数据源名称,多个从数据源用逗号分隔
spring.shardingsphere.rules.readwrite-splitting.data-sources.ms1.props.read-data-source-names=slave
 

四、读写分离测试

写操作:

@Test
public void testInsert(){

Products products = new Products();
products.setPname("电视机");
products.setPrice(2000);
products.setFlag("1");

productsMapper.insert(products);
}

 

可以看到,执行插入的是主数据库

读操作:

@Test
public void testQuery(){
QueryWrapper<Products> wrapper = new QueryWrapper<>();
wrapper.eq("pname","洗碗机");
List<Products> list = productsMapper.selectList(wrapper);
list.forEach(System.out::println);
}

为了保证主从库间的事务一致性,避免跨服务的分布式事务,ShardingSphere-JDBC的主从模型中,事务中的数据读写均用主库。

  • 不添加@Transactional:insert对主库操作,select对从库操作

  • 添加@Transactional:则insert和select均对主库操作

添加Transactional

@Transactional
@Test
public void testTrans(){

Products products = new Products();
products.setPname("洗碗机");
products.setPrice(1000);
products.setFlag("1");
productsMapper.insert(products);

QueryWrapper<Products> wrapper = new QueryWrapper<>();
wrapper.eq("pname","洗碗机");
List<Products> list = productsMapper.selectList(wrapper);
list.forEach(System.out::println);
}

将testTrans方法的注解注释掉,进行非事务测试

 本文中示例代码见:sharding-jdbc-example/sharding-jdbc-write-read at master · zhang1github2test/sharding-jdbc-example · GitHub

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/510986.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Leetcode2404. 出现最频繁的偶数元素

Every day a Leetcode 题目来源&#xff1a;2404. 出现最频繁的偶数元素 解法1&#xff1a;哈希 我们构建一个这样的哈希表 unordered_map<int, int> umap&#xff1a; key&#xff1a;偶数数组元素 nums[i]value&#xff1a;nums[i]的出现次数 count 我们遍历一次数…

算法之路--快速排序算法

由于冒泡算法算法之路--冒泡算法&#xff08;算法之路--冒泡算法&#xff09;每轮都要进行从头到落位之前的每个元素的比较&#xff0c;在执行效率上需要提升&#xff0c;快速排序算法就是对冒泡算法的一种效率上的提升。 算法思路 快速排序是基于冒泡的改进&#xff0c;所以基…

力扣回溯算法专题(二)- 切割 子集问题 131.分割回文串、93. 复原IP地址、78. 子集、90. 子集Ⅱ、491.递增子序列 思路 C++实现 总结

文章目录 切割问题子集问题回溯法模板与伪代码131. 分割回文串三要素及思路回文字符串判断代码 93. 复原IP地址三要素及思路验证子串是否合法代码 78. 子集三要素及思路代码 90. 子集Ⅱ三要素及思路三种去重方式代码 491.递增子序列三要素及思路去重方式及去重优化代码 总结1. …

Django框架004:orm对mysql的增删改查

大家好&#xff0c;我是csdn的博主&#xff1a;lqj_本人 这是我的个人博客主页&#xff1a; lqj_本人的博客_CSDN博客-微信小程序,前端,python领域博主lqj_本人擅长微信小程序,前端,python,等方面的知识https://blog.csdn.net/lbcyllqj?spm1011.2415.3001.5343哔哩哔哩欢迎关注…

TypeScript 配置简述

TypeScript 配置简述 初始化项目的过程为&#xff1a; 新建一个项目 这里使用 yarn init -y 去创建一个 node 项目&#xff0c;随后使用 yarn add typescript 下载 TS 的依赖 新建一个 ts 文件 console.log(test);随意 log 一点东西进行测试 使用 tsc 编译 ts 文件 ❯ yarn …

为什么国外资深的软件测试多是手动测试,但在国内,都推崇自动化测试?

将自动化测试当成很了不起的资本&#xff0c;源于国内对Coding的崇拜 譬如一个Dev跟一个QA放在一起&#xff0c;大家的第一直观印象就是——前者的技术能力比较强。 实际上&#xff0c;这个问题分两面看&#xff1a; 自动化测试能力是不是资本&#xff1f; 当然是。 测试自动…

redis(7)

全局ID生成器: 全局ID生成器&#xff0c;是一种在分布式系统下用来生成全局唯一ID的工具&#xff0c;一般要满足以下特性 唯一性高可用(随时访问随时生成)递增性安全性(不能具有规律性)高性能(生成ID的速度快) 为了增加ID的安全性&#xff0c;我们不会使用redis自增的数值&am…

yolov4

1 V4版本概述 集各种优秀方案于一身&#xff0c;嫁接了众多主流的目标识别方面的情况。 V4 贡献 3. 数据增强策略分析 BOF Bag of freebies(BOF) Mosiac 数据增强 Mixup 比如将狗和猫的两张图片混合&#xff0c;一半猫&#xff0c;一半狗。 label 也变成 Dog 0.5 , Cat 0…

JAVA中PO、VO、BO、POJO、DAO、DTO、TO的理解

目录 1.阿里规范 1.1.Service/DAO 层方法命名规约 1.2.领域模型命名规约 1.3.命名风格 2.简单类&#xff1a;包括 DO/DTO/BO/VO 等 3.与MVC三层架构的关系 4.总结 4.1.为什么要分这些对象 4.2.什么时候需要定义这么多O 4.3.实体对象之间如何转换&#xff1f; 参考资…

Ground-aware Monocular 3D Object Detection for Autonomous Driving论文

1 摘要 摘要&#xff1a;使用单个RGB相机估计环境中物体的3D位置和方向是低成本城市自主驾驶和移动机器人的一项至关重要的挑战性任务。大多数现有算法基于二维-三维对应中的几何约束&#xff0c;这源于一般的6D目标姿态估计。我们首先确定地平面如何在驾驶场景的深度推理中提…

RT-Thread 5.0.1 qemu-virt64-aarch64 解决编译问题

前言 最近在最新的 RT-Thread 上搭建 bsp qemu-virt64-aarch64 的编译环境&#xff0c;发现较新的 gcc 交叉编译器编译失败了。 经过尝试较旧版本的 gcc 交叉编译工具链&#xff0c;终于编译通过了 下载 gcc 交叉编译工具链&#xff0c;这里推荐使用 arm 官方的 gcc 下载地址…

Apache Shiro 1.2.4反序列化漏洞(Shiro-550)--Shiro rememberMe反序列化漏洞(CVE-2016-4437)

前言 Apache Shiro是一款开源安全框架&#xff0c;提供身份验证、授权、密码学和会话管理。Shiro框架直观、易用&#xff0c;同时也能提供健壮的安全性。 Apache Shiro 1.2.4及以前版本中&#xff0c;加密的用户信息序列化后存储在名为remember-me的Cookie中。攻击者可以使用S…

sort、uniq、tr、cut命令的使用

sort、uniq、tr、cut命令的使用 一、sort二、uniq三、tr四、cut 一、sort sort是一个以行为单位对文件内容排序的工具&#xff0c;也可以根据不同的数据类型来排序&#xff0c;例如数据和字符的排序就不一样。比较原则是从首字符向后&#xff0c;依次按ASCII码进行比较&#x…

MySQL-索引(1)

本文主要梳理的内容 : 主键索引的基本概念InnoDB引擎中的索引策略索引的分类(各种索引讲解)索引的创建索引的底层数据结构 目录 主键 InnoDB主键生成策略 数据库自增主键可能遇到什么问题. 如何选择合适的分布式主键方案呢&#xff1f; 超键、候选键、主键、外键分别是什…

第一个Mapreduce程序-wordcount

一个Maprduce程序主要包括三部分&#xff1a;Mapper类、Reducer类、执行类。 Maven项目下所需依赖 <dependencies><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-client</artifactId><version>3.3.0</v…

前端011_标签模块_列表功能

标签模块_列表功能 1、需求分析2、Mock添加数据列表模拟接口3、Api调用接口4、列表模版5、分页查询实现1、需求分析 标签模块主要文章标签进行管理,类别和标签的关系是一对多,一个类别下面存在多个标签。 首先开发模块中的列表功能,包含数据列表、分页。 2、Mock添加数据…

golang基于FFmpeg实现视频H264编解码

文章目录 一、基本知识1.1 FFmpeg相关1.2 H.264相关1.3 YUV相关 二、H264编码原理2.1 帧类型分析2.2 帧内/帧间预测2.3 变换量化2.4 滤波2.5 熵编码 三、H264解码为YUV3.1 代码逻辑及使用API3.2 具体代码实现3.3 YUV文件播放 四、YUV编码为H2644.1 代码逻辑及使用API4.2 具体代…

Python基础入门编程代码练习(二)

一、求1~100之间不能被3整除的数之和 循环条件&#xff1a;i<100循环操作 实现代码如下&#xff1a; def sums():sum 0for num in range(1, 101):if num % 3 ! 0:sum numprint("1~100之间不能被3整除的数之和为&#xff1a;%s" % (sum))sums() print("1~…

测试 —— 基础概念、开发模型、测试模型、BUG的描述

目录 一、什么是软件测试&#xff1f; 1. 调试和测试的区别 2. 优秀的测试人员需要具备的哪些素质 二、基本名词的概念 1. 什么是需求&#xff1f; 2. 什么是BUG&#xff1f; 3. 什么是测试用例&#xff1f; 4. 软件的生命周期&#xff1f;软件测试的生命周期&#xff1…

实验六 触发器与存储过程

实验六 触发器与存储过程 目录 实验六 触发器与存储过程 1、SQL触发器&#xff1a;删除学生数据题目代码题解 2、SQL触发器&#xff1a;创建成绩表插入触发器题目代码题解 3、 SQL存储过程&#xff1a;查询订单题目代码题解 4、SQL存储过程&#xff1a;建立存储过程&#xff0c…