SpringBoot 整合 Sharding

Stella981
• 阅读 639

1、POM文件

    <properties>
        <java.version>1.8</java.version>
        <mysql.version>8.0.11</mysql.version>
        <mybatis-plus.version>3.0.7</mybatis-plus.version>
        <sharding-jdbc.version>4.1.1</sharding-jdbc.version>
    </properties>
 
    <dependencies>
        <!-- 解决 swagger 依赖的 guava 包冲突的错误问题 -->
        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1-jre</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-core -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-core</artifactId>
            <version>${sharding-jdbc.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-boot-starter -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
            <version>${sharding-jdbc.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-namespace -->
        <dependency>
            <groupId>org.apache.shardingsphere</groupId>
            <artifactId>sharding-jdbc-spring-namespace</artifactId>
            <version>${sharding-jdbc.version}</version>
        </dependency>
    </dependencies>

2、配置 application.properties

# web port
server.port=8080
server.http2.enabled=true

spring.main.lazy-initialization=false

# undertow configuration
server.undertow.threads.io=16
server.undertow.threads.worker=256
server.undertow.buffer-size=1024
server.undertow.direct-buffers=true

kailo.swagger.title=xxx
kailo.swagger.description=xxxxx
kailo.swagger.version=1.0.0

# mybatis-plus configuration
mybatis-plus.global-config.banner=false
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.field-strategy=not_empty
mybatis-plus.global-config.db-config.table-underline=true
mybatis-plus.global-config.db-config.db-type=h2
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0


# 读写分离
spring.shardingsphere.datasource.names=master,slave0

# Hikari 用 jdbc-url
spring.shardingsphere.datasource.master.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.master.jdbc-url=jdbc:mysql://xxxxxxxx:3308/shardingjdbc?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.master.username=base_sa
spring.shardingsphere.datasource.master.password=base_sa

spring.shardingsphere.datasource.slave0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.slave0.driver-class-name=com.mysql.cj.jdbc.Driver
spring.shardingsphere.datasource.slave0.jdbc-url=jdbc:mysql://xxxxxxxx:3309/shardingjdbc?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8
spring.shardingsphere.datasource.slave0.username=base_sa
spring.shardingsphere.datasource.slave0.password=base_sa

spring.shardingsphere.masterslave.load-balance-algorithm-type=round_robin
spring.shardingsphere.masterslave.name=ms
spring.shardingsphere.masterslave.master-data-source-name=master
spring.shardingsphere.masterslave.slave-data-source-names=slave0

spring.shardingsphere.props.sql.show=true

3、编写测试代码

@ApiModel(value = "用户实体")
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("t_base_user")
public class User {

    @ApiModelProperty(value = "主键")
    @TableId(value = "id", type = IdType.NONE)
    private Long id;
    @ApiModelProperty(value = "姓名")
    private String userName;
    @ApiModelProperty(value = "创建时间")
    private Date createTime;
}

@Mapper
public interface UserMapper extends BaseMapper<User> {
}


<?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.test.shardingshperejdbc.mapper.UserMapper">

</mapper>

public interface UserService extends IService<User> {
}

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}


@Api(value = "用户管理")
@Log4j2
@RestController
@AllArgsConstructor
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @ApiOperation(value = "保存或更新用户", notes = "userName是必输入项")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "用户主键", dataTypeClass = Long.class, required = false),
            @ApiImplicitParam(name = "userName", value = "用户姓名", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/saveOrUpdate")
    public ResponseEntity<Result<User>> saveOrUpdate(
            @RequestParam(required = false) Long id,
            @RequestParam String userName
    ) {
        User user = new User(id, userName, new Date());
        userService.saveOrUpdate(user);
        return ResultUtils.ok(user);
    }

    @ApiOperation(value = "查询所有用户", notes = "")
    @GetMapping("/queryAll")
    public ResponseEntity<Result<List<User>>> queryAll() {
        List<User> userList = userService.list();
        return ResultUtils.ok(userList, "查询成功");
    }
}

4、启动类

@SpringBootApplication
public class ShardingShpereJdbcApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShardingShpereJdbcApplication.class, args);
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Easter79 Easter79
3年前
springboot入门之简单demo
项目构建  我们采用maven构建SpringBoot工程,首先创建一个maven工程,对应的pom文件如下:<properties<java.version1.8</java.version</properties<!集成springboot的父依赖
Souleigh ✨ Souleigh ✨
3年前
前端性能优化 - 雅虎军规
无论是在工作中,还是在面试中,web前端性能的优化都是很重要的,那么我们进行优化需要从哪些方面入手呢?可以遵循雅虎的前端优化35条军规,这样对于优化有一个比较清晰的方向.35条军规1.尽量减少HTTP请求个数——须权衡2.使用CDN(内容分发网络)3.为文件头指定Expires或CacheControl,使内容具有缓存性。4.避免空的
Stella981 Stella981
3年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Stella981 Stella981
3年前
SpringBoot集成mybatis以及自动化测试代码实现
Mybatis和logback的应用配置1、在module的pom.xml文件中,加载springboot和swagger、lombok、fastjson、mysql、mybatis包2、在resources中添加配置:配置文件有两种,一种是properties,另一种是yaml,这里使用yamlyaml配
Wesley13 Wesley13
3年前
Java 读取Properties文件时应注意的路径问题
1\.使用Class的getResourceAsStream()方法读取Properties文件(资源文件)的路径问题:      InputStreaminthis.getClass().getResourceAsStream("资源Name");    注意:    (1)这种方式要求Properties资源文件必须与当
Easter79 Easter79
3年前
SpringBoot集成mybatis以及自动化测试代码实现
Mybatis和logback的应用配置1、在module的pom.xml文件中,加载springboot和swagger、lombok、fastjson、mysql、mybatis包2、在resources中添加配置:配置文件有两种,一种是properties,另一种是yaml,这里使用yamlyaml配
Stella981 Stella981
3年前
SpringBoot 项目的 Maven 多环境打包配置
1\.在pom.xml文件中配置<profiles<profile<iddev</id<activation<activeByDefaulttrue</activeByDefault</activation<properties