代码库
2024年12月2日大约 2 分钟
代码库
记录下项目中使用的公共代码
统一全局返回实体对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
private Boolean success;
private String errorMsg;
private Object data;
private Long total;
public static Result ok(){
return new Result(true, null, null, null);
}
public static Result ok(Object data){
return new Result(true, null, data, null);
}
public static Result ok(List<?> data, Long total){
return new Result(true, null, data, total);
}
public static Result fail(String errorMsg){
return new Result(false, errorMsg, null, null);
}
}
分库分表shardingJDBC配置
# application.yaml
spring:
datasource:
# ShardingSphere 对 Driver 自定义,实现分库分表等隐藏逻辑
driver-class-name: org.apache.shardingsphere.driver.ShardingSphereDriver
# ShardingSphere 配置文件路径
url: jdbc:shardingsphere:classpath:shardingsphere-config.
# sharding-config.yaml
# 数据源集合
# 数据源集合
dataSources:
ds_0:
dataSourceClassName: com.zaxxer.hikari.HikariDataSource
driverClassName: com.mysql.cj.jdbc.Driver
jdbcUrl: jdbc:mysql://192.168.228.132:3306/link?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true&allowMultiQueries=true&serverTimezone=Asia/Shanghai
username: root
password: 123456
rules:
- !SHARDING
tables:
t_user:
# 真实数据节点,比如数据库源以及数据库在数据库中真实存在的
actualDataNodes: ds_0.t_user_${0..15}
# 分表策略
tableStrategy:
# 用于单分片键的标准分片场景
standard:
# 分片键
shardingColumn: username
# 分片算法,对应 rules[0].shardingAlgorithms
shardingAlgorithmName: user_table_hash_mod
# 分片算法
shardingAlgorithms:
# 数据表分片算法
user_table_hash_mod:
# 根据分片键 Hash 分片
type: HASH_MOD
# 分片数量
props:
sharding-count: 16
# 数据加密存储规则
- !ENCRYPT
# 需要加密的表集合
tables:
# 用户表
t_user:
# 用户表中哪些字段需要进行加密
columns:
# 手机号字段,逻辑字段,不一定是在数据库中真实存在
phone:
# 手机号字段存储的密文字段,这个是数据库中真实存在的字段
cipherColumn: phone
# 身份证字段加密算法
encryptorName: common_encryptor
mail:
cipherColumn: mail
encryptorName: common_encryptor
# 是否按照密文字段查询
queryWithCipherColumn: true
# 加密算法
encryptors:
# 自定义加密算法名称
common_encryptor:
# 加密算法类型
type: AES
props:
# AES 加密密钥
aes-key-value: d6oadClrrb9A3GWo
mps分页查询
// 首先ShortLinkRespDTO要继承Page<...DO>
//写配置
public class DataBaseConfiguration {
// 分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
//具体逻辑
@Override
public IPage<ShortLinkRespDTO> pageShortLink(ShortLinkPageReqDTO requestParam) {
LambdaQueryWrapper<LinkDO> queryWrapper = new LambdaQueryWrapper<LinkDO>()
.eq(LinkDO::getGid, requestParam.getGid())
.eq(LinkDO::getDelFlag, 0)
.eq(LinkDO::getEnableStatus, 0);
IPage<LinkDO> page = baseMapper.selectPage(requestParam,queryWrapper);
return page.convert(each -> BeanUtil.toBean(each, ShortLinkRespDTO.class));
}