ShardingSphere-JDBC入门

Posted G_whang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ShardingSphere-JDBC入门相关的知识,希望对你有一定的参考价值。

ShardingSphere-JDBC
上节实现了ShardingSphere-JDBC的分库 本节实现ShardingSphere-JDBC的读写分离
因为读写分离需要配置mysql主从复制 本次就不详细讲解主从复制,以实现读写分离为主
在order1,order2中分别加入t_address_test表

CREATE TABLE `t_address_test` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `code` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '编码',
  `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '名称',
  `pid` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '0' COMMENT '父id',
  `type` int DEFAULT NULL COMMENT '1国家2省3市4县区',
  `lit` int DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;

代码如下:
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.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>shatding-springboot-mybatis-generator03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shatding-springboot-mybatis-generator03</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <sharding.jdbc.version>3.0.0</sharding.jdbc.version>
        <mybatis.version>1.3.0</mybatis.version>
        <druid.version>1.1.10</druid.version>
        <mysql.version>8.0.19</mysql.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <dependency>
            <groupId>io.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>${sharding.jdbc.version}</version>
        </dependency>

        <!-- 引入Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

配置文件如下:

server:
  port: 8080
spring:
  application:
    name: shatding-springboot-mybatis
  main:
    allow-bean-definition-overriding: true
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.shatdingspringbootmybatisgenerator03.entity

###数据源名称,多数据源以逗号分隔
sharding:
  jdbc:
    datasource:
      names: master,slave
      master:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/order1?useSSL=false&serverTimezone=UTC
        username: root
        password: root
      slave:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/order2?useSSL=false&serverTimezone=UTC
        username: root
        password: root
    config:
      masterslave:
        # 读写分离配置
        load-balance-algorithm-type: round_robin
        # 最终的数据源名称
        name: dataSource
        # 主库数据源名称
        master-data-source-name: master
        # 从库数据源名称列表,多个逗号分隔
        slave-data-source-names: slave
      props:
        sql:
          show: true

实体类如下:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Address {

    private Long id;
    private String code;
    private String name;
    private String pid;
    private Integer type;
    private Integer lit;

}

controller

import com.example.shatdingspringbootmybatisgenerator03.entity.Address;
import com.example.shatdingspringbootmybatisgenerator03.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @RequestMapping("/save")
    public String save(){
        for (int i = 0; i <10 ; i++) {
            Address address=new Address();
            address.setCode("code_"+i);
            address.setName("name_"+i);
            address.setPid(i+"");
            address.setType(0);
            address.setLit(i%2==0?1:2);
            addressService.save(address);
        }

        return "success";
    }

    @RequestMapping("/get")
    public Address get(Long id){
        Address address = this.addressService.get(id);
        return address;
    }

}

service

import com.example.shatdingspringbootmybatisgenerator03.entity.Address;
import com.example.shatdingspringbootmybatisgenerator03.mapper.AddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddressService {

    @Autowired
    private AddressMapper addressMapper;

    public void save(Address address){
        this.addressMapper.save(address);
    }

    public Address get(Long id){
        Address address = this.addressMapper.get(id);
        return address;
    }

}

mapper

import com.example.shatdingspringbootmybatisgenerator03.entity.Address;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface AddressMapper {

    /**
     * 保存
     */
    void save(Address address);

    /**
     * 查询
     * @param id
     * @return
     */
    Address get(Long id);

}

mapper.xml

<?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="com.example.shatdingspringbootmybatisgenerator03.mapper.AddressMapper">
    <insert id="save" parameterType="Address">
        INSERT INTO t_address_test(code,name,pid,type,lit)
        VALUES
        (
            #{code},#{name},#{pid},#{type},#{lit}
        )
    </insert>

    <select id="get" parameterType="long" resultType="Address">
        select * from t_address_test where id = #{id}
    </select>
</mapper>

访问http://localhost:8080/address/save
查看数据库
主库 order1 库中的t_address_test 已经插入了10条数据了
在这里插入图片描述
因为没有做主从,所以 order2 库中的t_address_test表没有1条数据
在这里插入图片描述
然后查询数据 访问:http://localhost:8080/address/get?id=31
在这里插入图片描述
什么也没访问到,此时主库中是有数据的,但是访问时却没访问到,说明读写分离已经成功
然后将从主库数据复制1条到从库
在这里插入图片描述
再访问
在这里插入图片描述

以上是关于ShardingSphere-JDBC入门的主要内容,如果未能解决你的问题,请参考以下文章

ShardingSphere-JDBC入门

利用ShardingSphere-JDBC实现分库分表

看完这一篇,ShardingSphere-jdbc 实战再也不怕了

看完这一篇,ShardingSphere-jdbc 实战再也不怕了

ShardingSphere-JDBC篇

ShardingSphere-JDBC 关键字问题