• Mybatis-Plus官方分库分表神器,一个依赖轻松搞定!


    今天介绍一个 MyBatis - Plus 官方发布的神器:mybatis-mate 为 mp 企业级模块,支持分库分表,数据审计、数据敏感词过滤(AC 算法),字段加密,字典回写(数据绑定),数据权限,表结构自动生成 SQL 维护等,旨在更敏捷优雅处理数据。

     主要功能如下:

    • 字典绑定

    • 字段加密

    • 数据脱敏

    • 表结构动态维护

    • 数据审计记录

    • 数据范围(数据权限)

    • 数据库分库分表、动态据源、读写分离、数- - 据库健康检查自动切换。

    使用:

    | 依赖导入

    Spring Boot 引入自动依赖注解包:

    1. <dependency>
    2.   <groupId>com.baomidou</groupId>
    3.   <artifactId>mybatis-mate-starter</artifactId>
    4.   <version>1.0.8</version>
    5. </dependency>

    注解(实体分包使用):

    1. <dependency>
    2.   <groupId>com.baomidou</groupId>
    3.   <artifactId>mybatis-mate-annotation</artifactId>
    4.   <version>1.0.8</version>
    5. </dependency>

    | 字段数据绑定(字典回写)

    例如 user_sex 类型 sex 字典结果映射到 sexText 属性:

    1. @FieldDict(type = "user_sex", target = "sexText")
    2. private Integer sex;
    3. private String sexText;

    实现 IDataDict 接口提供字典数据源,注入到 Spring 容器即可。

    1. @Component
    2. public class DataDict implements IDataDict {
    3.     /**
    4.      * 从数据库或缓存中获取
    5.      */
    6.     private Map<StringStringSEX_MAP = new ConcurrentHashMap<StringString>() {{
    7.         put("0""女");
    8.         put("1""男");
    9.     }};
    10.     @Override
    11.     public String getNameByCode(FieldDict fieldDict, String code) {
    12.         System.err.println("字段类型:" + fieldDict.type() + ",编码:" + code);
    13.         return SEX_MAP.get(code);
    14.     }
    15. }

    | 字段加密

    属性 @FieldEncrypt 注解即可加密存储,会自动解密查询结果,支持全局配置加密密钥算法,及注解密钥算法,可以实现 IEncryptor 注入自定义算法。

    1. @FieldEncrypt(algorithm = Algorithm.PBEWithMD5AndDES)
    2. private String password;

    | 字段脱敏

    属性 @FieldSensitive 注解即可自动按照预设策略对源数据进行脱敏处理,默认 SensitiveType 内置 9 种常用脱敏策略。

    例如:中文名、银行卡账号、手机号码等脱敏策略。也可以自定义策略如下:

    1. @FieldSensitive(type = "testStrategy")
    2. private String username;
    3. @FieldSensitive(type = SensitiveType.mobile)
    4. private String mobile;

    自定义脱敏策略 testStrategy 添加到默认策略中注入 Spring 容器即可。

    1. @Configuration
    2. public class SensitiveStrategyConfig {
    3.     /**
    4.      * 注入脱敏策略
    5.      */
    6.     @Bean
    7.     public ISensitiveStrategy sensitiveStrategy() {
    8.         // 自定义 testStrategy 类型脱敏处理
    9.         return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
    10.     }
    11. }

    例如文章敏感词过滤:

    1. /**
    2.  * 演示文章敏感词过滤
    3.  */
    4. @RestController
    5. public class ArticleController {
    6.     @Autowired
    7.     private SensitiveWordsMapper sensitiveWordsMapper;
    8.     // 测试访问下面地址观察请求地址、界面返回数据及控制台( 普通参数 )
    9.     // 无敏感词 http://localhost:8080/info?content=tom&see=1&age=18
    10.     // 英文敏感词 http://localhost:8080/info?content=my%20content%20is%20tomcat&see=1&age=18
    11.     // 汉字敏感词 http://localhost:8080/info?content=%E7%8E%8B%E5%AE%89%E7%9F%B3%E5%94%90%E5%AE%8B%E5%85%AB%E5%A4%A7%E5%AE%B6&see=1
    12.     // 多个敏感词 http://localhost:8080/info?content=%E7%8E%8B%E5%AE%89%E7%9F%B3%E6%9C%89%E4%B8%80%E5%8F%AA%E7%8C%ABtomcat%E6%B1%A4%E5%A7%86%E5%87%AF%E7%89%B9&see=1&size=6
    13.     // 插入一个字变成非敏感词 http://localhost:8080/info?content=%E7%8E%8B%E7%8C%AB%E5%AE%89%E7%9F%B3%E6%9C%89%E4%B8%80%E5%8F%AA%E7%8C%ABtomcat%E6%B1%A4%E5%A7%86%E5%87%AF%E7%89%B9&see=1&size=6
    14.     @GetMapping("/info")
    15.     public String info(Article article) throws Exception {
    16.         return ParamsConfig.toJson(article);
    17.     }
    18.     // 添加一个敏感词然后再去观察是否生效 http://localhost:8080/add
    19.     // 观察【猫】这个词被过滤了 http://localhost:8080/info?content=%E7%8E%8B%E5%AE%89%E7%9F%B3%E6%9C%89%E4%B8%80%E5%8F%AA%E7%8C%ABtomcat%E6%B1%A4%E5%A7%86%E5%87%AF%E7%89%B9&see=1&size=6
    20.     // 嵌套敏感词处理 http://localhost:8080/info?content=%E7%8E%8B%E7%8C%AB%E5%AE%89%E7%9F%B3%E6%9C%89%E4%B8%80%E5%8F%AA%E7%8C%ABtomcat%E6%B1%A4%E5%A7%86%E5%87%AF%E7%89%B9&see=1&size=6
    21.     // 多层嵌套敏感词 http://localhost:8080/info?content=%E7%8E%8B%E7%8E%8B%E7%8C%AB%E5%AE%89%E7%9F%B3%E5%AE%89%E7%9F%B3%E6%9C%89%E4%B8%80%E5%8F%AA%E7%8C%ABtomcat%E6%B1%A4%E5%A7%86%E5%87%AF%E7%89%B9&see=1&size=6
    22.     @GetMapping("/add")
    23.     public String add() throws Exception {
    24.         Long id = 3L;
    25.         if (null == sensitiveWordsMapper.selectById(id)) {
    26.             System.err.println("插入一个敏感词:" + sensitiveWordsMapper.insert(new SensitiveWords(id, "猫")));
    27.             // 插入一个敏感词,刷新算法引擎敏感词
    28.             SensitiveWordsProcessor.reloadSensitiveWords();
    29.         }
    30.         return "ok";
    31.     }
    32.     // 测试访问下面地址观察控制台( 请求json参数 )
    33.     // idea 执行 resources 目录 TestJson.http 文件测试
    34.     @PostMapping("/json")
    35.     public String json(@RequestBody Article article) throws Exception {
    36.         return ParamsConfig.toJson(article);
    37.     }
    38. }

    | DDL 数据结构自动维护

    解决升级表结构初始化,版本发布更新 SQL 维护问题,目前支持 MySQL、PostgreSQL。

    1. @Component
    2. public class PostgresDdl implements IDdl {
    3.     /**
    4.      * 执行 SQL 脚本方式
    5.      */
    6.     @Override
    7.     public List<String> getSqlFiles() {
    8.         return Arrays.asList(
    9.                 // 内置包方式
    10.                 "db/tag-schema.sql",
    11.                 // 文件绝对路径方式
    12.                 "D:\\db\\tag-data.sql"
    13.         );
    14.     }
    15. }

    不仅仅可以固定执行,也可以动态执行!!

    1. ddlScript.run(new StringReader("DELETE FROM user;\n" +
    2.                 "INSERT INTO user (id, username, password, sex, email) VALUES\n" +
    3.                 "(20, 'Duo', '123456', 0, 'Duo@baomidou.com');"));

     
    

    它还支持多数据源执行!!!

    1. @Component
    2. public class MysqlDdl implements IDdl {
    3.     @Override
    4.     public void sharding(Consumer<IDdl> consumer) {
    5.         // 多数据源指定,主库初始化从库自动同步
    6.         String group = "mysql";
    7.         ShardingGroupProperty sgp = ShardingKey.getDbGroupProperty(group);
    8.         if (null != sgp) {
    9.             // 主库
    10.             sgp.getMasterKeys().forEach(key -> {
    11.                 ShardingKey.change(group + key);
    12.                 consumer.accept(this);
    13.             });
    14.             // 从库
    15.             sgp.getSlaveKeys().forEach(key -> {
    16.                 ShardingKey.change(group + key);
    17.                 consumer.accept(this);
    18.             });
    19.         }
    20.     }
    21.     /**
    22.      * 执行 SQL 脚本方式
    23.      */
    24.     @Override
    25.     public List<StringgetSqlFiles() {
    26.         return Arrays.asList("db/user-mysql.sql");
    27.     }
    28. }
     
    

    | 动态多数据源主从自由切换

    @Sharding 注解使数据源不限制随意使用切换,你可以在 mapper 层添加注解,按需求指哪打哪!!

    1. @Mapper
    2. @Sharding("mysql")
    3. public interface UserMapper extends BaseMapper<User{
    4.     @Sharding("postgres")
    5.     Long selectByUsername(String username);
    6. }

    你也可以自定义策略统一调兵遣将:

    1. @Component
    2. public class MyShardingStrategy extends RandomShardingStrategy {
    3.     /**
    4.      * 决定切换数据源 key {@link ShardingDatasource}
    5.      *
    6.      * @param group 动态数据库组
    7.      * @param invocation {@link Invocation}
    8.      * @param sqlCommandType {@link SqlCommandType}
    9.      */
    10.     @Override
    11.     public void determineDatasourceKey(String group, Invocation invocation, SqlCommandType sqlCommandType) {
    12.         // 数据源组 group 自定义选择即可, keys 为数据源组内主从多节点,可随机选择或者自己控制
    13.         this.changeDatabaseKey(group, sqlCommandType, keys -> chooseKey(keys, invocation));
    14.     }
    15. }

    可以开启主从策略,当然也是可以开启健康检查!具体配置:

    1. mybatis-mate:
    2.   sharding:
    3.     health: true # 健康检测
    4.     primary: mysql # 默认选择数据源
    5.     datasource:
    6.       mysql: # 数据库组
    7.         - key: node1
    8.           ...
    9.         - key: node2
    10.           cluster: slave # 从库读写分离时候负责 sql 查询操作,主库 master 默认可以不写
    11.           ...
    12.       postgres:
    13.         - key: node1 # 数据节点
    14.           ...

    | 分布式事务日志打印

    部分配置如下:

    1. /**
    2.  * <p>
    3.  * 性能分析拦截器,用于输出每条 SQL 语句及其执行时间
    4.  * </p>
    5.  */
    6. @Slf4j
    7. @Component
    8. @Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
    9.         @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
    10.         @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
    11. public class PerformanceInterceptor implements Interceptor {
    12.     /**
    13.      * SQL 执行最大时长,超过自动停止运行,有助于发现问题。
    14.      */
    15.     private long maxTime = 0;
    16.     /**
    17.      * SQL 是否格式化
    18.      */
    19.     private boolean format = false;
    20.     /**
    21.      * 是否写入日志文件<br>
    22.      * true 写入日志文件,不阻断程序执行!<br>
    23.      * 超过设定的最大执行时长异常提示!
    24.      */
    25.     private boolean writeInLog = false;
    26.     @Override
    27.     public Object intercept(Invocation invocation) throws Throwable {
    28.         Statement statement;
    29.         Object firstArg = invocation.getArgs()[0];
    30.         if (Proxy.isProxyClass(firstArg.getClass())) {
    31.             statement = (Statement) SystemMetaObject.forObject(firstArg).getValue("h.statement");
    32.         } else {
    33.             statement = (Statement) firstArg;
    34.         }
    35.         MetaObject stmtMetaObj = SystemMetaObject.forObject(statement);
    36.         try {
    37.             statement = (Statement) stmtMetaObj.getValue("stmt.statement");
    38.         } catch (Exception e) {
    39.             // do nothing
    40.         }
    41.         if (stmtMetaObj.hasGetter("delegate")) {//Hikari
    42.             try {
    43.                 statement = (Statement) stmtMetaObj.getValue("delegate");
    44.             } catch (Exception e) {
    45.             }
    46.         }
    47.         String originalSql = null;
    48.         if (originalSql == null) {
    49.             originalSql = statement.toString();
    50.         }
    51.         originalSql = originalSql.replaceAll("[\\s]+"" ");
    52.         int index = indexOfSqlStart(originalSql);
    53.         if (index > 0) {
    54.             originalSql = originalSql.substring(index);
    55.         }
    56.         // 计算执行 SQL 耗时
    57.         long start = SystemClock.now();
    58.         Object result = invocation.proceed();
    59.         long timing = SystemClock.now() - start;
    60.         // 格式化 SQL 打印执行结果
    61.         Object target = PluginUtils.realTarget(invocation.getTarget());
    62.         MetaObject metaObject = SystemMetaObject.forObject(target);
    63.         MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    64.         StringBuilder formatSql = new StringBuilder();
    65.         formatSql.append(" Time:").append(timing);
    66.         formatSql.append(" ms - ID:").append(ms.getId());
    67.         formatSql.append("\n Execute SQL:").append(sqlFormat(originalSql, format)).append("\n");
    68.         if (this.isWriteInLog()) {
    69.             if (this.getMaxTime() >= 1 && timing > this.getMaxTime()) {
    70.                 log.error(formatSql.toString());
    71.             } else {
    72.                 log.debug(formatSql.toString());
    73.             }
    74.         } else {
    75.             System.err.println(formatSql);
    76.             if (this.getMaxTime() >= 1 && timing > this.getMaxTime()) {
    77.                 throw new RuntimeException(" The SQL execution time is too large, please optimize ! ");
    78.             }
    79.         }
    80.         return result;
    81.     }
    82.     @Override
    83.     public Object plugin(Object target) {
    84.         if (target instanceof StatementHandler) {
    85.             return Plugin.wrap(target, this);
    86.         }
    87.         return target;
    88.     }
    89.     @Override
    90.     public void setProperties(Properties prop) {
    91.         String maxTime = prop.getProperty("maxTime");
    92.         String format = prop.getProperty("format");
    93.         if (StringUtils.isNotEmpty(maxTime)) {
    94.             this.maxTime = Long.parseLong(maxTime);
    95.         }
    96.         if (StringUtils.isNotEmpty(format)) {
    97.             this.format = Boolean.valueOf(format);
    98.         }
    99.     }
    100.     public long getMaxTime() {
    101.         return maxTime;
    102.     }
    103.     public PerformanceInterceptor setMaxTime(long maxTime) {
    104.         this.maxTime = maxTime;
    105.         return this;
    106.     }
    107.     public boolean isFormat() {
    108.         return format;
    109.     }
    110.     public PerformanceInterceptor setFormat(boolean format) {
    111.         this.format = format;
    112.         return this;
    113.     }
    114.     public boolean isWriteInLog() {
    115.         return writeInLog;
    116.     }
    117.     public PerformanceInterceptor setWriteInLog(boolean writeInLog) {
    118.         this.writeInLog = writeInLog;
    119.         return this;
    120.     }
    121.     public Method getMethodRegular(Class<?> clazz, String methodName) {
    122.         if (Object.class.equals(clazz)) {
    123.             return null;
    124.         }
    125.         for (Method method : clazz.getDeclaredMethods()) {
    126.             if (method.getName().equals(methodName)) {
    127.                 return method;
    128.             }
    129.         }
    130.         return getMethodRegular(clazz.getSuperclass(), methodName);
    131.     }
    132.     /**
    133.      * 获取sql语句开头部分
    134.      *
    135.      * @param sql
    136.      * @return
    137.      */
    138.     private int indexOfSqlStart(String sql) {
    139.         String upperCaseSql = sql.toUpperCase();
    140.         Set<Integer> set = new HashSet<>();
    141.         set.add(upperCaseSql.indexOf("SELECT "));
    142.         set.add(upperCaseSql.indexOf("UPDATE "));
    143.         set.add(upperCaseSql.indexOf("INSERT "));
    144.         set.add(upperCaseSql.indexOf("DELETE "));
    145.         set.remove(-1);
    146.         if (CollectionUtils.isEmpty(set)) {
    147.             return -1;
    148.         }
    149.         List<Integer> list = new ArrayList<>(set);
    150.         Collections.sort(list, Integer::compareTo);
    151.         return list.get(0);
    152.     }
    153.     private final static SqlFormatter sqlFormatter = new SqlFormatter();
    154.     /**
    155.      * 格式sql
    156.      *
    157.      * @param boundSql
    158.      * @param format
    159.      * @return
    160.      */
    161.     public static String sqlFormat(String boundSql, boolean format) {
    162.         if (format) {
    163.             try {
    164.                 return sqlFormatter.format(boundSql);
    165.             } catch (Exception ignored) {
    166.             }
    167.         }
    168.         return boundSql;
    169.     }
    170. }

    使用:

    1. @RestController
    2. @AllArgsConstructor
    3. public class TestController {
    4.     private BuyService buyService;
    5.     // 数据库 test 表 t_order 在事务一致情况无法插入数据,能够插入说明多数据源事务无效
    6.     // 测试访问 http://localhost:8080/test
    7.     // 制造事务回滚 http://localhost:8080/test?error=true 也可通过修改表结构制造错误
    8.     // 注释 ShardingConfig 注入 dataSourceProvider 可测试事务无效情况
    9.     @GetMapping("/test")
    10.     public String test(Boolean error) {
    11.         return buyService.buy(null != error && error);
    12.     }
    13. }

    | 数据权限

    mapper 层添加注解:

    1. // 测试 test 类型数据权限范围,混合分页模式
    2. @DataScope(type = "test", value = {
    3.         // 关联表 user 别名 u 指定部门字段权限
    4.         @DataColumn(alias = "u", name = "department_id"),
    5.         // 关联表 user 别名 u 指定手机号字段(自己判断处理)
    6.         @DataColumn(alias = "u", name = "mobile")
    7. })
    8. @Select("select u.* from user u")
    9. List<User> selectTestList(IPage<User> page, Long id, @Param("name") String username);
     
    
     
    

    模拟业务处理逻辑:

    1. @Bean
    2. public IDataScopeProvider dataScopeProvider() {
    3.     return new AbstractDataScopeProvider() {
    4.         @Override
    5.         protected void setWhere(PlainSelect plainSelect, Object[] args, DataScopeProperty dataScopeProperty) {
    6.             // args 中包含 mapper 方法的请求参数,需要使用可以自行获取
    7.             /*
    8.                 // 测试数据权限,最终执行 SQL 语句
    9.                 SELECT u.* FROM user u WHERE (u.department_id IN ('1', '2', '3', '5'))
    10.                 AND u.mobile LIKE '%1533%'
    11.              */
    12.             if ("test".equals(dataScopeProperty.getType())) {
    13.                 // 业务 test 类型
    14.                 List<DataColumnProperty> dataColumns = dataScopeProperty.getColumns();
    15.                 for (DataColumnProperty dataColumn : dataColumns) {
    16.                     if ("department_id".equals(dataColumn.getName())) {
    17.                         // 追加部门字段 IN 条件,也可以是 SQL 语句
    18.                         Set<String> deptIds = new HashSet<>();
    19.                         deptIds.add("1");
    20.                         deptIds.add("2");
    21.                         deptIds.add("3");
    22.                         deptIds.add("5");
    23.                         ItemsList itemsList = new ExpressionList(deptIds.stream().map(StringValue::new).collect(Collectors.toList()));
    24.                         InExpression inExpression = new InExpression(new Column(dataColumn.getAliasDotName()), itemsList);
    25.                         if (null == plainSelect.getWhere()) {
    26.                             // 不存在 where 条件
    27.                             plainSelect.setWhere(new Parenthesis(inExpression));
    28.                         } else {
    29.                             // 存在 where 条件 and 处理
    30.                             plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), inExpression));
    31.                         }
    32.                     } else if ("mobile".equals(dataColumn.getName())) {
    33.                         // 支持一个自定义条件
    34.                         LikeExpression likeExpression = new LikeExpression();
    35.                         likeExpression.setLeftExpression(new Column(dataColumn.getAliasDotName()));
    36.                         likeExpression.setRightExpression(new StringValue("%1533%"));
    37.                         plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), likeExpression));
    38.                     }
    39.                 }
    40.             }
    41.         }
    42.     };
    43. }
     
    

    最终执行 SQL 输出:

    1. SELECT u.* FROM user u 
    2.   WHERE (u.department_id IN ('1''2''3''5')) 
    3.   AND u.mobile LIKE '%1533%' LIMIT 110

  • 相关阅读:
    小景的Dba之路--impdp导入数据问题报错排查总结
    Arduino 控制理论(3)- 如何在 Arduino 中调节 PID 控制器
    Zookeeper实战案例(1)
    关于web前端大作业的HTML网页设计——我的班级网页HTML+CSS+JavaScript
    Selenium安装以及案例演示【Java爬虫】
    TIM_CCxChannelCmd函数无法关闭互补通道输出
    开发笔记:如何对【动态链接库】文件进行加密保护?
    关于<dependencyManagement>和<dependencies>
    【Ubuntu】Ubuntu 16.04 安装新的Linux内核
    奥迪Q3电瓶损坏问题解决思路
  • 原文地址:https://blog.csdn.net/qq_35872777/article/details/125534245