我先说一下我的环境,项目使用了Maven和MyBatis-Plus,数据库是MySQL 8,至于增删改查的代码,我就不往上贴了,请读者自行准备。
首先,pom.xml需要增加shardingsphere依赖,如下:
<!--shardingsphere start-->
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0-alpha</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core-spring-namespace</artifactId>
<version>5.0.0-alpha</version>
</dependency>
<!--shardingsphere end-->
接着,配置application.yml或者bootstrap.yml,我使用的是application.yml,如下:
server:
port: 4111
spring:
shardingsphere:
props:
sql-show: true
datasource:
common:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
names: ds0,ds1
ds0:
url: jdbc:mysql://127.0.0.1:3306/sharding_0?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false
username: root
password: root
ds1:
url: jdbc:mysql://127.0.0.1:3306/sharding_1?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false
username: root
password: root
rules:
sharding:
key-generators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
tables:
user_info:
actual-data-nodes: ds$->{0..1}.user_info
database-strategy:
standard:
sharding-column: age
sharding-algorithm-name: database-inline
sharding-algorithms:
database-inline:
type: INLINE
props:
algorithm-expression: ds$->{age % 2}
其中,ds0和ds1代表着两个库,分别是sharding_0和sharding_1。在这里可以理解为,将sharding_0和sharding_1的连接信息,取了一个别名,分别是ds0和ds1。
根据末尾的配置项可以看出,我是以年龄进行分库依据的。我对ds$->{age % 2}这行代码的理解就是,$符号就是一个占位符,ds后面的内容是什么,取决于age字段的值。比如年龄为18、20、22的,放在ds0数据源,也就是sharding_0库。而19、21、23则放在sharding_1库。
数据库如下两张图:
贴一下entity和controller的代码,供参考:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "用户信息")
public class UserInfo extends Model<UserInfo> {
@ApiModelProperty(value = "ID", required=false)
@TableId(value = "id", type = IdType.ASSIGN_UUID)
private String id;
@ApiModelProperty(value = "用户名", required=true)
private String username;
@ApiModelProperty(value = "年龄", required = true)
private int age;
}
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.core.util.R; # 我自己的类
import com.demo.entity.UserInfo; # 我自己的类
import com.demo.service.UserInfoService; # 我自己的类
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@AllArgsConstructor
@Api(tags = "演示用-用户管理")
@RequestMapping("/userinfo")
public class UserInfoController {
private final UserInfoService userInfoService;
@ApiOperation(value = "测试访问", notes = "测试一下此服务是否能正常访问")
@ApiImplicitParam(name = "param", value = "传入什么,就返回什么", required = true)
@GetMapping("/testconn")
public R testConn(String param){
return R.ok(param);
}
@ApiOperation(value = "添加用户", notes = "向数据库添加一条数据")
@PostMapping("/add")
public R saveUser(@RequestBody UserInfo userInfo){
userInfoService.save(userInfo);
return R.ok("添加成功");
}
@ApiOperation(value = "查询所有", notes = "返回所有结果")
@GetMapping("/all")
public R getUsers(Page page){
return R.ok(userInfoService.selectPage(page));
}
@ApiOperation(value = "根据条件查询", notes = "根据条件返回所有结果")
@GetMapping("/getByConditions")
public R getUses(Page page, UserInfo userInfo){
return R.ok(userInfoService.selectPage(page, userInfo));
}
}
如果项目启动失败,报“Error creating bean with name 'userInfoController' defined in file”异常的话,可以在启动类加上“@EnableAutoConfiguration(exclude={DruidDataSourceAutoConfigure.class})”
最后贴一下测试结果:
好啦,技术分享不讲版权,欢迎转载,让更多的人少走弯路。就这样吧,我是来北京天码科技的卢泽!