溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot中怎么利用Sharding-JDBC實(shí)現(xiàn)MySQL8讀寫分離

發(fā)布時(shí)間:2021-07-29 17:46:28 來源:億速云 閱讀:379 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)SpringBoot中怎么利用Sharding-JDBC實(shí)現(xiàn)MySQL8讀寫分離,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。


一.前言

這是一個(gè)基于SpringBoot整合Sharding-JDBC實(shí)現(xiàn)讀寫分離的極簡教程,筆者使用到的技術(shù)及版本如下:

  • SpringBoot 2.5.2

  • MyBatis-Plus 3.4.3

  • Sharding-JDBC 4.1.1

  • MySQL8集群(看筆者前一篇文章有部署教程)

二.項(xiàng)目目錄結(jié)構(gòu)

SpringBoot中怎么利用Sharding-JDBC實(shí)現(xiàn)MySQL8讀寫分離

三.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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>xyz.hcworld</groupId>
    <artifactId>sharding-jdbc-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sharding-jdbc-demo</name>
    <description>多數(shù)據(jù)源切換實(shí)例</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--   mybatis-plus依賴     -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <!--    mysql驅(qū)動(dòng)    -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--  sharding-jdbc(多數(shù)據(jù)源切換)     -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>4.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

四.配置文件(基于YAML)及SQL建表語句

spring:
  main:
    allow-bean-definition-overriding: true
  #顯示sql
  shardingsphere:
    props:
      sql:
        show: true
    masterslave:
      #配置主從名稱
      name: ms
      #置主庫master,負(fù)責(zé)數(shù)據(jù)的寫入
      master-data-source-name: ds1
      #配置從庫slave節(jié)點(diǎn)
      slave-data-source-names: ds2,ds3
      #配置slave節(jié)點(diǎn)的負(fù)載均衡均衡策略,采用輪詢機(jī)制,有兩種算法:round_robin(輪詢)和random(隨機(jī))
      load-balance-algorithm-type: round_robin
    sharding:
      #配置默認(rèn)數(shù)據(jù)源ds1 默認(rèn)數(shù)據(jù)源,主要用于寫
      default-data-source-name: ds1
    # 配置數(shù)據(jù)源
    datasource:
      names: ds1,ds2,ds3
      #master-ds1數(shù)據(jù)庫連接信息
      ds1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://192.168.2.142:3307/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
        maxPoolSize: 100
        minPoolSize: 5
      #slave-ds2數(shù)據(jù)庫連接信息
      ds2:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://192.168.2.142:3308/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
        maxPoolSize: 100
        minPoolSize: 5
      #slave-ds3數(shù)據(jù)庫連接信息
      ds3:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://192.168.2.142:3309/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai
        username: root
        password: 123456
        maxPoolSize: 100
        minPoolSize: 5
#mybatis-plus配置
mybatis-plus:
  type-aliases-package: xyz.hcworld.demo.model
  mapper-locations: classpath*:/mapper/**Mapper.xml
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(100) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `sex` int(11) DEFAULT NULL,
  `birthday` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

五.Mapper.xml文件及Mapper接口

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xyz.hcworld.demo.mapper.UserMapper">

    <update id="addUser">
        INSERT INTO t_user(nickname,PASSWORD,sex,birthday) VALUES(#{nickname},#{password},#{sex},#{birthday})
    </update>

    <select id="findUsers" resultType="xyz.hcworld.demo.model.User">
        SELECT
            id,
            nickname,
            PASSWORD,
            sex,
            birthday
        FROM t_user;
    </select>

</mapper>
package xyz.hcworld.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Component;
import xyz.hcworld.demo.model.User;

import java.util.List;

/**
 * @ClassName: UserMapper
 * @Author: 張紅塵
 * @Date: 2021-07-20
 * @Version: 1.0
 */
@Component
public interface UserMapper  extends BaseMapper<User> {


    void addUser(User user);


    List<User> findUsers();
}

六 .Controller及Mocel文件

package xyz.hcworld.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.hcworld.demo.mapper.UserMapper;
import xyz.hcworld.demo.model.User;

import java.security.SecureRandom;
import java.util.List;

/**
 * @ClassName: UserController
 * @Author: 張紅塵
 * @Date: 2021-07-20
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/save")
    public String addUser() {
        User user = new User();
        user.setNickname("zhangsan" + new SecureRandom().nextInt());
        user.setPassword("123456");
        user.setSex(1);
        user.setBirthday("1997-12-03");
        userMapper.addUser(user);
        return user.toString();
    }

    @GetMapping("/findUsers")
    public List<User> findUsers() {
        return userMapper.findUsers();
    }
}
package xyz.hcworld.demo.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @ClassName: User
 * @Author: 張紅塵
 * @Date: 2021-07-20
 * @Version: 1.0
 */
@Data
@TableName("t_user")
public class User {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String nickname;

    private String password;

    private Integer sex;

    private String birthday;
}

七.結(jié)果

從結(jié)果可以看出,寫入操作全部通過ds1數(shù)據(jù)庫(master)數(shù)據(jù)庫完成,而讀操作因?yàn)樵O(shè)置了輪詢的緣故,由ds2(slaver)、ds3(slaver2)數(shù)據(jù)庫完成。這樣就實(shí)現(xiàn)了基于一主二從的數(shù)據(jù)庫集群的讀寫分離操作。

SpringBoot中怎么利用Sharding-JDBC實(shí)現(xiàn)MySQL8讀寫分離

八.Sharding-JDBC不同版本上的配置

網(wǎng)上Sharding-JDBC的教程多為4.0.0.RC1版本,筆者使用的是最新的4.1.1所以
在該部分?jǐn)?shù)據(jù)庫地址在4.1.1為jdbc-url在4.0.0.RC1上需要改為url否則會(huì)啟動(dòng)失敗

jdbc-url: jdbc:mysql://XXXX/XXXX

關(guān)于SpringBoot中怎么利用Sharding-JDBC實(shí)現(xiàn)MySQL8讀寫分離就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI