ShardingSphere-JDBC入门

Posted G_whang

tags:

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

shardingsphere-jdbc
上节使用ShardingSphere-JDBC 实现了分表,本节实现分库
首先创建两个数据库
order1,order2
然后每个库里面都新增一张t_address 表

CREATE TABLE `t_address` (
  `id` bigint NOT NULL,
  `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 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-generator02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shatding-springboot-mybatis-generator02</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
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.shatdingspringbootmybatisgenerator02.entity


###数据源名称,多数据源以逗号分隔
sharding:
  jdbc:
    datasource:
      names: ds0,ds1
      # 数据源ds0
      ds0:
        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
      # 数据源ds1
      ds1:
        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:
      sharding:
        props:
          sql.show: true
        tables:
          t_user:  #t_user表
            key-generator-column-name: id  #主键
            actual-data-nodes: ds${0..1}.t_user${0..1}    #数据节点,均匀分布
            database-strategy:   #分库策略
              inline: #行表达式
                sharding-column: city_id        #列名称,多个列以逗号分隔
                algorithm-expression: ds${city_id % 2}    #按模运算分配
            table-strategy:  #分表策略
              inline: #行表达式
                sharding-column: sex
                algorithm-expression: t_user${sex % 2}
          t_address:
            key-generator-column-name: id
            actual-data-nodes: ds${0..1}.t_address
            database-strategy:
              inline:
                sharding-column: lit
                algorithm-expression: ds${lit % 2}

controller

import com.example.shatdingspringbootmybatisgenerator02.entity.Address;
import com.example.shatdingspringbootmybatisgenerator02.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.shatdingspringbootmybatisgenerator02.entity.Address;
import com.example.shatdingspringbootmybatisgenerator02.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;
    }

}

实体类

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;

}

mapper

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

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

启动项目
然后访问:http://localhost:8080/address/save
查看数据库表 order1
在这里插入图片描述
查看数据库表 order2
在这里插入图片描述

访问order1的数据
在这里插入图片描述
访问order2的数据
在这里插入图片描述
后台同样打印了2条SQL查询,这次不同的是使用的是不同的库
在这里插入图片描述

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

ShardingSphere-JDBC入门

利用ShardingSphere-JDBC实现分库分表

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

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

ShardingSphere-JDBC篇

ShardingSphere-JDBC 关键字问题