在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    MyBatisPlus又在搞事了!發(fā)布神器,一個依賴輕松搞定權限問題

    今天介紹一個 MyBatis – Plus 官方發(fā)布的神器:mybatis-mate 為 mp 企業(yè)級模塊,支持分庫分表,數(shù)據(jù)審計、數(shù)據(jù)敏感詞過濾(AC算法),字段加密,字典回寫(數(shù)據(jù)綁定),數(shù)據(jù)權限,表結構自動生成 SQL 維護等,旨在更敏捷優(yōu)雅處理數(shù)據(jù)。

    1. 主要功能

    • 字典綁定
    • 字段加密
    • 數(shù)據(jù)脫敏
    • 表結構動態(tài)維護
    • 數(shù)據(jù)審計記錄
    • 數(shù)據(jù)范圍(數(shù)據(jù)權限)
    • 數(shù)據(jù)庫分庫分表、動態(tài)據(jù)源、讀寫分離、數(shù)- – 據(jù)庫健康檢查自動切換。

    2.使用

    2.1 依賴導入

    Spring Boot 引入自動依賴注解

    com.baomidoumybatis-mate-starter1.0.8

    注解(實體分包使用)

    com.baomidoumybatis-mate-annotation1.0.8

    2.2 字段數(shù)據(jù)綁定(字典回寫)

    例如 user_sex 類型 sex 字典結果映射到 sexText 屬性

    @FieldDict(type = “user_sex”, target = “sexText”)private Integer sex;private String sexText;

    實現(xiàn) IDataDict 接口提供字典數(shù)據(jù)源,注入到 Spring 容器即可。

    @Componentpublic class DataDict implements IDataDict {/*** 從數(shù)據(jù)庫或緩存中獲取*/private Map SEX_MAP = new ConcurrentHashMap() {{put(“0”, “女”);put(“1”, “男”);}};@Overridepublic String getNameByCode(FieldDict fieldDict, String code) {System.err.println(“字段類型:” + fieldDict.type() + “,編碼:” + code);return SEX_MAP.get(code);}}

    2.3 字段加密

    屬性 @FieldEncrypt 注解即可加密存儲,會自動解密查詢結果,支持全局配置加密密鑰算法,及注解密鑰算法,可以實現(xiàn) IEncryptor 注入自定義算法。

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

    2.4 字段脫敏

    屬性 @FieldSensitive 注解即可自動按照預設策略對源數(shù)據(jù)進行脫敏處理,默認 SensitiveType 內置 9 種常用脫敏策略。

    例如:中文名、銀行卡賬號、手機號碼等 脫敏策略。也可以自定義策略如下:

    @FieldSensitive(type = “testStrategy”)private String username;@FieldSensitive(type = SensitiveType.mobile)private String mobile;

    自定義脫敏策略 testStrategy 添加到默認策略中注入 Spring 容器即可。

    @Configurationpublic class SensitiveStrategyConfig {/*** 注入脫敏策略*/@Beanpublic ISensitiveStrategy sensitiveStrategy() {// 自定義 testStrategy 類型脫敏處理return new SensitiveStrategy().addStrategy(“testStrategy”, t -> t + “***test***”);}}

    例如:文章敏感詞過濾

    /*** 演示文章敏感詞過濾*/@RestControllerpublic class ArticleController {@Autowiredprivate SensitiveWordsMapper sensitiveWordsMapper;// 測試訪問下面地址觀察請求地址、界面返回數(shù)據(jù)及控制臺( 普通參數(shù) )// 無敏感詞 http://localhost:8080/info?content=tom&see=1&age=18// 英文敏感詞 http://localhost:8080/info?content=my%20content%20is%20tomcat&see=1&age=18// 漢字敏感詞 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// 多個敏感詞 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// 插入一個字變成非敏感詞 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@GetMapping(“/info”)public String info(Article article) throws Exception {return ParamsConfig.toJson(article);}// 添加一個敏感詞然后再去觀察是否生效 http://localhost:8080/add// 觀察【貓】這個詞被過濾了 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// 嵌套敏感詞處理 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// 多層嵌套敏感詞 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@GetMapping(“/add”)public String add() throws Exception {Long id = 3L;if (null == sensitiveWordsMapper.selectById(id)) {System.err.println(“插入一個敏感詞:” + sensitiveWordsMapper.insert(new SensitiveWords(id, “貓”)));// 插入一個敏感詞,刷新算法引擎敏感詞SensitiveWordsProcessor.reloadSensitiveWords();}return “ok”;}// 測試訪問下面地址觀察控制臺( 請求json參數(shù) )// idea 執(zhí)行 resources 目錄 TestJson.http 文件測試@PostMapping(“/json”)public String json(@RequestBody Article article) throws Exception {return ParamsConfig.toJson(article);}}

    2.5 DDL 數(shù)據(jù)結構自動維護

    解決升級表結構初始化,版本發(fā)布更新 SQL 維護問題,目前支持 MySql、PostgreSQL。

    @Componentpublic class PostgresDdl implements IDdl {/*** 執(zhí)行 SQL 腳本方式*/@Overridepublic List getSqlFiles() {return Arrays.asList(// 內置包方式”db/tag-schema.sql”,// 文件絕對路徑方式”D:dbtag-data.sql”);}}

    不僅僅可以固定執(zhí)行,也可以動態(tài)執(zhí)行??!

    ddlScript.run(new StringReader(“DELETE FROM user;” +”INSERT INTO user (id, username, password, sex, email) VALUES” +”(20, ‘Duo’, ‘123456’, 0, ‘[email protected]’);”));

    它還支持多數(shù)據(jù)源執(zhí)行?。?!

    @Componentpublic class MysqlDdl implements IDdl {@Overridepublic void sharding(Consumer consumer) {// 多數(shù)據(jù)源指定,主庫初始化從庫自動同步String group = “mysql”;ShardingGroupProperty sgp = ShardingKey.getDbGroupProperty(group);if (null != sgp) {// 主庫sgp.getMasterKeys().forEach(key -> {ShardingKey.change(group + key);consumer.accept(this);});// 從庫sgp.getSlaveKeys().forEach(key -> {ShardingKey.change(group + key);consumer.accept(this);});}}/*** 執(zhí)行 SQL 腳本方式*/@Overridepublic List getSqlFiles() {return Arrays.asList(“db/user-mysql.sql”);}}

    2.6 動態(tài)多數(shù)據(jù)源主從自由切換

    @Sharding 注解使數(shù)據(jù)源不限制隨意使用切換,你可以在 mapper 層添加注解,按需求指哪打哪??!

    @Mapper@Sharding(“mysql”)public interface UserMapper extends BaseMapper {@Sharding(“postgres”)Long selectByUsername(String username);}

    你也可以自定義策略統(tǒng)一調兵遣將

    @Componentpublic class MyShardingStrategy extends RandomShardingStrategy {/*** 決定切換數(shù)據(jù)源 key {@link ShardingDatasource}** @param group 動態(tài)數(shù)據(jù)庫組* @param invocation {@link Invocation}* @param sqlCommandType {@link SqlCommandType}*/@Overridepublic void determineDatasourceKey(String group, Invocation invocation, SqlCommandType sqlCommandType) {// 數(shù)據(jù)源組 group 自定義選擇即可, keys 為數(shù)據(jù)源組內主從多節(jié)點,可隨機選擇或者自己控制this.changeDatabaseKey(group, sqlCommandType, keys -> chooseKey(keys, invocation));}}

    可以開啟主從策略,當然也是可以開啟健康檢查!具體配置:

    mybatis-mate:sharding:health: true # 健康檢測primary: mysql # 默認選擇數(shù)據(jù)源datasource:mysql: # 數(shù)據(jù)庫組- key: node1…- key: node2cluster: slave # 從庫讀寫分離時候負責 sql 查詢操作,主庫 master 默認可以不寫…postgres:- key: node1 # 數(shù)據(jù)節(jié)點…

    2.7 分布式事務日志打印

    部分配置如下:

    /***

    * 性能分析攔截器,用于輸出每條 SQL 語句及其執(zhí)行時間*

    */@Slf4j@Component@Intercepts({@Signature(type = StatementHandler.class, method = “query”, args = {Statement.class, ResultHandler.class}),@Signature(type = StatementHandler.class, method = “update”, args = {Statement.class}),@Signature(type = StatementHandler.class, method = “batch”, args = {Statement.class})})public class PerformanceInterceptor implements Interceptor {/*** SQL 執(zhí)行最大時長,超過自動停止運行,有助于發(fā)現(xiàn)問題。*/private long maxTime = 0;/*** SQL 是否格式化*/private boolean format = false;/*** 是否寫入日志文件* true 寫入日志文件,不阻斷程序執(zhí)行!* 超過設定的最大執(zhí)行時長異常提示!*/private boolean writeInLog = false;@Overridepublic Object intercept(Invocation invocation) throws Throwable {Statement statement;Object firstArg = invocation.getArgs()[0];if (Proxy.isProxyClass(firstArg.getClass())) {statement = (Statement) SystemMetaObject.forObject(firstArg).getValue(“h.statement”);} else {statement = (Statement) firstArg;}MetaObject stmtMetaObj = SystemMetaObject.forObject(statement);try {statement = (Statement) stmtMetaObj.getValue(“stmt.statement”);} catch (Exception e) {// do nothing}if (stmtMetaObj.hasGetter(“delegate”)) {//Hikaritry {statement = (Statement) stmtMetaObj.getValue(“delegate”);} catch (Exception e) {}}String originalSql = null;if (originalSql == null) {originalSql = statement.toString();}originalSql = originalSql.replaceAll(“[s]+”, ” “);int index = indexOfSqlStart(originalSql);if (index > 0) {originalSql = originalSql.substring(index);}// 計算執(zhí)行 SQL 耗時long start = SystemClock.now();Object result = invocation.proceed();long timing = SystemClock.now() – start;// 格式化 SQL 打印執(zhí)行結果Object target = PluginUtils.realTarget(invocation.getTarget());MetaObject metaObject = SystemMetaObject.forObject(target);MappedStatement ms = (MappedStatement) metaObject.getValue(“delegate.mappedStatement”);StringBuilder formatSql = new StringBuilder();formatSql.append(” Time:”).append(timing);formatSql.append(” ms – ID:”).append(ms.getId());formatSql.append(” Execute SQL:”).append(sqlFormat(originalSql, format)).append(“”);if (this.isWriteInLog()) {if (this.getMaxTime() >= 1 && timing > this.getMaxTime()) {log.error(formatSql.toString());} else {log.debug(formatSql.toString());}} else {System.err.println(formatSql);if (this.getMaxTime() >= 1 && timing > this.getMaxTime()) {throw new RuntimeException(” The SQL execution time is too large, please optimize ! “);}}return result;}@Overridepublic Object plugin(Object target) {if (target instanceof StatementHandler) {return Plugin.wrap(target, this);}return target;}@Overridepublic void setProperties(Properties prop) {String maxTime = prop.getProperty(“maxTime”);String format = prop.getProperty(“format”);if (StringUtils.isNotEmpty(maxTime)) {this.maxTime = Long.parseLong(maxTime);}if (StringUtils.isNotEmpty(format)) {this.format = Boolean.valueOf(format);}}public long getMaxTime() {return maxTime;}public PerformanceInterceptor setMaxTime(long maxTime) {this.maxTime = maxTime;return this;}public boolean isFormat() {return format;}public PerformanceInterceptor setFormat(boolean format) {this.format = format;return this;}public boolean isWriteInLog() {return writeInLog;}public PerformanceInterceptor setWriteInLog(boolean writeInLog) {this.writeInLog = writeInLog;return this;}public Method getMethodRegular(Class clazz, String methodName) {if (Object.class.equals(clazz)) {return null;}for (Method method : clazz.getDeclaredMethods()) {if (method.getName().equals(methodName)) {return method;}}return getMethodRegular(clazz.getSuperclass(), methodName);}/*** 獲取sql語句開頭部分** @param sql* @return*/private int indexOfSqlStart(String sql) {String upperCaseSql = sql.toUpperCase();Set set = new HashSet();set.add(upperCaseSql.indexOf(“SELECT “));set.add(upperCaseSql.indexOf(“UPDATE “));set.add(upperCaseSql.indexOf(“INSERT “));set.add(upperCaseSql.indexOf(“DELETE “));set.remove(-1);if (CollectionUtils.isEmpty(set)) {return -1;}List list = new ArrayList(set);Collections.sort(list, Integer::compareTo);return list.get(0);}private final static SqlFormatter sqlFormatter = new SqlFormatter();/*** 格式sql** @param boundSql* @param format* @return*/public static String sqlFormat(String boundSql, boolean format) {if (format) {try {return sqlFormatter.format(boundSql);} catch (Exception ignored) {}}return boundSql;}}

    使用:

    @RestController@AllArgsConstructorpublic class TestController {private BuyService buyService;// 數(shù)據(jù)庫 test 表 t_order 在事務一致情況無法插入數(shù)據(jù),能夠插入說明多數(shù)據(jù)源事務無效// 測試訪問 http://localhost:8080/test// 制造事務回滾 http://localhost:8080/test?error=true 也可通過修改表結構制造錯誤// 注釋 ShardingConfig 注入 dataSourceProvider 可測試事務無效情況@GetMapping(“/test”)public String test(Boolean error) {return buyService.buy(null != error && error);}}

    2.8 數(shù)據(jù)權限

    mapper 層添加注解:

    // 測試 test 類型數(shù)據(jù)權限范圍,混合分頁模式@DataScope(type = “test”, value = {// 關聯(lián)表 user 別名 u 指定部門字段權限@DataColumn(alias = “u”, name = “department_id”),// 關聯(lián)表 user 別名 u 指定手機號字段(自己判斷處理)@DataColumn(alias = “u”, name = “mobile”)})@Select(“select u.* from user u”)List selectTestList(IPage page, Long id, @Param(“name”) String username);

    模擬業(yè)務處理邏輯:

    @Beanpublic IDataScopeProvider dataScopeProvider() {return new AbstractDataScopeProvider() {@Overrideprotected void setWhere(PlainSelect plainSelect, Object[] args, DataScopeProperty dataScopeProperty) {// args 中包含 mapper 方法的請求參數(shù),需要使用可以自行獲取/*// 測試數(shù)據(jù)權限,最終執(zhí)行 SQL 語句SELECT u.* FROM user u WHERE (u.department_id IN (‘1’, ‘2’, ‘3’, ‘5’))AND u.mobile LIKE ‘%1533%’*/if (“test”.equals(dataScopeProperty.getType())) {// 業(yè)務 test 類型List dataColumns = dataScopeProperty.getColumns();for (DataColumnProperty dataColumn : dataColumns) {if (“department_id”.equals(dataColumn.getName())) {// 追加部門字段 IN 條件,也可以是 SQL 語句Set deptIds = new HashSet();deptIds.add(“1”);deptIds.add(“2”);deptIds.add(“3”);deptIds.add(“5”);ItemsList itemsList = new ExpressionList(deptIds.stream().map(StringValue::new).collect(Collectors.toList()));InExpression inExpression = new InExpression(new Column(dataColumn.getAliasDotName()), itemsList);if (null == plainSelect.getWhere()) {// 不存在 where 條件plainSelect.setWhere(new Parenthesis(inExpression));} else {// 存在 where 條件 and 處理plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), inExpression));}} else if (“mobile”.equals(dataColumn.getName())) {// 支持一個自定義條件LikeExpression likeExpression = new LikeExpression();likeExpression.setLeftExpression(new Column(dataColumn.getAliasDotName()));likeExpression.setRightExpression(new StringValue(“%1533%”));plainSelect.setWhere(new AndExpression(plainSelect.getWhere(), likeExpression));}}}}};}

    最終執(zhí)行 SQL 輸出:

    SELECT u.* FROM user uWHERE (u.department_id IN (‘1’, ‘2’, ‘3’, ‘5’))AND u.mobile LIKE ‘%1533%’ LIMIT 1, 10

    目前僅有付費版本,了解更多 mybatis-mate 使用示例詳見:

    https://gitee.com/baomidou/mybatis-mate-example

    原文鏈接:https://mp.weixin.qq.com/s/3Uim4i5YK4QWL4GHiNpjdA

    鄭重聲明:本文內容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權歸原作者所有,如有侵權請聯(lián)系管理員(admin#wlmqw.com)刪除。
    用戶投稿
    上一篇 2022年6月19日 07:00
    下一篇 2022年6月19日 07:00

    相關推薦

    • 什么是推廣cpa一篇文章帶你看懂CPA推廣渠道

      CPA渠道 CPA指的是按照指定的行為結算,可以是搜索,可以是注冊,可以是激活,可以是搜索下載激活,可以是綁卡,實名認證,可以是付費,可以是瀏覽等等。甲乙雙方可以根據(jù)自己的情況來定…

      2022年11月25日
    • 百度關鍵詞快速排名的4大原理解析(百度怎么刷關鍵詞)

      近期百度公告驚雷算法2.0,升級之快還是第一次吧,看來百度對于刷點擊行為是零容忍了。之前尹華峰SEO技術博客介紹過一篇如何使用刷點擊工具,其實市面上有很多這類SEO快速排名的軟件,…

      2022年11月25日
    • 抖音直播帶貨有哪些方法技巧(抖音直播帶貨有哪些痛點)

      如今抖音這個短視頻的變現(xiàn)能力越來越突顯了,尤其是在平臺上開通直播,更具有超強的帶貨屬性,已經(jīng)有越來越多的普通人加入到其中了。不過直播帶貨雖然很火,但是也不是每個人都能做好的,那么在…

      2022年11月24日
    • 明查|美國新冠后遺癥患者中有16%癥狀嚴重以致無法工作?

      點擊進入澎湃新聞全球事實核查平臺 速覽 – 網(wǎng)傳數(shù)據(jù)比例無權威信源佐證,該比例有可能是結合了美國疾病防控中心和布魯金斯學會的數(shù)據(jù)得出,但這兩個機構的調研目的和樣本都不同…

      2022年11月24日
    • 愛美劇改成什么了(愛美劇什么意思)

      現(xiàn)在市面是哪個有很多看劇神器,有韓劇軟件、泰劇軟件、美劇軟件,其中愛美劇是非常不錯的一款看美劇軟件,里面資源豐富,據(jù)悉現(xiàn)在已經(jīng)改名了,那么愛美劇改成什么了?愛美劇現(xiàn)在叫什么?下面小…

      2022年11月22日
    • 寬帶測速軟件(手機寬帶測速軟件)

      中國聯(lián)通用戶可登錄中國聯(lián)通網(wǎng)上營業(yè)廳,選擇寬帶寬帶服務寬帶測速,按頁面指導進行測速,測速時建議您直連電腦,如測速結果無法達到簽約速率,您可通過中國聯(lián)通APP,“服務報障在線報障”進…

      2022年11月22日
    • 淘寶運營數(shù)據(jù)分析的3個指標解析(運營數(shù)據(jù)分析怎么做)

      我們知道淘寶運營工作中對于數(shù)據(jù)的分析與整理是很重要的,這些工作乍一聽可能比較難,但是也有一些相關的技巧可以讓我們能夠有效的找出對我們有用的數(shù)據(jù),這樣我們也能夠更加直觀的看出我們店鋪…

      2022年11月20日
    • 軟件開發(fā)階段的6大劃分詳解(需求規(guī)格說明書在哪個階段)

      1計劃 對所要解決的問題進行總體定義,包括了解用戶的要求及現(xiàn)實環(huán)境,從技術、經(jīng)濟和社會因素等3個方面研究并論證本軟件項目的可行性,編寫可行性研究報告,探討解決問題的方案,并對可供使…

      2022年11月19日
    • 3階魔方教程 1~7步驟(魔方教程一步一步圖解)

      基礎層先魔方復原法 by信手拈花 0. 魔方轉動的公式表示和復原步驟 0. 1魔方轉動的公式表示 魔方轉動的公式表示 0. 2層先法魔方復原步驟 層先法魔方復原步驟 讓我開始魔方復…

      2022年11月18日
    • 1公頃等于多少平方千米(公頃等于多少平方米)

      四年級數(shù)學上冊第二單元 公頃和平方千米 一、換算進率 1平方千米= 100公頃=1000000 平方米 1公頃= 10000平方米 1平方米=100平方分米 1平方分米= 100平…

      2022年11月18日

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時間:周一至周五,10:30-18:30,節(jié)假日休息