diff --git a/.gitignore b/.gitignore index 1567da9a..50ba3ac5 100644 --- a/.gitignore +++ b/.gitignore @@ -36,5 +36,3 @@ build/ !/mvnw !/mvnw.cmd -shardingsphere101/.idea/** -springboot101/.idea/** diff --git a/README.md b/README.md index dd8cc16b..1a495581 100644 --- a/README.md +++ b/README.md @@ -5,23 +5,22 @@ - + -## 说在前边 - - -> 本项目全部案例详细教程,同步在 个人**公众号:程序员小富** , 欢迎关注交流指正,加群学习! +> 本项目全部案例详细教程,同步在 个人公众号:**程序员小富** , 欢迎关注交流指正,加群学习
- +
![](wx/person.png) -[**作者小富,目前就职某大厂,点击一起来了解下**](https://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247500646&idx=1&sn=5a0993997dc1fc609da4eda5ba610681&chksm=9b86539bacf1da8d2bc22b569d27e1b7b85a21a0ec7d5a5f4a6660148a5f40f076e2d42e4885&token=1045698719&lang=zh_CN#rd) +[**作者小富,目前就职京东,点击一起来了解下**](https://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247500646&idx=1&sn=5a0993997dc1fc609da4eda5ba610681&chksm=9b86539bacf1da8d2bc22b569d27e1b7b85a21a0ec7d5a5f4a6660148a5f40f076e2d42e4885&token=1045698719&lang=zh_CN#rd) + +--- -## 项目介绍 +### 介绍 **Springboot-Notebook** 一个以 `springboot` 为基础开发框架, 整合 `Redis` 、`Mysql` 、 `Rabbitmq` 、`ES` 、`MongoDB`、`sharding-jdbc @@ -42,84 +41,17 @@ 消息推送 | 7种实时消息推送 更多 | ...... -## 🤝 关于作者 - -大家好,我是本站作者小富~ 从事编程工作十余年,在大厂狗东做过架构相关工作. - -写作分享很多年,将工作中的所遇到的问题、用到技术梳理成文章分享出来和小伙伴们共勉,希望对大家有用! - -目前在持续的更新三个系列的专题《Springboot开发实战100例》、《ShardingSphere5.x分库分表原理与实战》、《面试八股》 - -## 🔥技术群 & 资料 - -如果遇到了问题,可以通过以下方式联系我。也欢迎加入我们的技术交流群,群里都是热心的Javaer,会讨论技术问题,互相帮助,相信能让您获得更多收获。 - -**在我的公众号:程序员小富,内提供了一些资料:** - -- 技术书籍公众号内回复[ **pdf** ] Get。 - -- 面试笔记、springcloud进阶实战PDF,公众号内回复[ **1222** ] Get。 - -- 原创《ShardingSphere5.x分库分表原理与实战》PDF,公众号内回复[ **分库分表** ] Get。 - - -| ![个人公众号](https://img.shields.io/static/v1?label=wechat&message=微信公众号&logo=wechat&color=07C160) | ![个人公众号](https://img.shields.io/static/v1?label=wechat&message=个人微信&logo=wechat&color=07C160) | -| ---------| ------- | -| | | -| 关注公众号:程序员小富 | 接搜微信号:xiaofucode| - - -## 系列专题 - -### 《ShardingSphere5.x分库分表原理与实战》 - -内容同步在小富的个人网站:[xiaofucode.com](https://xiaofucode.com),现有章节已经生成了 **PDF**,欢迎下载! - -获取方式:《ShardingSphere5.x分库分表原理与实战》PDF,**公众号:程序员小富**内回复[ **分库分表** ] Get。 - -
- -
- -系列往期精选: - -- [好好的系统,为什么要分库分表?](https://mp.weixin.qq.com/s/-WFBtHtTMtHoGwIm9bL4Uw) -- [分库分表的 21 条法则,hold 住!](https://mp.weixin.qq.com/s/aRQLKGzFHcX7zQLqa6FIbA) -- [2 种方式快速实现分库分表,轻松拿捏!](https://mp.weixin.qq.com/s/XdlJK170YZEwof6DzZlbZg) -- [分库分表如何管理不同实例中几万张分片表?](https://mp.weixin.qq.com/s/IdJoG-0cCaPJ5s2aAOM3Jw) -- [一口气搞懂分库分表 12 种分片算法,大厂都在用](https://mp.weixin.qq.com/s/HAoCXGoGCbDt9ZaWCu-qIw) -- [DIY 3 种分库分表分片算法,自己写的轮子才吊!](https://mp.weixin.qq.com/s/EADxOtkURwYEit7-ou2bqQ) -- [ 持续更新中...](https://xiaofucode.com) - -### 《Springboot 开发场景 100 例》 - -Springboot101 上百个 Springboot 开发实战案例分享,开发工作拿来即用,省下的时间就是生活。内容同步在小富的个人网站:[xiaofucode.com](https://xiaofucode.com)! - -系列往期精选: - -- [springboot一行代码实现文件上传20个平台](http://www.xiaofucode.com/guide/springboot101/high/一行代码实现文件上传%2020个平台.html) -- [springboot + rabbitmq + MQTT 实现智能家居](http://www.xiaofucode.com/guide/springboot101/high/springboot%20_%20rabbitmq%20做智能家居.html) -- [springboot + redis 分布式限流器](http://www.xiaofucode.com/guide/springboot101/high/springboot%20_%20Redis%20分布式限流器.html) -- [springboot注解实现动态数据源切换](http://www.xiaofucode.com/guide/springboot101/数据库/注解实现动态数据源切换.html) -- [springboot + Knife4j 集成API文档](http://www.xiaofucode.com/guide/springboot101/文档/集成Knife4j.html) -- [springboot + oauth2.0实战](http://www.xiaofucode.com/guide/springboot101/high/OAuth2.0实战.html) -- [springboot + canal实现 mysql+binlog 监控](http://www.xiaofucode.com/guide/springboot101/high/canal%20实现mysql%20binlog监控.html) -- [springboot + jsoup 实现爬虫](http://www.xiaofucode.com/guide/springboot101/high/springboot%20_%20jsoup%20实现爬虫.html) -- [ 更多文章...](https://xiaofucode.com) - ### 面试八股 -内容同步在小富的个人网站:[xiaofucode.com](https://xiaofucode.com)。 - - 《spring cloud alibaba 微服务全家桶》 + - 《面试笔记》 + - 《LeetCode算法笔记》 -**获取方式**:[公众号:**程序员小富** , 回复[ **1222** ]](https://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247500646&idx=1&sn=5a0993997dc1fc609da4eda5ba610681&chksm=9b86539bacf1da8d2bc22b569d27e1b7b85a21a0ec7d5a5f4a6660148a5f40f076e2d42e4885&token=1045698719&lang=zh_CN#rd) -
- -
+**获取方式**:[公众号:**程序员小富** , 回复 **1222**](https://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247500646&idx=1&sn=5a0993997dc1fc609da4eda5ba610681&chksm=9b86539bacf1da8d2bc22b569d27e1b7b85a21a0ec7d5a5f4a6660148a5f40f076e2d42e4885&token=1045698719&lang=zh_CN#rd) + ### 电子书 @@ -127,9 +59,9 @@ Springboot101 上百个 Springboot 开发实战案例分享,开发工作拿来 ![](wx/book.png) -## 优质文章精选 +### 优质文章精选 -### Java 开发技巧 +#### Java 开发技巧 - [3种 Springboot 全局时间格式化方式,别再写重复代码了](https://mp.weixin.qq.com/s/MeDfnL__jdEq7Yi48vg_vA) (`springboot-global-formatting`) - [真是没想到,Springboot + Flowable 开发工作流会这么简单!](https://mp.weixin.qq.com/s/hXS9HirRnhYRMIwd4GVeIQ) (`springboot-work-flowable`) @@ -258,3 +190,20 @@ Springboot101 上百个 Springboot 开发实战案例分享,开发工作拿来 - [看了 100多份简历后,想给找工作的程序员几点建议](https://mp.weixin.qq.com/s/iVBbzaNpC--Tk6c-JfwtUQ) + + + +## springboot 101 + + +springboot 101 一个全新的免费 springboot 专栏,旨在让新手Java开发者可以快速上手实战,整个专栏分为基础篇和高级篇两大块。 + + + + +> 欢迎关注公众号、或者添加个人微信:xinzhifu521,加群学习 + +
+ + +
diff --git a/changeCommit.sh b/changeCommit.sh deleted file mode 100755 index a20834c7..00000000 --- a/changeCommit.sh +++ /dev/null @@ -1,10 +0,0 @@ - # changeCommit.sh - git filter-branch --commit-filter ' - if [ "$GIT_AUTHOR_EMAIL" = "" ]; - then - GIT_AUTHOR_NAME="程序员小富"; - GIT_AUTHOR_EMAIL="515361725@qq.com"; - git commit-tree "$@"; - else - git commit-tree "$@"; - fi' HEAD \ No newline at end of file diff --git a/pom.xml b/pom.xml index 798f221b..4437210a 100644 --- a/pom.xml +++ b/pom.xml @@ -14,9 +14,7 @@ pom - springboot101 - shardingsphere101 @@ -69,6 +67,12 @@ 1.2.83 + + + org.springframework.boot + spring-boot-starter-thymeleaf + + diff --git a/shardingsphere101/README.md b/shardingsphere101/README.md index 5d43c57c..da622045 100644 --- a/shardingsphere101/README.md +++ b/shardingsphere101/README.md @@ -1,5 +1,3 @@ -本项目的主要内容: +快速实现分库分表的两种方式 -1、默认的分库分表策略 -2、广播表 -3、绑定表的使用 \ No newline at end of file +文件链接:[SpringBoot 2 种方式快速实现分库分表,轻松拿捏!](https://mp.weixin.qq.com/s/XdlJK170YZEwof6DzZlbZg) diff --git a/shardingsphere101/pom.xml b/shardingsphere101/pom.xml index 936df99d..b753cd7a 100644 --- a/shardingsphere101/pom.xml +++ b/shardingsphere101/pom.xml @@ -17,36 +17,25 @@ 8 5.2.0 - 3.5.3.1 - 8.2.0 - shardingsphere-2fastcode - shardingsphere-default-strategy - - shardingsphere-autocreate-table - - shardingsphere-algorithms - - shardingsphere-sequence-algorithm + shardingsphere-default - - com.baomidou - mybatis-plus-boot-starter - ${mybatis.plus.version} + org.springframework.boot + spring-boot-starter-data-jpa com.mysql mysql-connector-j - ${mysql.connector.version} + 8.0.32 diff --git a/shardingsphere101/shardingsphere-2fastcode/README.md b/shardingsphere101/shardingsphere-2fastcode/README.md index 31f2a64e..6211e9da 100644 --- a/shardingsphere101/shardingsphere-2fastcode/README.md +++ b/shardingsphere101/shardingsphere-2fastcode/README.md @@ -1,4 +1,2 @@ -### 本案例对应的文章教程 - -[SpringBoot 2 种方式快速实现分库分表,轻松拿捏!](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247504158&idx=1&sn=37bdbb8de72068a95602a16f5451cd98&chksm=9b8641e3acf1c8f5508bbc52dba2e304ca465440800caac465a6e7509579ff2c3b088ab17b9d&token=755618913&lang=zh_CN#rd) +yml 和 Java编码的方式实现了简单的分库分表 \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-2fastcode/pom.xml b/shardingsphere101/shardingsphere-2fastcode/pom.xml index 379520bf..ac3ea2e6 100644 --- a/shardingsphere101/shardingsphere-2fastcode/pom.xml +++ b/shardingsphere101/shardingsphere-2fastcode/pom.xml @@ -12,10 +12,8 @@ shardingsphere-2fastcode - - org.springframework.boot - spring-boot-starter-data-jpa - + + diff --git a/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java b/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java index 14330559..06c262c9 100644 --- a/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java +++ b/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java @@ -1,95 +1,95 @@ -//package com.shardingsphere_101.conf; -// -//import com.zaxxer.hikari.HikariDataSource; -//import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory; -//import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration; -//import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -// -//import javax.sql.DataSource; -//import java.sql.SQLException; -//import java.util.*; -// -///** -// * 公众号:程序员小富 -// */ -//@Configuration -//public class ShardingConfiguration { -// -// /** -// * 配置分片数据源 -// * 公众号:程序员小富 -// */ -// @Bean -// public DataSource getShardingDataSource() throws SQLException { -// Map dataSourceMap = new HashMap<>(); -// dataSourceMap.put("db0", dataSource0()); -// dataSourceMap.put("db1", dataSource1()); -// -// // 分片rules规则配置 -// ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); -// -// shardingRuleConfig.setBroadcastTables(Collections.singletonList("t_city_dict")); -// shardingRuleConfig.setShardingAlgorithms(getShardingAlgorithms()); -// // 配置 t_order 表分片规则 -// ShardingTableRuleConfiguration orderTableRuleConfig = new ShardingTableRuleConfiguration("t_order", "db${0..1}.t_order_${0..2}"); -// orderTableRuleConfig.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "table-inline")); -// orderTableRuleConfig.setDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "database-inline")); -// shardingRuleConfig.getTables().add(orderTableRuleConfig); -// -// // 是否在控制台输出解析改造后真实执行的 SQL -// Properties properties = new Properties(); -// properties.setProperty("sql-show", "true"); -// // 创建 ShardingSphere 数据源 -// return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, Collections.singleton(shardingRuleConfig), properties); -// } -// -// /** -// * 配置数据源1 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource0() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/shardingsphere-db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置数据源2 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource1() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/shardingsphere-db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置分片算法 -// * 公众号:程序员小富 -// */ -// private Map getShardingAlgorithms() { -// Map shardingAlgorithms = new LinkedHashMap<>(); -// -// // 自定义分库算法 -// Properties databaseAlgorithms = new Properties(); -// databaseAlgorithms.setProperty("algorithm-expression", "db$->{order_id % 2}"); -// shardingAlgorithms.put("database-inline", new AlgorithmConfiguration("INLINE", databaseAlgorithms)); -// -// // 自定义分表算法 -// Properties tableAlgorithms = new Properties(); -// tableAlgorithms.setProperty("algorithm-expression", "t_order_$->{order_id % 3}"); -// shardingAlgorithms.put("table-inline", new AlgorithmConfiguration("INLINE", tableAlgorithms)); -// -// return shardingAlgorithms; -// } -//} +package com.shardingsphere_101.conf; + +import com.zaxxer.hikari.HikariDataSource; +import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory; +import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration; +import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; +import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; +import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.sql.DataSource; +import java.sql.SQLException; +import java.util.*; + +/** + * 公众号:程序员小富 + */ +@Configuration +public class ShardingConfiguration { + + /** + * 配置分片数据源 + * 公众号:程序员小富 + */ + @Bean + public DataSource getShardingDataSource() throws SQLException { + Map dataSourceMap = new HashMap<>(); + dataSourceMap.put("db0", dataSource0()); + dataSourceMap.put("db1", dataSource1()); + + // 分片rules规则配置 + ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); + + shardingRuleConfig.setShardingAlgorithms(getShardingAlgorithms()); + + // 配置 t_order 表分片规则 + ShardingTableRuleConfiguration orderTableRuleConfig = new ShardingTableRuleConfiguration("t_order", "db${0..1}.t_order_${0..2}"); + orderTableRuleConfig.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "table-inline")); + orderTableRuleConfig.setDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "database-inline")); + shardingRuleConfig.getTables().add(orderTableRuleConfig); + + // 是否在控制台输出解析改造后真实执行的 SQL + Properties properties = new Properties(); + properties.setProperty("sql-show", "true"); + // 创建 ShardingSphere 数据源 + return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, Collections.singleton(shardingRuleConfig), properties); + } + + /** + * 配置数据源1 + * 公众号:程序员小富 + */ + public DataSource dataSource0() { + HikariDataSource dataSource = new HikariDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/shardingsphere-db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); + dataSource.setUsername("root"); + dataSource.setPassword("123456"); + return dataSource; + } + + /** + * 配置数据源2 + * 公众号:程序员小富 + */ + public DataSource dataSource1() { + HikariDataSource dataSource = new HikariDataSource(); + dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); + dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/shardingsphere-db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); + dataSource.setUsername("root"); + dataSource.setPassword("123456"); + return dataSource; + } + + /** + * 配置分片算法 + * 公众号:程序员小富 + */ + private Map getShardingAlgorithms() { + Map shardingAlgorithms = new LinkedHashMap<>(); + + // 自定义分库算法 + Properties databaseAlgorithms = new Properties(); + databaseAlgorithms.setProperty("algorithm-expression", "db$->{order_id % 2}"); + shardingAlgorithms.put("database-inline", new AlgorithmConfiguration("INLINE", databaseAlgorithms)); + + // 自定义分表算法 + Properties tableAlgorithms = new Properties(); + tableAlgorithms.setProperty("algorithm-expression", "t_order_$->{order_id % 3}"); + shardingAlgorithms.put("table-inline", new AlgorithmConfiguration("INLINE", tableAlgorithms)); + + return shardingAlgorithms; + } +} diff --git a/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/controller/OrderController.java b/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/controller/OrderController.java index f11c19b8..9c103db6 100644 --- a/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/controller/OrderController.java +++ b/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/controller/OrderController.java @@ -2,10 +2,10 @@ import com.shardingsphere_101.entity.Order; import com.shardingsphere_101.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; -import javax.annotation.Resource; import java.util.List; /** @@ -16,7 +16,7 @@ @RestController @RequestMapping("/order") public class OrderController { - @Resource + @Autowired private OrderService orderService; /** diff --git a/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java b/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java index 78d9af87..eab3f5dd 100644 --- a/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java +++ b/shardingsphere101/shardingsphere-2fastcode/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java @@ -3,13 +3,13 @@ import com.shardingsphere_101.entity.Order; import com.shardingsphere_101.repository.OrderRepository; import com.shardingsphere_101.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.annotation.Resource; import java.util.Date; import java.util.List; import java.util.stream.LongStream; @@ -21,7 +21,7 @@ */ @Service public class OrderServiceImpl implements OrderService { - @Resource + @Autowired private OrderRepository orderRepository; @Override diff --git a/shardingsphere101/shardingsphere-algorithms/README.md b/shardingsphere101/shardingsphere-algorithms/README.md deleted file mode 100644 index 16e1b11b..00000000 --- a/shardingsphere101/shardingsphere-algorithms/README.md +++ /dev/null @@ -1,6 +0,0 @@ - - -### 本案例对应的文章教程 - -[一口气搞懂分库分表 12 种分片算法,大厂都在用](https://mp.weixin.qq.com/s/HAoCXGoGCbDt9ZaWCu-qIw) - diff --git a/shardingsphere101/shardingsphere-algorithms/pom.xml b/shardingsphere101/shardingsphere-algorithms/pom.xml deleted file mode 100644 index db0bfbd2..00000000 --- a/shardingsphere101/shardingsphere-algorithms/pom.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - 4.0.0 - - com.shardingsphere101 - shardingsphere101 - 0.0.1-SNAPSHOT - - shardingsphere-algorithms - 0.0.1-SNAPSHOT - shardingsphere-algorithms - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/AlgorithmsApplication.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/AlgorithmsApplication.java deleted file mode 100644 index 66459f23..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/AlgorithmsApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.shardingsphere_101; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class AlgorithmsApplication { - - public static void main(String[] args) { - SpringApplication.run(AlgorithmsApplication.class, args); - } - -} diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderComplexCustomAlgorithm.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderComplexCustomAlgorithm.java deleted file mode 100644 index 9c3b820b..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderComplexCustomAlgorithm.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.shardingsphere_101.algorithm; - -import com.alibaba.fastjson.JSON; -import com.google.common.collect.Range; -import lombok.extern.slf4j.Slf4j; -import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm; -import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; - -/** - * 自定义复合分片算法 - * - * @author 公众号:程序员小富 - * @date 2024/03/22 11:02 - */ -@Slf4j -public class OrderComplexCustomAlgorithm implements ComplexKeysShardingAlgorithm { - - /** - * 复合分片算法进入,支持>,>=, <=,<,=,IN 和 BETWEEN AND 等操作符 - * - * @param availableTargetNames 所有分片表的集合 - * @param complexKeysShardingValue 多个分片健的值,并SQL中解析出来的分片值 - */ - @Override - public Collection doSharding(Collection availableTargetNames, - ComplexKeysShardingValue complexKeysShardingValue) { - - /** - * 分库策略使用时:availableTargetNames 参数数据为分片库的集合 ["db0","db1"] - * 分表策略使用时:availableTargetNames 参数数据为分片库的集合 ["t_order_0","t_order_1","t_order_2"] - */ - log.info("进入复合分片:complex availableTargetNames:{}", JSON.toJSONString(availableTargetNames)); - - // 多分片健和其对应的分片健范围值 - Map> columnNameAndRangeValuesMap = complexKeysShardingValue.getColumnNameAndRangeValuesMap(); - log.info("进入复合分片:columnNameAndRangeValuesMap:{}", JSON.toJSONString(columnNameAndRangeValuesMap)); - - columnNameAndRangeValuesMap.forEach((columnName, range) -> { - range.lowerEndpoint(); - range.upperEndpoint(); - // 分片健 - log.info("进入复合分片:columnName:{}", columnName); - // 分片健范围值 - log.info("进入复合分片:range:{}", JSON.toJSONString(range)); - }); - - // 多分片健和其对应的分片健值 - Map> columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap(); - log.info("进入复合分片:columnNameAndShardingValuesMap:{}", JSON.toJSONString(columnNameAndShardingValuesMap)); - columnNameAndShardingValuesMap.forEach((columnName, shardingValues) -> { - // 分片健 - log.info("进入复合分片:columnName:{}", columnName); - // 分片健值 - log.info("进入复合分片:shardingValues:{}", JSON.toJSONString(shardingValues)); - }); - - return null; - } - - @Override - public Properties getProps() { - - Properties props = new Properties(); - // 设置算法所需的配置信息 - props.setProperty("key1", "value1"); - props.setProperty("key2", "value2"); - return props; - } - - /** - * 初始化配置 - * - * @param properties - */ - @Override - public void init(Properties properties) { - Object prop = properties.get("aaaaaa"); - log.info("自定义配置信息:{}", JSON.toJSONString(prop)); - } -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderHintCustomAlgorithm.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderHintCustomAlgorithm.java deleted file mode 100644 index c4414cda..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderHintCustomAlgorithm.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.shardingsphere_101.algorithm; - -import lombok.extern.slf4j.Slf4j; -import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm; -import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Properties; - -/** - * 自定义强制路由分片算法 - * - * @author 公众号:程序员小富 - * @date 2024/03/22 11:02 - */ -@Slf4j -public class OrderHintCustomAlgorithm implements HintShardingAlgorithm { - - @Override - public Collection doSharding(Collection availableTargetNames, HintShardingValue hintShardingValue) { - - /** - * 获取到设置的分表或者分库的分片值 - * 指定分表时的分片值 hintManager.addTableShardingValue("t_order",2L); - * 指定分库时的分片值 hintManager.addDatabaseShardingValue("t_order", 100L); - */ - Collection values = hintShardingValue.getValues(); - Collection result = new ArrayList<>(); - // 从所有分片表中得到合适的分片表 - for (String each : availableTargetNames) { - for (Long value : values) { - Long mod = value % availableTargetNames.size(); - if (each.endsWith(String.valueOf(mod))) { - result.add(each); - } - } - } - return result; - } - - @Override - public Properties getProps() { - return null; - } - - @Override - public void init(Properties properties) { - - } -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderStandardCustomAlgorithm.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderStandardCustomAlgorithm.java deleted file mode 100644 index a7e4e817..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/algorithm/OrderStandardCustomAlgorithm.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.shardingsphere_101.algorithm; - -import com.alibaba.fastjson.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue; -import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue; -import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm; - -import java.util.Collection; -import java.util.Collections; -import java.util.Properties; - -/** - * 自定义标准分片算法 - * - * @author 公众号:程序员小富 - * @date 2024/03/22 11:02 - */ -@Slf4j -public class OrderStandardCustomAlgorithm implements StandardShardingAlgorithm { - - /** - * 精准分片进入 sql中有 = 和 in 等操作符会执行 - * - * @param availableTargetNames 所有分片表的集合 - * @param preciseShardingValue 分片健的值,SQL中解析出来的分片值 - */ - @Override - public String doSharding(Collection availableTargetNames, - PreciseShardingValue preciseShardingValue) { - /** - * 分库策略使用时:availableTargetNames 参数数据为分片库的集合 ["db0","db1"] - * 分表策略使用时:availableTargetNames 参数数据为分片库的集合 ["t_order_0","t_order_1","t_order_2"] - */ - log.info("进入精准分片 precise availableTargetNames:{}", JSON.toJSONString(availableTargetNames)); - - /** - * 分库策略使用时: shardingValue 参数数据:{"columnName":"order_id","dataNodeInfo":{"paddingChar":"0","prefix":"db","suffixMinLength":1},"logicTableName":"t_order","value":1} - * 分表策略使用时: shardingValue 参数数据:{"columnName":"order_id","dataNodeInfo":{"paddingChar":"0","prefix":"t_order_","suffixMinLength":1},"logicTableName":"t_order","value":1} - */ - log.info("进入精准分片 preciseShardingValue:{}", JSON.toJSONString(preciseShardingValue)); - int tableSize = availableTargetNames.size(); - // 真实表的前缀 - String tablePrefix = preciseShardingValue.getDataNodeInfo().getPrefix(); - // 分片健的值 - long orderId = preciseShardingValue.getValue(); - // 对分片健取模后确定位置 - long mod = orderId % tableSize; - return tablePrefix + mod; - } - - /** - * 范围分片进入 sql中有 between 和 < > 等操作符会执行 - * - * @param availableTargetNames 所有分片表的集合 - * @param rangeShardingValue 分片健的值,SQL中解析出来的分片值 - * @return - */ - @Override - public Collection doSharding(Collection availableTargetNames, - RangeShardingValue rangeShardingValue) { - /** - * 分库策略使用时:availableTargetNames 参数数据为分片库的集合 ["db0","db1"] - * 分表策略使用时:availableTargetNames 参数数据为分片库的集合 ["t_order_0","t_order_1","t_order_2"] - */ - log.info("进入范围分片:range availableTargetNames:{}", JSON.toJSONString(availableTargetNames)); - - - /** - * 分库策略使用时 shardingValue 参数数据:{"columnName":"order_id","dataNodeInfo":{"paddingChar":"0","prefix":"db","suffixMinLength":1},"logicTableName":"t_order","valueRange":{"empty":false}} - * 分表策略使用时 shardingValue 参数数据:{"columnName":"order_id","dataNodeInfo":{"paddingChar":"0","prefix":"t_order_","suffixMinLength":1},"logicTableName":"t_order","valueRange":{"empty":false}} - */ - log.info("进入范围分片:rangeShardingValue:{}", JSON.toJSONString(rangeShardingValue)); - - Properties props = getProps(); - log.info("进入范围分片:rangeShardingValue props:{}", JSON.toJSONString(props)); - // 分片健值的上下边界 -// Range valueRange = rangeShardingValue.getValueRange(); -// Long lower = valueRange.lowerEndpoint(); -// // 分片健值的上边界 -// Long upper = valueRange.upperEndpoint(); -// // 真实表的前缀 -// String tablePrefix = rangeShardingValue.getDataNodeInfo().getPrefix(); -// if (lower != null && upper != null) { -// // 分片健的值 -// long orderId = upper - lower; -// // 对分片健取模后确定位置 -// long mod = orderId % availableTargetNames.size(); -// return Arrays.asList(tablePrefix + mod); -// } - // - return Collections.singletonList("t_order_0"); - } - - @Override - public Properties getProps() { - Properties props = new Properties(); - // 设置算法所需的配置信息 - props.setProperty("key1", "value1"); - props.setProperty("key2", "value2"); - return props; - } - - /** - * 初始化配置 - * - * @param properties - */ - @Override - public void init(Properties properties) { - Object prop = properties.get("cccccc"); - log.info("自定义配置信息:{}", JSON.toJSONString(prop)); - } -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java deleted file mode 100644 index 33736b75..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java +++ /dev/null @@ -1,96 +0,0 @@ -//package com.shardingsphere_101.config; -// -//import com.zaxxer.hikari.HikariDataSource; -//import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory; -//import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration; -//import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -// -//import javax.sql.DataSource; -//import java.sql.SQLException; -//import java.util.*; -// -///** -// * 公众号:程序员小富 -// */ -//@Configuration -//public class ShardingConfiguration { -// -// /** -// * 配置分片数据源 -// * 公众号:程序员小富 -// */ -// @Bean -// public DataSource getShardingDataSource() throws SQLException { -// Map dataSourceMap = new HashMap<>(); -// dataSourceMap.put("db0", dataSource0()); -// dataSourceMap.put("db1", dataSource1()); -// -// // 分片rules规则配置 -// ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); -// -// // 分片算法 -// shardingRuleConfig.setShardingAlgorithms(getShardingAlgorithms()); -// // 配置 t_order 表分片规则 -// ShardingTableRuleConfiguration orderTableRuleConfig = new ShardingTableRuleConfiguration("t_order", "db${0..1}.t_order_${1..1000}"); -// orderTableRuleConfig.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_table_algorithms")); -// orderTableRuleConfig.setDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_database_algorithms")); -// shardingRuleConfig.getTables().add(orderTableRuleConfig); -// -// // 是否在控制台输出解析改造后真实执行的 SQL -// Properties properties = new Properties(); -// properties.setProperty("sql-show", "true"); -// -// // 创建 ShardingSphere 数据源 -// return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, Collections.singleton(shardingRuleConfig), properties); -// } -// -// /** -// * 配置数据源1 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource0() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置数据源2 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource1() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置分片算法 -// * 公众号:程序员小富 -// */ -// private Map getShardingAlgorithms() { -// Map shardingAlgorithms = new LinkedHashMap<>(); -// -// // 自定义分库算法 -// Properties databaseAlgorithms = new Properties(); -// databaseAlgorithms.setProperty("algorithm-expression", "db$->{order_id % 2}"); -// shardingAlgorithms.put("t_order_database_algorithms", new AlgorithmConfiguration("INLINE", databaseAlgorithms)); -// -// // 自定义分表算法 -// Properties tableAlgorithms = new Properties(); -// tableAlgorithms.setProperty("algorithm-expression", "db$->{order_id % 1000}"); -// shardingAlgorithms.put("t_order_table_algorithms", new AlgorithmConfiguration("INLINE", tableAlgorithms)); -// -// return shardingAlgorithms; -// } -//} diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/controller/PingController.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/controller/PingController.java deleted file mode 100644 index f60d3ffc..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/controller/PingController.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.shardingsphere_101.controller; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class PingController { - - @RequestMapping("/ping") - public String ping() { - return "pong"; - } -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/dao/OrderMapper.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/dao/OrderMapper.java deleted file mode 100644 index 06f066e4..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/dao/OrderMapper.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.shardingsphere_101.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.shardingsphere_101.entity.OrderPo; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface OrderMapper extends BaseMapper { - -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/entity/OrderPo.java b/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/entity/OrderPo.java deleted file mode 100644 index ef9fdcde..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/java/com/shardingsphere_101/entity/OrderPo.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.shardingsphere_101.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.util.Date; - -/** - * 订单实体类 - */ -@Data -@TableName("t_order") -public class OrderPo { - - private Long Id; - private Long orderId; - private Long userId; - private String orderNumber; - private Long customerId; - private Date orderDate; - private BigDecimal totalAmount; - private String intervalValue; -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-complex-line.yml b/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-complex-line.yml deleted file mode 100644 index 6e8a550f..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-complex-line.yml +++ /dev/null @@ -1,75 +0,0 @@ -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - # 具体规则配置 - rules: - sharding: - # 自动分片表规则配置 -# auto-tables: -# t_order: -# actual-data-sources: db$->{0..1} -# sharding-strategy: -# standard: -# sharding-column: order_id -# sharding-algorithm-name: t_order_database_complex_inline_algorithms - # 分片算法定义 - sharding-algorithms: - t_order_database_complex_inline_algorithms: - type: complex_inline - props: - sharding-columns: order_id, user_id # 分片列名称,多个列用逗号分隔。 - algorithm-expression: db$->{(order_id + user_id) % 2} # 分片算法的行表达式 - allow-range-query-with-inline-sharding: false # 是否允许范围查询。注意:范围查询会无视分片策略,进行全路由,默认 false - t_order_table_complex_inline: - type: COMPLEX_INLINE - props: - sharding-columns: order_id, user_id # 分片列名称,多个列用逗号分隔。 - algorithm-expression: t_order_$->{ (order_id + user_id) % 3 } # 分片算法的行表达式 - allow-range-query-with-inline-sharding: false # 是否允许范围查询。注意:范围查询会无视分片策略,进行全路由,默认 false - # 分布式序列算法配置 - key-generators: - t_order_snowflake: - # 分布式序列算法(雪花算法:SNOWFLAKE; UUID:UUID)(注:UUID没有props配置) - type: SNOWFLAKE - # 分布式序列算法属性配置 - props: - # 工作机器唯一标识 - worker-id: 1 - tables: - # 逻辑表名称 - t_order: - # 数据节点:数据库.分片表 - actual-data-nodes: db$->{0..1}.t_order_${0..2} - # 分库策略 - database-strategy: - complex: - shardingColumns: order_id, user_id - sharding-algorithm-name: t_order_database_complex_inline_algorithms - # 分表策略 - table-strategy: - complex: - shardingColumns: order_id, user_id - sharding-algorithm-name: t_order_table_complex_inline - keyGenerateStrategy: - column: id - keyGeneratorName: t_order_snowflake - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-custom-standard.yml b/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-custom-standard.yml deleted file mode 100644 index 3456b59f..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-custom-standard.yml +++ /dev/null @@ -1,76 +0,0 @@ -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - # 具体规则配置 - rules: - sharding: - # 自动分片表规则配置 - # auto-tables: - # t_order: - # actual-data-sources: db$->{0..1} - # sharding-strategy: - # standard: - # sharding-column: order_id - # sharding-algorithm-name: t_order_table_cosid_mod - # 分片算法定义 - sharding-algorithms: - # 12、自定义 STANDARD 标准算法 - t_order_standard_custom_algorithm: - type: CLASS_BASED - props: - # 分片策略 - strategy: standard - # 分片算法类 - algorithmClassName: com.shardingsphere_101.algorithm.OrderStandardCustomAlgorithm - # 自定义属性 - prop: - aaaaaa: 123456 - bbbbbb: 654321 - - # 分布式序列算法配置 - key-generators: - t_order_snowflake: - # 分布式序列算法(雪花算法:SNOWFLAKE; UUID:UUID)(注:UUID没有props配置) - type: SNOWFLAKE - # 分布式序列算法属性配置 - props: - # 工作机器唯一标识 - worker-id: 1 - tables: - # 逻辑表名称 - t_order: - # 数据节点:数据库.分片表 - actual-data-nodes: db$->{0..1}.t_order_${0..2} - # 分库策略 - database-strategy: - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_database_mod - # 分表策略 - table-strategy: - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_standard_custom_algorithm - keyGenerateStrategy: - column: id - keyGeneratorName: t_order_snowflake - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-hint-inline.yml b/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-hint-inline.yml deleted file mode 100644 index 83965e57..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-hint-inline.yml +++ /dev/null @@ -1,62 +0,0 @@ -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - # 具体规则配置 - rules: - sharding: - # 分片算法定义 - sharding-algorithms: - # Hint 行表达式分片算法 - t_order_database_hint_inline: - type: HINT_INLINE - props: - algorithm-expression: db$->{Integer.valueOf(value) % 2} # 分片算法的行表达式,默认值${value} - t_order_table_hint_inline: - type: HINT_INLINE - props: - algorithm-expression: t_order_$->{Integer.valueOf(value) % 3} # 分片算法的行表达式,默认值${value} - # 分布式序列算法配置 - key-generators: - t_order_snowflake: - # 分布式序列算法(雪花算法:SNOWFLAKE; UUID:UUID)(注:UUID没有props配置) - type: SNOWFLAKE - # 分布式序列算法属性配置 - props: - # 工作机器唯一标识 - worker-id: 1 - tables: - # 逻辑表名称 - t_order: - # 数据节点:数据库.分片表 - actual-data-nodes: db$->{0..1}.t_order_${0..2} - # 分库策略 - database-strategy: - hint: - sharding-algorithm-name: t_order_database_hint_inline - # 分表策略 - table-strategy: - hint: - sharding-algorithm-name: t_order_table_hint_inline - keyGenerateStrategy: - column: id - keyGeneratorName: t_order_snowflake - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-interval.yml b/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-interval.yml deleted file mode 100644 index 81cb4546..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application-interval.yml +++ /dev/null @@ -1,59 +0,0 @@ -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - # 具体规则配置 - rules: - sharding: - # 分片算法定义 - sharding-algorithms: - t_order_database_mod: - type: MOD - props: - sharding-count: 2 # 指定分片数量 - t_order_table_interval: - type: INTERVAL - props: - datetime-pattern: "yyyy-MM-dd HH:mm:ss" # 分片字段格式 - datetime-lower: "2024-01-01 00:00:00" # 范围下限 - datetime-upper: "2024-06-30 23:59:59" # 范围上限 - sharding-suffix-pattern: "yyyyMM" # 分片名后缀,可以是MM,yyyyMMdd等。 - datetime-interval-amount: 1 # 分片间隔,这里指一个月 - datetime-interval-unit: "MONTHS" # 分片间隔单位 - tables: - # 逻辑表名称 - t_order: - # 数据节点:数据库.分片表 - actual-data-nodes: db$->{0..1}.t_order_${202401..202406} - # 分库策略 - database-strategy: - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_database_mod - # 分表策略 - table-strategy: - standard: - sharding-column: interval_value - sharding-algorithm-name: t_order_table_interval - keyGenerateStrategy: - column: id - keyGeneratorName: t_order_snowflake - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application.yml b/shardingsphere101/shardingsphere-algorithms/src/main/resources/application.yml deleted file mode 100644 index 9dce0cb8..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/main/resources/application.yml +++ /dev/null @@ -1,200 +0,0 @@ -server: - port: 10202 -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - # 具体规则配置 - rules: - sharding: - # 自动分片表规则配置 - # auto-tables: - # t_order: - # actual-data-sources: db$->{0..1} - # sharding-strategy: - # standard: - # sharding-column: order_id - # sharding-algorithm-name: t_order_table_cosid_mod - # 分片算法定义 - sharding-algorithms: - - t_order_database_algorithms: - # 分片算法类型 - type: INLINE - props: # 自定义参数 - algorithm-expression: db$->{order_id % 2} - t_order_table_algorithms: - type: INLINE - props: - algorithm-expression: t_order_$->{order_id % 3} - t_order_database_mod: - type: MOD - props: - sharding-count: 2 # 指定分片数量 - # 内置分片算法 - # 1、取模分片算法 - t_order_table_mod: - type: MOD - props: - sharding-count: 3 # 指定分片数量 - # 2、哈希取模分片算法 - t_order_table_hash_mod: - type: HASH_MOD - props: - sharding-count: 6 # 指定分片数量 - # 3、基于分片容量的范围分片算法 [1,2) 第一张表 [2,12) 第二张表 [12,20) 第三张表 [20,♾️) 第四张表 - t_order_table_volume_range: - type: VOLUME_RANGE - props: - range-lower: 2 # 范围下界,超过边界的数据会报错 - range-upper: 20 # 范围上界,超过边界的数据会报错 - sharding-volume: 10 # 分片容量 - # 4、基于分片边界的范围分片算法,[1,10) 第一张表 [10,20) 第二张表 [20,30) 第三张表 [30,40) 第四张表 [40,♾️) 第五张表 - t_order_table_boundary_range: - type: BOUNDARY_RANGE - props: - sharding-ranges: 10,20,30,40 # 分片的范围边界,多个范围边界以逗号分隔 - # 5、自动时间段分片算法 - t_order_table_auto_interval: - type: AUTO_INTERVAL - props: - datetime-lower: '2024-01-01 00:00:00' # 分片的起始时间范围,时间戳格式:yyyy-MM-dd HH:mm:ss - datetime-upper: '2026-01-01 00:00:00' # 分片的结束时间范围,时间戳格式:yyyy-MM-dd HH:mm:ss - sharding-seconds: 31536000 # 单一分片所能承载的最大时间,单位:秒,允许分片键的时间戳格式的秒带有时间精度,但秒后的时间精度会被自动抹去 - # 标准分片算法 - # 6、行表达式分片算法 - t_order_table_inline: - type: INLINE - props: - algorithm-expression: t_order_$->{order_id % 3} # 分片算法的行表达式 - allow-range-query-with-inline-sharding: false # 是否允许范围查询。注意:范围查询会无视分片策略,进行全路由,默认 false - - # 7、时间范围分片算法 - t_order_table_interval: - type: INTERVAL - props: - datetime-pattern: "yyyy-MM-dd HH:mm:ss" # 分片字段格式 - datetime-lower: "2024-01-01 00:00:00" # 范围下限 - datetime-upper: "2024-06-30 23:59:59" # 范围上限 - sharding-suffix-pattern: "yyyyMM" # 分片名后缀,可以是MM,yyyyMMdd等。 - datetime-interval-amount: 1 # 分片间隔,这里指一个月 - datetime-interval-unit: "MONTHS" # 分片间隔单位 - - # 8、基于 CosId 的取模分片算法 - t_order_table_cosid_mod: - type: COSID_MOD - props: - mod: 3 # 分片数量 - logic-name-prefix: t_order_ # 分片数据源或真实表的前缀格式 - - # 9、基于 CosId 的固定时间范围的分片算法 - t_order_table_cosid_interval: - type: COSID_INTERVAL - props: - zone-id: "Asia/Shanghai" # 时区,必须遵循 java.time.ZoneId 的所含值。 例如:Asia/Shanghai - logic-name-prefix: t_order_ # 分片数据源或真实表的前缀格式 - sharding-suffix-pattern: "yyyyMM" # 分片数据源或真实表的后缀格式,必须遵循 Java DateTimeFormatter 的格式,必须和 datetime-interval-unit 保持一致。例如:yyyyMM - datetime-lower: "2024-01-01 00:00:00" # 时间分片下界值,格式与 yyyy-MM-dd HH:mm:ss 的时间戳格式一致 - datetime-upper: "2024-12-31 00:00:00" # 时间分片上界值,格式与 yyyy-MM-dd HH:mm:ss 的时间戳格式一致 - datetime-interval-unit: "MONTHS" # 分片键时间间隔单位,必须遵循 Java ChronoUnit 的枚举值。例如:MONTHS - datetime-interval-amount: 1 # 分片键时间间隔,超过该时间间隔将进入下一分片 - # 10、基于 CosId 的雪花ID固定时间范围的分片算法 - t_order_table_cosid_interval_snowflake: - type: COSID_INTERVAL_SNOWFLAKE - props: - zone-id: "Asia/Shanghai" # 时区,必须遵循 java.time.ZoneId 的所含值。 例如:Asia/Shanghai - logic-name-prefix: t_order_ # 分片数据源或真实表的前缀格式 - sharding-suffix-pattern: "yyyyMM" # 分片数据源或真实表的后缀格式,必须遵循 Java DateTimeFormatter 的格式,必须和 datetime-interval-unit 保持一致。例如:yyyyMM - datetime-lower: "2024-01-01 00:00:00" # 时间分片下界值,格式与 yyyy-MM-dd HH:mm:ss 的时间戳格式一致 - datetime-upper: "2024-12-31 00:00:00" # 时间分片上界值,格式与 yyyy-MM-dd HH:mm:ss 的时间戳格式一致 - datetime-interval-unit: "MONTHS" # 分片键时间间隔单位,必须遵循 Java ChronoUnit 的枚举值。例如:MONTHS - datetime-interval-amount: 1 # 分片键时间间隔,超过该时间间隔将进入下一分片 - - # 11、Hint 行表达式分片算法 - t_order_database_hint_inline: - type: HINT_INLINE - props: - algorithm-expression: db$->{Integer.valueOf(value) % 2} # 分片算法的行表达式,默认值${value} - t_order_table_hint_inline: - type: HINT_INLINE - props: - algorithm-expression: t_order_$->{Integer.valueOf(value) % 3} # 分片算法的行表达式,默认值${value} - - # 12、自定义 STANDARD 标准算法 - t_order_standard_custom_algorithm: - type: CLASS_BASED - props: - # 分片策略 - strategy: standard - # 分片算法类 - algorithmClassName: com.shardingsphere_101.algorithm.OrderStandardCustomAlgorithm - # 自定义属性 - cccccc: cccccc - - # 13、自定义 complex 标准算法 - t_order_complex_custom_algorithm: - type: CLASS_BASED - props: - # 分片策略 - strategy: complex - # 分片算法类 - algorithmClassName: com.shardingsphere_101.algorithm.OrderComplexCustomAlgorithm - # 自定义属性 - aaaaaa: aaaaaa - # 14、自定义 hint 标准算法 - t_order_hint_custom_algorithm: - type: CLASS_BASED - props: - # 分片策略 - strategy: hint - # 分片算法类 - algorithmClassName: com.shardingsphere_101.algorithm.OrderHintCustomAlgorithm - # 自定义属性 - bbbbbb: bbbbbb - - # 分布式序列算法配置 - key-generators: - t_order_snowflake: - # 分布式序列算法(雪花算法:SNOWFLAKE; UUID:UUID)(注:UUID没有props配置) - type: SNOWFLAKE - # 分布式序列算法属性配置 - props: - # 工作机器唯一标识 - worker-id: 1 - tables: - # 逻辑表名称 - t_order: - # 数据节点:数据库.分片表 - actual-data-nodes: db$->{0..1}.t_order_${0..2} - # 分库策略 - database-strategy: - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_database_mod - # 分表策略 - table-strategy: - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_table_mod - keyGenerateStrategy: - column: id - keyGeneratorName: t_order_snowflake - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-algorithms/src/test/java/com/shardingsphere_101/CustomShardingAlgorithmsTests.java b/shardingsphere101/shardingsphere-algorithms/src/test/java/com/shardingsphere_101/CustomShardingAlgorithmsTests.java deleted file mode 100644 index c901dcd8..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/test/java/com/shardingsphere_101/CustomShardingAlgorithmsTests.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.shardingsphere_101; - -import com.alibaba.fastjson.JSON; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.shardingsphere_101.dao.OrderMapper; -import com.shardingsphere_101.entity.OrderPo; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomUtils; -import org.apache.shardingsphere.infra.hint.HintManager; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.annotation.Resource; -import java.math.BigDecimal; -import java.util.Date; -import java.util.List; - -/** - * 自动义分片算法测试类 - * - * @author 公众号:程序员小富 - * @date 2023/12/31 17:25 - */ -@Slf4j -@DisplayName("自定义分片算法测试类") -@SpringBootTest -class CustomShardingAlgorithmsTests { - - @Resource - private JdbcTemplate jdbcTemplate; - - @Resource - private OrderMapper orderMapper; - - @DisplayName("测试自定义标准分片算法插入数据") - @Test - public void orderComplexCustomAlgorithmTest() { - - int randomId = RandomUtils.nextInt(); - OrderPo order = new OrderPo(); - order.setOrderId(20L); - order.setUserId(100L); - order.setOrderNumber(String.valueOf(randomId)); - order.setCustomerId((long) randomId); - order.setOrderDate(new Date()); - order.setTotalAmount(new BigDecimal("0")); - order.setIntervalValue("2024-03-01 00:00:00"); - orderMapper.insert(order); - } - - /** - * 查询标准策略 - * - * @author 公众号:程序员小富 - */ - @DisplayName("自动义分片算法-范围查询") - @Test - public void queryTableTest() { - QueryWrapper queryWrapper = new QueryWrapper() -// .le("order_id", 10) -// .ge("order_id", 1) - .eq("user_id", 1); - queryWrapper.orderByAsc("order_id"); -// .eq("id", 1771023476480950274L); - List orderPos = orderMapper.selectList(queryWrapper); - log.info("查询结果:{}", JSON.toJSONString(orderPos)); - } - - /** - * Hint 强制路由查询 - * - * @author 公众号:程序员小富 - */ - @DisplayName("Hint 自动义分片算法-范围查询") - @Test - public void queryHintTableTest() { - - HintManager hintManager = HintManager.getInstance(); - // 指定分表时的分片值 - hintManager.addTableShardingValue("t_order",2L); - // 指定分库时的分片值 - hintManager.addDatabaseShardingValue("t_order", 100L); - - QueryWrapper queryWrapper = new QueryWrapper() - .eq("user_id", 20).eq("order_id", 10); - List orderPos = orderMapper.selectList(queryWrapper); - log.info("查询结果:{}", JSON.toJSONString(orderPos)); - } -} diff --git a/shardingsphere101/shardingsphere-algorithms/src/test/java/com/shardingsphere_101/ShardingAlgorithmsTests.java b/shardingsphere101/shardingsphere-algorithms/src/test/java/com/shardingsphere_101/ShardingAlgorithmsTests.java deleted file mode 100644 index 1e539378..00000000 --- a/shardingsphere101/shardingsphere-algorithms/src/test/java/com/shardingsphere_101/ShardingAlgorithmsTests.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.shardingsphere_101; - -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.shardingsphere_101.dao.OrderMapper; -import com.shardingsphere_101.entity.OrderPo; -import org.apache.commons.lang3.RandomUtils; -import org.apache.shardingsphere.infra.hint.HintManager; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.annotation.Resource; -import java.math.BigDecimal; -import java.util.Date; - -/** - * 分片算法测试类 - * - * @author 公众号:程序员小富 - * @date 2023/12/31 17:25 - */ -@DisplayName("分片算法测试类") -@SpringBootTest -class ShardingAlgorithmsTests { - - @Resource - private JdbcTemplate jdbcTemplate; - - @Resource - private OrderMapper orderMapper; - - /** - * 执行创建逻辑表的SQL,会根据AutoTables的配置自动在对应的数据源内创建分片表 - * - * @author 公众号:程序员小富 - */ - @DisplayName("创建分片表") - @Test - public void autoCreateOrderTableAlgorithmsTest() { - jdbcTemplate.execute("CREATE TABLE `t_order` (\n" + " `id` bigint(20) NOT NULL,\n" + " `order_id` bigint(20) NOT NULL,\n" + " `user_id` bigint(20) NOT NULL,\n" + " `order_number` varchar(255) NOT NULL,\n" + " `customer_id` bigint(20) NOT NULL,\n" + " `order_date` datetime default NULL,\n" + " `interval_value` varchar(125) default NULL,\n" + " `total_amount` decimal(10,2) NOT NULL,\n" + " PRIMARY KEY (`order_id`) USING BTREE\n" + ");"); - } - - /** - * 删除 t_order 表 - * - * @author 公众号:程序员小富 - */ - @DisplayName("删除分片表") - @Test - public void autoDeleteOrderTableAlgorithmsTest() { - jdbcTemplate.execute("DROP TABLE `t_order`;"); - } - - @DisplayName("测试t_order_id插入数据") - @Test - public void insertTableTest() { - - for (int i = 1; i <= 40; i++) { - int randomId = RandomUtils.nextInt(); - OrderPo order = new OrderPo(); - order.setOrderId((long) i); - order.setUserId((long) i); - order.setOrderNumber(String.valueOf(randomId)); - order.setCustomerId((long) randomId); - order.setOrderDate(new Date()); - order.setTotalAmount(new BigDecimal("0")); - order.setIntervalValue("2024-03-01 00:00:00"); - orderMapper.insert(order); - } - } - - /** - * 查询标准策略 - * - * @author 公众号:程序员小富 - */ - @DisplayName("查询标准策略") - @Test - public void queryTableTest() { - QueryWrapper queryWrapper = new QueryWrapper().eq("order_id", 9).eq("id", 1769988936014688257L); - OrderPo orderPo = orderMapper.selectOne(queryWrapper); - System.out.println(orderPo.getId()); - } - - @DisplayName("测试 AUTO_INTERVAL 时间分片算法插入数据") - @Test - public void insertAutoIntervalDateTableTest() { - // 放入 t_order_0 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (1, '2023-03-20 00:00:00', 1, '1', 1, 1.00 , '2024-01-01 00:00:00', 1);"); - - // 放入 t_order_1 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (2, '2024-03-20 00:00:00', 2, '2', 2,1.00 , '2024-01-01 00:00:00', 1);"); - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (3, '2024-03-20 00:00:00', 3, '3', 3, 1.00 , '2024-01-01 00:00:00', 1);"); - - // 放入 t_order_2 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (4,'2025-03-20 00:00:00',4, '4', 4, 1.00 , '2024-01-01 00:00:00', 1);"); - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (5,'2025-03-20 00:00:00',5, '5', 5, 1.00 , '2024-01-01 00:00:00', 1);"); - - // 放入 t_order_3 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (6,'2026-03-20 00:00:00',6, '6', 6, 1.00 , '2024-01-01 00:00:00', 1);"); - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (7,'2027-03-20 11:19:58',7, '7', 7, 1.00 , '2024-01-01 00:00:00', 1);"); - } - - - @DisplayName("测试 interval 时间范围分片算法插入数据") - @Test - public void insertIntervalDateTableTest() { - // 放入 t_order_202401 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (1, '2024-03-20 00:00:00', 1, '1', 1, 1.00, '2024-01-01 00:00:00', 1);"); - // 放入 t_order_202402 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (2, '2024-03-20 00:00:00', 2, '2', 2, 1.00, '2024-02-01 00:00:00', 1);"); - // 放入 t_order_202403 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (3, '2024-03-20 00:00:00', 3, '3', 3, 1.00, '2024-03-01 00:00:00', 1);"); - // 放入 t_order_202404 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (4, '2025-03-20 00:00:00', 4, '4', 4, 1.00, '2024-04-01 00:00:00', 1);"); - // 放入 t_order_202405 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (5, '2025-03-20 00:00:00', 5, '5', 5, 1.00, '2024-05-01 00:00:00', 1);"); - // 放入 t_order_202406 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (6, '2026-03-20 00:00:00', 6, '6', 6, 1.00, '2024-06-01 00:00:00', 1);"); - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (7, '2027-03-20 00:00:00', 7, '7', 7, 1.00, '2024-07-01 00:00:00', 1);"); - } - - - @DisplayName("测试 cosid_interval COSID_INTERVAL_SNOWFLAKE 时间范围分片算法插入数据") - @Test - public void insertCosIdIntervalDateTableTest() { - // 放入 t_order_202401 分片表 - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (1, '2024-03-20 00:00:00', 1, '1', 1, 1.00, '2024-01-01 00:00:00', 1);"); -// jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (2, '2024-03-20 00:00:00', 2, '2', 2, 1.00, '2024-02-01 00:00:00', 1);"); -// jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (3, '2024-03-20 00:00:00', 3, '3', 3, 1.00, '2024-03-01 00:00:00', 1);"); -// jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (4, '2025-03-20 00:00:00', 4, '4', 4, 1.00, '2024-04-01 00:00:00', 1);"); -// jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (5, '2025-03-20 00:00:00', 5, '5', 5, 1.00, '2024-05-11 00:00:10', 1);"); -// jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (6, '2026-03-20 00:00:00', 6, '6', 6, 1.00, '2024-06-01 00:00:00', 1);"); - } - - @DisplayName("测试 hint_inline 分片算法插入数据") - @Test - public void insertHintInlineTableTest() { - HintManager hintManager = HintManager.getInstance(); - hintManager.clearShardingValues(); - // 设置逻辑表 t_order 的分库值 - hintManager.addDatabaseShardingValue("t_order", 0); - // 设置逻辑表 t_order 的分表值 - hintManager.addTableShardingValue("t_order", 1); - // 1%3 = 1 所以放入 db0.t_order_1 分片表 - // /* SHARDINGSPHERE_HINT: t_order.SHARDING_DATABASE_VALUE=0, t_order.SHARDING_TABLE_VALUE=1 */ - jdbcTemplate.execute("INSERT INTO `t_order`(`id`,`order_date`,`order_id`, `order_number`, `customer_id`, `total_amount`, `interval_value`, `user_id`) VALUES (1, '2024-03-20 00:00:00', 1, '1', 1, 1.00, '2024-01-01 00:00:00', 1);"); - - hintManager.close(); - } -} diff --git a/shardingsphere101/shardingsphere-autocreate-table/README.md b/shardingsphere101/shardingsphere-autocreate-table/README.md deleted file mode 100644 index b574be63..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/README.md +++ /dev/null @@ -1,4 +0,0 @@ -### 本案例对应的文章教程 - -[分库分表如何管理不同实例中几万张分片表?](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247506123&idx=1&sn=50ea1c80fbd145a0407a647cbbb10a10&chksm=9b864836acf1c120b2bdcc84e27266ac3544161bb87d1aec360bacaa830e42f08460bb931a6c&token=755618913&lang=zh_CN#rd) - diff --git a/shardingsphere101/shardingsphere-autocreate-table/pom.xml b/shardingsphere101/shardingsphere-autocreate-table/pom.xml deleted file mode 100644 index 453be44e..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - - com.shardingsphere101 - shardingsphere101 - 0.0.1-SNAPSHOT - - shardingsphere-autocreate-table - 0.0.1-SNAPSHOT - shardingsphere-autocreate-table - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/AutoCreateTableApplication.java b/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/AutoCreateTableApplication.java deleted file mode 100644 index 697d89ca..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/AutoCreateTableApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.shardingsphere_101; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class AutoCreateTableApplication{ - - public static void main(String[] args) { - SpringApplication.run(AutoCreateTableApplication.class, args); - } - -} diff --git a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java b/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java deleted file mode 100644 index 33736b75..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java +++ /dev/null @@ -1,96 +0,0 @@ -//package com.shardingsphere_101.config; -// -//import com.zaxxer.hikari.HikariDataSource; -//import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory; -//import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration; -//import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -// -//import javax.sql.DataSource; -//import java.sql.SQLException; -//import java.util.*; -// -///** -// * 公众号:程序员小富 -// */ -//@Configuration -//public class ShardingConfiguration { -// -// /** -// * 配置分片数据源 -// * 公众号:程序员小富 -// */ -// @Bean -// public DataSource getShardingDataSource() throws SQLException { -// Map dataSourceMap = new HashMap<>(); -// dataSourceMap.put("db0", dataSource0()); -// dataSourceMap.put("db1", dataSource1()); -// -// // 分片rules规则配置 -// ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); -// -// // 分片算法 -// shardingRuleConfig.setShardingAlgorithms(getShardingAlgorithms()); -// // 配置 t_order 表分片规则 -// ShardingTableRuleConfiguration orderTableRuleConfig = new ShardingTableRuleConfiguration("t_order", "db${0..1}.t_order_${1..1000}"); -// orderTableRuleConfig.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_table_algorithms")); -// orderTableRuleConfig.setDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_database_algorithms")); -// shardingRuleConfig.getTables().add(orderTableRuleConfig); -// -// // 是否在控制台输出解析改造后真实执行的 SQL -// Properties properties = new Properties(); -// properties.setProperty("sql-show", "true"); -// -// // 创建 ShardingSphere 数据源 -// return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, Collections.singleton(shardingRuleConfig), properties); -// } -// -// /** -// * 配置数据源1 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource0() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置数据源2 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource1() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置分片算法 -// * 公众号:程序员小富 -// */ -// private Map getShardingAlgorithms() { -// Map shardingAlgorithms = new LinkedHashMap<>(); -// -// // 自定义分库算法 -// Properties databaseAlgorithms = new Properties(); -// databaseAlgorithms.setProperty("algorithm-expression", "db$->{order_id % 2}"); -// shardingAlgorithms.put("t_order_database_algorithms", new AlgorithmConfiguration("INLINE", databaseAlgorithms)); -// -// // 自定义分表算法 -// Properties tableAlgorithms = new Properties(); -// tableAlgorithms.setProperty("algorithm-expression", "db$->{order_id % 1000}"); -// shardingAlgorithms.put("t_order_table_algorithms", new AlgorithmConfiguration("INLINE", tableAlgorithms)); -// -// return shardingAlgorithms; -// } -//} diff --git a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/dao/OrderMapper.java b/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/dao/OrderMapper.java deleted file mode 100644 index 968af444..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/dao/OrderMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.shardingsphere_101.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.shardingsphere_101.entity.Order; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface OrderMapper extends BaseMapper { - -// @Select("SELECT o.orderId, o.orderNumber, oi.itemId, oi.productId, oi.quantity FROM t_order o" + -// "JOIN t_order_item oi ON o.orderId = oi.orderId") -// List selectOrderWithItems(); -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/entity/Order.java b/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/entity/Order.java deleted file mode 100644 index d1c0d7e8..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/src/main/java/com/shardingsphere_101/entity/Order.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.shardingsphere_101.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Date; - -/** - * 订单实体类 - */ -@Data -@TableName("t_order") -@NoArgsConstructor -public class Order implements Serializable { - - @TableId(type = IdType.AUTO) - private Long Id; - private Long orderId; - private String orderNumber; - private Long customerId; - private Date orderDate; - private BigDecimal totalAmount; -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-autocreate-table/src/main/resources/application.yml b/shardingsphere101/shardingsphere-autocreate-table/src/main/resources/application.yml deleted file mode 100644 index 1ce697a9..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/src/main/resources/application.yml +++ /dev/null @@ -1,86 +0,0 @@ -server: - port: 10202 -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - # 具体规则配置 - rules: - sharding: - # 自动分片表规则配置 -# auto-tables: -# t_order: -# actual-data-sources: db$->{0..1} -# sharding-strategy: -# standard: -# sharding-column: order_date -# sharding-algorithm-name: t_order_mod - # 分片算法定义 - sharding-algorithms: - # 自定义分片算法名称 - t_order_database_algorithms: - # 分片算法类型 - type: INLINE - # 自定义参数 - props: - algorithm-expression: db$->{order_id % 2} - t_order_table_algorithms: - type: INLINE - props: - algorithm-expression: t_order_$->{order_id % 1000} - t_order_mod: - type: MOD - props: - # 指定分片数量 - sharding-count: 2000 - # 分布式序列算法配置 - key-generators: - t_order_snowflake: - # 分布式序列算法(雪花算法:SNOWFLAKE; UUID:UUID)(注:UUID没有props配置) - type: SNOWFLAKE - # 分布式序列算法属性配置 - props: - # 工作机器唯一标识 - worker-id: 1 - tables: - # 逻辑表名称 - t_order: - # 数据节点:数据库.分片表 - actual-data-nodes: db$->{0..1}.t_order_${1..1000} - # 分库策略 - database-strategy: - standard: - # 分片列名称 - sharding-column: order_id - # 分片算法名称 - sharding-algorithm-name: t_order_database_algorithms - # 分表策略 - table-strategy: - standard: - # 分片列名称 - sharding-column: order_id - # 分片算法名称 - sharding-algorithm-name: t_order_table_algorithms - keyGenerateStrategy: - column: order_id - keyGeneratorName: t_order_snowflake - - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-autocreate-table/src/test/java/com/shardingsphere_101/AutoCreateTablesTests.java b/shardingsphere101/shardingsphere-autocreate-table/src/test/java/com/shardingsphere_101/AutoCreateTablesTests.java deleted file mode 100644 index 479c315a..00000000 --- a/shardingsphere101/shardingsphere-autocreate-table/src/test/java/com/shardingsphere_101/AutoCreateTablesTests.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.shardingsphere_101; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.jdbc.core.JdbcTemplate; -import javax.annotation.Resource; - -/** - * @author 公众号:程序员小富 - * 自动创建分片表 - * @date 2023/12/31 17:25 - */ -@SpringBootTest -class AutoCreateTablesTests { - - @Resource - private JdbcTemplate jdbcTemplate; - - /** - * 执行创建逻辑表的SQL,会根据AutoTables的配置自动在对应的数据源内创建分片表 - * - * @author 公众号:程序员小富 - */ - @DisplayName("创建分片表") - @Test - public void autoCreateOrderTableTest() { - - jdbcTemplate.execute("CREATE TABLE `t_order` (\n" + - " `order_id` bigint(20) NOT NULL,\n" + - " `order_number` varchar(255) NOT NULL,\n" + - " `customer_id` bigint(20) NOT NULL,\n" + - " `order_date` date NOT NULL,\n" + - " `total_amount` decimal(10,2) NOT NULL,\n" + - " PRIMARY KEY (`order_id`) USING BTREE\n" + - ");"); - } - - /** - * 删除 t_order 表 - * - * @author 公众号:程序员小富 - */ - @DisplayName("修改分片表字段长度") - @Test - public void autoModifyOrderTableTest() { - - jdbcTemplate.execute("ALTER TABLE t_order MODIFY COLUMN order_number varchar(500);"); - } - - /** - * 删除 t_order 表 - * - * @author 公众号:程序员小富 - */ - @DisplayName("删除分片表") - @Test - public void autoDeleteOrderTableTest() { - - jdbcTemplate.execute("DROP TABLE `t_order`;"); - } -} diff --git a/shardingsphere101/shardingsphere-default-strategy/README.md b/shardingsphere101/shardingsphere-default-strategy/README.md deleted file mode 100644 index 8b137891..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/README.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/shardingsphere101/shardingsphere-default-strategy/sql/CreateTable.sql b/shardingsphere101/shardingsphere-default-strategy/sql/CreateTable.sql deleted file mode 100644 index 25f08bbe..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/sql/CreateTable.sql +++ /dev/null @@ -1,66 +0,0 @@ -CREATE TABLE t_city_dict ( - id BIGINT, -- 城市ID - city_name VARCHAR(255) NOT NULL, -- 城市名称 - province_name VARCHAR(255) NOT NULL, -- 省份名称 - country_name VARCHAR(255) NOT NULL, -- 国家名称 - population INT, -- 城市人口数量 - area FLOAT, -- 城市面积 - timezone VARCHAR(255), -- 所属时区 - postal_code VARCHAR(10), -- 邮政编码 - created_date datetime DEFAULT CURRENT_TIMESTAMP, - updated_date datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - PRIMARY KEY (`id`) -) ; - - -CREATE TABLE t_order_0 ( - order_id INT PRIMARY KEY, - order_number VARCHAR(20), - customer_id INT, - order_date DATE, - total_amount DECIMAL(10, 2) -); - - -CREATE TABLE t_order_1 ( - order_id INT PRIMARY KEY, - order_number VARCHAR(20), - customer_id INT, - order_date DATE, - total_amount DECIMAL(10, 2) -); - -CREATE TABLE t_order_2 ( - order_id INT PRIMARY KEY, - order_number VARCHAR(20), - customer_id INT, - order_date DATE, - total_amount DECIMAL(10, 2) -); - --- 创建 t_order_item 表 -CREATE TABLE t_order_item_0 ( - item_id INT PRIMARY KEY, - order_id INT, - product_id INT, - quantity INT, - unit_price DECIMAL(8, 2) -); - -CREATE TABLE t_order_item_1 ( - item_id INT PRIMARY KEY, - order_id INT, - product_id INT, - quantity INT, - unit_price DECIMAL(8, 2) -); - -CREATE TABLE t_order_item_2 ( - item_id INT PRIMARY KEY, - order_id INT, - product_id INT, - quantity INT, - unit_price DECIMAL(8, 2) -); - - diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/controller/OrderController.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/controller/OrderController.java deleted file mode 100644 index 2a3500b6..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/controller/OrderController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.shardingsphere_101.controller; - -import com.shardingsphere_101.dao.OrderItemMapper; -import com.shardingsphere_101.dao.OrderMapper; -import com.shardingsphere_101.entity.Order; -import com.shardingsphere_101.entity.OrderItem; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; -import java.math.BigDecimal; -import java.util.Date; - -/** - * 公众号:程序员小富 - * - * @author Jiahai - */ -@RestController -@RequestMapping("/order") -public class OrderController { - - @Resource - private OrderMapper orderMapper; - - @Resource - private OrderItemMapper orderItemMapper; - - @RequestMapping("/test1") - public String test1() { - for (int i = 0; i < 3; i++) { - Order order = new Order(); - order.setOrderNumber("WIN000" + i); - order.setCustomerId((long) i); - order.setOrderDate(new Date()); - order.setTotalAmount(new BigDecimal("0" + i)); - orderMapper.insert(order); -// OrderItem orderItem = new OrderItem(); -// orderItem.setOrderId(order.getOrderId()); -// orderItem.setProductId(i); -// orderItem.setQuantity(i); -// orderItem.setUnitPrice(new BigDecimal("0" + i)); -// orderItemMapper.insert(orderItem); - } - return "ok"; - } -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/CityDictMapper.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/CityDictMapper.java deleted file mode 100644 index e236a502..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/CityDictMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.shardingsphere_101.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.shardingsphere_101.entity.CityDict; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface CityDictMapper extends BaseMapper { -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/OrderItemMapper.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/OrderItemMapper.java deleted file mode 100644 index 83734d14..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/OrderItemMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.shardingsphere_101.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.shardingsphere_101.entity.OrderItem; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface OrderItemMapper extends BaseMapper { -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/OrderMapper.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/OrderMapper.java deleted file mode 100644 index 968af444..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/dao/OrderMapper.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.shardingsphere_101.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.shardingsphere_101.entity.Order; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface OrderMapper extends BaseMapper { - -// @Select("SELECT o.orderId, o.orderNumber, oi.itemId, oi.productId, oi.quantity FROM t_order o" + -// "JOIN t_order_item oi ON o.orderId = oi.orderId") -// List selectOrderWithItems(); -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/CityDict.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/CityDict.java deleted file mode 100644 index 2f03cf51..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/CityDict.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.shardingsphere_101.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -@TableName("t_city_dict") -@Data -public class CityDict { - - private Long id; - private String cityName; - private String provinceName; - private String countryName; - private Integer population; - private Integer area; -} diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/Order.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/Order.java deleted file mode 100644 index d1c0d7e8..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/Order.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.shardingsphere_101.entity; - -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Date; - -/** - * 订单实体类 - */ -@Data -@TableName("t_order") -@NoArgsConstructor -public class Order implements Serializable { - - @TableId(type = IdType.AUTO) - private Long Id; - private Long orderId; - private String orderNumber; - private Long customerId; - private Date orderDate; - private BigDecimal totalAmount; -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/OrderItem.java b/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/OrderItem.java deleted file mode 100644 index 1c600072..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/OrderItem.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.shardingsphere_101.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.math.BigDecimal; - -/** - * 订单实体类 - * - * @author Jiahai - */ -@NoArgsConstructor -@TableName("t_order_item") -@Data -public class OrderItem { - private Long id; - private Long itemId; - private Long orderId; - private int productId; - private int quantity; - private BigDecimal unitPrice; -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/AutoCreateTablesTests.java b/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/AutoCreateTablesTests.java deleted file mode 100644 index 140ecf52..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/AutoCreateTablesTests.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.shardingsphere_101; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.annotation.Resource; - -/** - * @author 公众号:程序员小富 - * 自动创建分片表 - * @date 2023/12/31 17:25 - */ -@SpringBootTest -class AutoCreateTablesTests { - - @Resource - private JdbcTemplate jdbcTemplate; - - /** - * 执行创建逻辑表的SQL,会根据AutoTables的配置自动在对应的数据源内创建分片表 - * - * @author 公众号:程序员小富 - */ - @Test - public void autoCreateOrderTableTest() { - - jdbcTemplate.execute("CREATE TABLE `t_order` (\n" + - " `order_id` bigint(20) NOT NULL,\n" + - " `order_number` varchar(255) NOT NULL,\n" + - " `customer_id` bigint(20) NOT NULL,\n" + - " `order_date` date NOT NULL,\n" + - " `total_amount` decimal(10,2) NOT NULL,\n" + - " `id` bigint(20) NOT NULL AUTO_INCREMENT,\n" + - " PRIMARY KEY (`id`) USING BTREE\n" + - ");"); - } - - @Test - public void autoCreateOrderItemTableTest() { - - jdbcTemplate.execute("CREATE TABLE t_order_item (\n" + - " item_id INT PRIMARY KEY,\n" + - " order_id INT,\n" + - " product_id INT,\n" + - " quantity INT,\n" + - " unit_price DECIMAL(8, 2)\n" + - ");"); - } -} diff --git a/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/MyBindingTablesTests.java b/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/MyBindingTablesTests.java deleted file mode 100644 index 26e98b3e..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/MyBindingTablesTests.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.shardingsphere_101; - -import com.shardingsphere_101.dao.OrderItemMapper; -import com.shardingsphere_101.dao.OrderMapper; -import com.shardingsphere_101.entity.Order; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -import javax.annotation.Resource; -import java.math.BigDecimal; -import java.util.Date; -import java.util.Random; - -/** - * 绑定表测试 - */ -@SpringBootTest -class MyBindingTablesTests { - - @Resource - private OrderMapper orderMapper; - - @Resource - private OrderItemMapper orderItemMapper; - - public static long getRandomNumber(int i) { - int digits = 11; // 要生成的位数 - long min = (long) Math.pow(10, digits - 1); // 最小值 - long max = (long) Math.pow(10, digits) - 1; // 最大值 - Random random = new Random(); - long randomNumber = min + ((long) (random.nextDouble() * (max - min))); - return randomNumber; - } - - @Test - public void insertOrderAndItemsTest() { - - for (int i = 0; i < 6; i++) { - Order order = new Order(); - - long orderId = getRandomNumber(11); -// order.setOrderId(orderId); - order.setOrderNumber("WIN" + orderId); - order.setCustomerId((long) i); - order.setOrderDate(new Date()); - order.setTotalAmount(new BigDecimal("0" + i)); - orderMapper.insert(order); - -// OrderItem orderItem = new OrderItem(); -// orderItem.setOrderId(order.getOrderId()); -// orderItem.setProductId(i); -// orderItem.setQuantity(i); -// orderItem.setUnitPrice(new BigDecimal("0" + i)); -// orderItemMapper.insert(orderItem); - } - } -} diff --git a/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/MyBroadcastTableTests.java b/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/MyBroadcastTableTests.java deleted file mode 100644 index 11239aa9..00000000 --- a/shardingsphere101/shardingsphere-default-strategy/src/test/java/com/shardingsphere_101/MyBroadcastTableTests.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.shardingsphere_101; - -import com.alibaba.fastjson.JSON; -import com.shardingsphere_101.dao.CityDictMapper; -import com.shardingsphere_101.entity.CityDict; -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -import javax.annotation.Resource; - -/** - * 广播表测试 - */ -@Slf4j -@SpringBootTest -class MyBroadcastTableTests { - - @Resource - private CityDictMapper cityDictRepository; - - /** - * 广播表测试 - */ - @Test - void saveCityDict() { - CityDict cityDict = new CityDict(); - cityDict.setCityName("北京市"); - cityDict.setProvinceName("北京"); - cityDict.setCountryName("中国"); - cityDict.setPopulation(0); - cityDict.setArea(0); - cityDictRepository.insert(cityDict); - } - - @Test - void findCityDict() { - for (int i = 0; i < 2000; i++) { - CityDict dict = cityDictRepository.selectById(1L); - log.info(JSON.toJSONString(dict)); - } - } -} diff --git a/shardingsphere101/shardingsphere-default/.gitignore b/shardingsphere101/shardingsphere-default/.gitignore new file mode 100644 index 00000000..3d0452a4 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/.gitignore @@ -0,0 +1,35 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ +!/.mvn/ +!/.idea/!/.mvn/ diff --git a/shardingsphere101/shardingsphere-default/README.md b/shardingsphere101/shardingsphere-default/README.md new file mode 100644 index 00000000..6211e9da --- /dev/null +++ b/shardingsphere101/shardingsphere-default/README.md @@ -0,0 +1,2 @@ + +yml 和 Java编码的方式实现了简单的分库分表 \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/pom.xml b/shardingsphere101/shardingsphere-default/pom.xml similarity index 90% rename from shardingsphere101/shardingsphere-default-strategy/pom.xml rename to shardingsphere101/shardingsphere-default/pom.xml index 066295e3..34b88219 100644 --- a/shardingsphere101/shardingsphere-default-strategy/pom.xml +++ b/shardingsphere101/shardingsphere-default/pom.xml @@ -7,9 +7,9 @@ shardingsphere101 0.0.1-SNAPSHOT - shardingsphere-default-strategy + shardingsphere-default 0.0.1-SNAPSHOT - shardingsphere-default-strategy + shardingsphere-default diff --git a/shardingsphere101/shardingsphere-default/sql/CreateTable.sql b/shardingsphere101/shardingsphere-default/sql/CreateTable.sql new file mode 100644 index 00000000..a3a71e96 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/sql/CreateTable.sql @@ -0,0 +1,29 @@ +CREATE TABLE `t_order_0` ( + `order_id` bigint NOT NULL, + `create_time` datetime DEFAULT NULL, + PRIMARY KEY (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; + +CREATE TABLE `t_order_1` ( + `order_id` bigint NOT NULL, + `create_time` datetime DEFAULT NULL, + PRIMARY KEY (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; + +CREATE TABLE `t_order_2` ( + `order_id` bigint NOT NULL, + `create_time` datetime DEFAULT NULL, + PRIMARY KEY (`order_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; + + + +CREATE TABLE `t_user` ( + `id` bigint NOT NULL AUTO_INCREMENT, + `u_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL, + `u_age` int DEFAULT NULL, + `u_address` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL, + `create_time` datetime DEFAULT NULL, + `date_time` datetime DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/StrategyApplication.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/Application.java similarity index 70% rename from shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/StrategyApplication.java rename to shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/Application.java index 2ae7b8b6..a113699c 100644 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/StrategyApplication.java +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/Application.java @@ -4,11 +4,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class -StrategyApplication { +public class Application { public static void main(String[] args) { - SpringApplication.run(StrategyApplication.class, args); + SpringApplication.run(Application.class, args); } } diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java similarity index 83% rename from shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java rename to shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java index a99e6d0d..b0ab0d4a 100644 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/config/ShardingConfiguration.java +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/conf/ShardingConfiguration.java @@ -5,7 +5,6 @@ //import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration; //import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; //import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration; //import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; @@ -33,19 +32,8 @@ // // 分片rules规则配置 // ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); // -// // 默认的分库策略 -// shardingRuleConfig.setDefaultDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "database-inline")); // 默认的分库策略 -// // 默认的分表策略 -// shardingRuleConfig.setDefaultTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "table-inline")); -// // 默认的主键生成策略 -// shardingRuleConfig.setDefaultShardingColumn("order_id"); -// shardingRuleConfig.setDefaultKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("id", "table-inline")); -// -// // 广播表 -// shardingRuleConfig.setBroadcastTables(Collections.singletonList("t_city_dict")); -// -// // 分片算法 // shardingRuleConfig.setShardingAlgorithms(getShardingAlgorithms()); +// // // 配置 t_order 表分片规则 // ShardingTableRuleConfiguration orderTableRuleConfig = new ShardingTableRuleConfiguration("t_order", "db${0..1}.t_order_${0..2}"); // orderTableRuleConfig.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "table-inline")); diff --git a/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/controller/OrderController.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/controller/OrderController.java new file mode 100644 index 00000000..9c103db6 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/controller/OrderController.java @@ -0,0 +1,84 @@ +package com.shardingsphere_101.controller; + +import com.shardingsphere_101.entity.Order; +import com.shardingsphere_101.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 订单 API + * + * @author Jiahai + */ +@RestController +@RequestMapping("/order") +public class OrderController { + @Autowired + private OrderService orderService; + + /** + * 新增 + * + * @return Order + */ + @PostMapping + public Order save() { + return orderService.save(); + } + + /** + * 删除 + * + * @param orderId 订单ID + */ + @DeleteMapping("/{orderId}") + public void delete(@PathVariable Long orderId) { + orderService.delete(orderId); + } + + /** + * 修改 + * + * @param orderId 订单ID + */ + @PutMapping + public void update(Long orderId) { + orderService.update(orderId); + } + + /** + * 根据主键ID查询 + * + * @param orderId 订单ID + * @return Order + */ + @GetMapping("/{orderId}") + public Order findById(@PathVariable Long orderId) { + return orderService.findById(orderId); + } + + /** + * 列表查询(根据主键ID顺序) + * + * @return List + */ + @GetMapping("/list") + public List list() { + return orderService.list(); + } + + /** + * 分页查询(根据主键ID逆序) + * + * @param page 当前页 + * @param size 每页条数 + * @return Page + */ + @GetMapping("/page/{page}/{size}") + public Page page(@PathVariable int page, @PathVariable int size) { + return orderService.page(page, size); + } +} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/entity/Order.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/entity/Order.java new file mode 100644 index 00000000..2d5ba087 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/entity/Order.java @@ -0,0 +1,38 @@ +package com.shardingsphere_101.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; +import java.util.Date; + +/** + * 订单实体类 + * + * @author Jiahai + */ +@Accessors(chain = true) +@Entity +@Table(name = "t_order") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Order implements Serializable { + /** + * 订单ID + */ + @Id + private Long orderId; + + /** + * 创建时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date createTime; +} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/User.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/entity/User.java similarity index 52% rename from shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/User.java rename to shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/entity/User.java index 42ca83f6..f771de05 100644 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/java/com/shardingsphere_101/entity/User.java +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/entity/User.java @@ -1,15 +1,25 @@ package com.shardingsphere_101.entity; -import com.baomidou.mybatisplus.annotation.TableName; +import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import javax.persistence.*; import java.io.Serializable; import java.util.Date; -@TableName("t_user") + +@Accessors(chain = true) +@Entity +@Table(name = "t_user") @Data +@NoArgsConstructor +@AllArgsConstructor public class User implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String uName; diff --git a/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/repository/OrderRepository.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/repository/OrderRepository.java new file mode 100644 index 00000000..afffc7a5 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/repository/OrderRepository.java @@ -0,0 +1,7 @@ +package com.shardingsphere_101.repository; + +import com.shardingsphere_101.entity.Order; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface OrderRepository extends JpaRepository { +} diff --git a/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/repository/UserRepository.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/repository/UserRepository.java new file mode 100644 index 00000000..e7ee4a95 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.shardingsphere_101.repository; + +import com.shardingsphere_101.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git a/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/service/OrderService.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/service/OrderService.java new file mode 100644 index 00000000..dd1c93ea --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/service/OrderService.java @@ -0,0 +1,58 @@ +package com.shardingsphere_101.service; + +import com.shardingsphere_101.entity.Order; +import org.springframework.data.domain.Page; + +import java.util.List; + +/** + * 订单业务层接口 + * + * @author Jiahai + */ +public interface OrderService { + /** + * 新增(测试数据) + * + * @return + */ + Order save(); + + /** + * 根据ID删除 + * + * @param orderId + */ + void delete(Long orderId); + + /** + * 更新(创建时间) + * + * @param orderId + */ + void update(Long orderId); + + /** + * 根据主键查询 + * + * @param orderId 订单ID + * @return + */ + Order findById(Long orderId); + + /** + * 列表查询(根据主键ID顺序) + * + * @return + */ + List list(); + + /** + * 分页查询(根据主键ID逆序) + * + * @param page 当前页 + * @param size 每页条数 + * @return + */ + Page page(int page, int size); +} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java new file mode 100644 index 00000000..eab3f5dd --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/main/java/com/shardingsphere_101/service/impl/OrderServiceImpl.java @@ -0,0 +1,62 @@ +package com.shardingsphere_101.service.impl; + +import com.shardingsphere_101.entity.Order; +import com.shardingsphere_101.repository.OrderRepository; +import com.shardingsphere_101.service.OrderService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.List; +import java.util.stream.LongStream; + +/** + * 订单业务层接口实现类 + * + * @author Jiahai + */ +@Service +public class OrderServiceImpl implements OrderService { + @Autowired + private OrderRepository orderRepository; + + @Override + @Transactional(rollbackFor = Exception.class) + public Order save() { + // 新增订单ID从1~10的测试数据 + LongStream.range(1, 11).forEach(value -> orderRepository.save(new Order(value, new Date()))); + return null; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Long orderId) { + orderRepository.deleteById(orderId); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(Long orderId) { + orderRepository.findById(orderId).orElseThrow(() -> new RuntimeException("ID不存在")).setCreateTime(new Date()); + } + + @Override + public Order findById(Long orderId) { + return orderRepository.findById(orderId).orElseThrow(() -> new RuntimeException("ID不存在")); + } + + @Override + public List list() { + return orderRepository.findAll(Sort.by(Sort.Direction.ASC, "orderId")); + } + + @Override + public Page page(int page, int size) { + PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "orderId")); + return this.orderRepository.findAll(pageRequest); + } +} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-default-strategy/src/main/resources/application.yml b/shardingsphere101/shardingsphere-default/src/main/resources/application.yml similarity index 59% rename from shardingsphere101/shardingsphere-default-strategy/src/main/resources/application.yml rename to shardingsphere101/shardingsphere-default/src/main/resources/application.yml index c5c0f6a0..1bcd1eb2 100644 --- a/shardingsphere101/shardingsphere-default-strategy/src/main/resources/application.yml +++ b/shardingsphere101/shardingsphere-default/src/main/resources/application.yml @@ -6,13 +6,13 @@ spring: # 数据源配置 datasource: # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 + names: db2 , db1 , db0 db0: # 数据库连接池类名称 type: com.zaxxer.hikari.HikariDataSource # 数据库驱动类名 driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true + jdbc-url: jdbc:mysql://127.0.0.1:3306/shardingsphere-db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true username: root password: 123456 db1: @@ -20,34 +20,37 @@ spring: type: com.zaxxer.hikari.HikariDataSource # 数据库驱动类名 driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true + jdbc-url: jdbc:mysql://127.0.0.1:3306/shardingsphere-db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true + username: root + password: 123456 + db2: + # 数据库连接池类名称 + type: com.zaxxer.hikari.HikariDataSource + # 数据库驱动类名 + driver-class-name: com.mysql.cj.jdbc.Driver + jdbc-url: jdbc:mysql://127.0.0.1:3306/shardingsphere-db2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true username: root password: 123456 # 规则配置 rules: sharding: + # 设置默认数据源 + default-data-source-name: db1 # 分片算法配置 sharding-algorithms: - order-database-inline: + database-inline: # 分片算法类型 type: INLINE props: + # 分片算法的行表达式 algorithm-expression: db$->{order_id % 2} - order-table-inline: + table-inline: + # 分片算法类型 type: INLINE props: - algorithm-expression: t_order_$->{order_id % 4} - mod: - type: MOD - props: - # 指定分片数量 - sharding-count: 8 - order-table-mod: - type: MOD - props: - # 指定分片数量 - sharding-count: 4 + # 分片算法的行表达式 + algorithm-expression: t_order_$->{order_id % 3} # 分布式序列算法配置 key-generators: snowflake: @@ -61,33 +64,21 @@ spring: # 逻辑表名称 t_order: # 行表达式标识符可以使用 ${...} 或 $->{...},但前者与 Spring 本身的属性文件占位符冲突,因此在 Spring 环境中使用行表达式标识符建议使用 $->{...} - actual-data-nodes: db$->{0..1}.t_order_$->{0..5} + actual-data-nodes: db$->{0..1}.t_order_$->{0..3} # 分库策略 database-strategy: standard: # 分片列名称 sharding-column: order_id # 分片算法名称 - sharding-algorithm-name: order-database-inline + sharding-algorithm-name: database-inline # 分表策略 table-strategy: standard: # 分片列名称 sharding-column: order_id # 分片算法名称 - sharding-algorithm-name: order-table-inline - keyGenerateStrategy: - column: order_id - keyGeneratorName: snowflake - - # 自动分片表规则配置 -# auto-tables: -# t_order: # 逻辑表名称 -# actual-data-sources: db$->{0..1} -# sharding-strategy: # 切分策略 -# standard: # 用于单分片键的标准分片场景 -# sharding-column: order_id # 分片列名称 -# sharding-algorithm-name: mod # 自动分片算法名称 + sharding-algorithm-name: table-inline # 属性配置 props: # 展示修改以后的sql语句 diff --git a/shardingsphere101/shardingsphere-default/src/test/java/com/shardingsphere_101/ShardingSphereApplicationTests.java b/shardingsphere101/shardingsphere-default/src/test/java/com/shardingsphere_101/ShardingSphereApplicationTests.java new file mode 100644 index 00000000..222798d4 --- /dev/null +++ b/shardingsphere101/shardingsphere-default/src/test/java/com/shardingsphere_101/ShardingSphereApplicationTests.java @@ -0,0 +1,42 @@ +package com.shardingsphere_101; + +import com.shardingsphere_101.entity.User; +import com.shardingsphere_101.repository.UserRepository; +import com.shardingsphere_101.service.OrderService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; +import java.util.Date; + +@SpringBootTest +class ShardingSphereApplicationTests { + + @Resource + private OrderService orderService; + + @Resource + private UserRepository userRepository; + + /** + * 插入 t_order 数据验证简单的分库分表示例 + */ + @Test + void saveOrderSharding() { + orderService.save(); + } + + /** + * t_user 未做分库分表的表,插入数据验证示例 + */ + @Test + void saveDefaultUserSharding() { + User user = new User(); + user.setUName("公众号:程序员小富"); + user.setUAge(12); + user.setUAddress("宇宙商场"); + user.setCreateTime(new Date()); + user.setDateTime(new Date()); + userRepository.save(user); + } +} diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/README.md b/shardingsphere101/shardingsphere-sequence-algorithm/README.md deleted file mode 100644 index 82c3bc05..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/README.md +++ /dev/null @@ -1,8 +0,0 @@ - - -### 本案例对应的文章教程 - -[一口气搞懂分库分表 12 种分片算法,大厂都在用](https://mp.weixin.qq.com/s/HAoCXGoGCbDt9ZaWCu-qIw) - - - diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/pom.xml b/shardingsphere101/shardingsphere-sequence-algorithm/pom.xml deleted file mode 100644 index 0062a52f..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - com.shardingsphere101 - shardingsphere101 - 0.0.1-SNAPSHOT - - shardingsphere-sequence-algorithm - 0.0.1-SNAPSHOT - shardingsphere-sequence-algorithm - - - - org.apache.shardingsphere - shardingsphere-jdbc-core - ${shardingsphere.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/SequenceAlgorithmsApplication.java b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/SequenceAlgorithmsApplication.java deleted file mode 100644 index 556db00a..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/SequenceAlgorithmsApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.shardingsphere_101.keyGenerator; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SequenceAlgorithmsApplication { - - public static void main(String[] args) { - - SpringApplication.run(SequenceAlgorithmsApplication.class, args); - } -} diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/algorithm/SequenceAlgorithms.java b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/algorithm/SequenceAlgorithms.java deleted file mode 100644 index 2e00041b..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/algorithm/SequenceAlgorithms.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.shardingsphere_101.keyGenerator.algorithm; - -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm; - -import java.util.Properties; - -/** - * 自定义分库分表主键算法 - */ -@Data -@Slf4j -public class SequenceAlgorithms implements KeyGenerateAlgorithm { - @Override - public String getType() { - // 返回算法类型表示 - return "custom"; - } - - @Override - public Comparable generateKey() { - System.out.println(111); - System.out.println(111); - System.out.println(111); - - return null; - } - - @Override - public Properties getProps() { - return null; - } - - @Override - public void init(Properties properties) { - } -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/config/ShardingConfiguration.java b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/config/ShardingConfiguration.java deleted file mode 100644 index d3367095..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/config/ShardingConfiguration.java +++ /dev/null @@ -1,122 +0,0 @@ -//package com.shardingsphere_101.config; -// -//import com.zaxxer.hikari.HikariDataSource; -//import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory; -//import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration; -//import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration; -//import org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration; -//import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; -//import org.springframework.context.annotation.Bean; -//import org.springframework.context.annotation.Configuration; -// -//import javax.sql.DataSource; -//import java.sql.SQLException; -//import java.util.*; -// -///** -// * 公众号:程序员小富 -// */ -//@Configuration -//public class ShardingConfiguration { -// -// /** -// * 配置分片数据源 -// * 公众号:程序员小富 -// */ -// @Bean -// public DataSource getShardingDataSource() throws SQLException { -// Map dataSourceMap = new HashMap<>(); -// dataSourceMap.put("db0", dataSource0()); -// dataSourceMap.put("db1", dataSource1()); -// -// // 分片rules规则配置 -// ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); -// -// // 分片算法 -// shardingRuleConfig.setShardingAlgorithms(getShardingAlgorithms()); -// shardingRuleConfig.setKeyGenerators(getKeyGenerators()); -// // 配置 t_order 表分片规则 -// ShardingTableRuleConfiguration orderTableRuleConfig = new ShardingTableRuleConfiguration("t_order", "db${0..1}.t_order_${0..2}"); -// orderTableRuleConfig.setTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_table_mod")); -// orderTableRuleConfig.setDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", "t_order_database_mod")); -// -// // 配置分片健策略 -// orderTableRuleConfig.setKeyGenerateStrategy(new KeyGenerateStrategyConfiguration("id", "xiaofu")); -// -// -// shardingRuleConfig.getTables().add(orderTableRuleConfig); -// -// // 是否在控制台输出解析改造后真实执行的 SQL -// Properties properties = new Properties(); -// properties.setProperty("sql-show", "true"); -// -// // 创建 ShardingSphere 数据源 -// return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, Collections.singleton(shardingRuleConfig), properties); -// } -// -// /** -// * 配置数据源1 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource0() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置数据源2 -// * 公众号:程序员小富 -// */ -// public DataSource dataSource1() { -// HikariDataSource dataSource = new HikariDataSource(); -// dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); -// dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"); -// dataSource.setUsername("root"); -// dataSource.setPassword("123456"); -// return dataSource; -// } -// -// /** -// * 配置分片算法 -// * 公众号:程序员小富 -// */ -// private Map getShardingAlgorithms() { -// Map shardingAlgorithms = new LinkedHashMap<>(); -// -// // 自定义分库算法 -// Properties databaseAlgorithms = new Properties(); -// databaseAlgorithms.setProperty("sharding-count", "2"); -// shardingAlgorithms.put("t_order_database_mod", new AlgorithmConfiguration("MOD", databaseAlgorithms)); -// -// // 自定义分表算法 -// Properties tableAlgorithms = new Properties(); -// tableAlgorithms.setProperty("sharding-count", "3"); -// shardingAlgorithms.put("t_order_table_mod", new AlgorithmConfiguration("MOD", tableAlgorithms)); -// -// return shardingAlgorithms; -// } -// -// /** -// * 配置分片健 -// * 公众号:程序员小富 -// */ -// private Map getKeyGenerators() { -// Map keyGenerators = new LinkedHashMap<>(); -// -// Properties uuidProperties = new Properties(); -// keyGenerators.put("uuid", new AlgorithmConfiguration("UUID", uuidProperties)); -// -// Properties nanoid = new Properties(); -// keyGenerators.put("nanoid", new AlgorithmConfiguration("NANOID", nanoid)); -// -// Properties xiaofu = new Properties(); -// keyGenerators.put("xiaofu", new AlgorithmConfiguration("xiaofu", xiaofu)); -// -// return keyGenerators; -// } -//} diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/dao/OrderMapper.java b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/dao/OrderMapper.java deleted file mode 100644 index 744187ff..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/dao/OrderMapper.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.shardingsphere_101.keyGenerator.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.shardingsphere_101.keyGenerator.entity.OrderPo; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface OrderMapper extends BaseMapper { - -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/entity/OrderPo.java b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/entity/OrderPo.java deleted file mode 100644 index 73d3f399..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/java/com/shardingsphere_101/keyGenerator/entity/OrderPo.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.shardingsphere_101.keyGenerator.entity; - -import com.aventrix.jnanoid.jnanoid.NanoIdUtils; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import org.apache.shardingsphere.sharding.cosid.algorithm.keygen.CosIdSnowflakeKeyGenerateAlgorithm; -import org.apache.shardingsphere.sharding.nanoid.algorithm.keygen.NanoIdKeyGenerateAlgorithm; -import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm; - -import java.beans.Transient; -import java.math.BigDecimal; -import java.util.Date; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -/** - * 订单实体类 - */ -@Data -@TableName("t_order") -public class OrderPo { - private transient Long Id; - private Long orderId; - private Long userId; - private String orderNumber; - private Long customerId; - private Date orderDate; - private BigDecimal totalAmount; - private String intervalValue; -} \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/resources/META-INF/services/org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/resources/META-INF/services/org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm deleted file mode 100644 index a9c8e0b4..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/resources/META-INF/services/org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm +++ /dev/null @@ -1,6 +0,0 @@ -com.shardingsphere_101.keyGenerator.algorithm.SequenceAlgorithms -org.apache.shardingsphere.sharding.algorithm.keygen.SnowflakeKeyGenerateAlgorithm -org.apache.shardingsphere.sharding.algorithm.keygen.UUIDKeyGenerateAlgorithm -org.apache.shardingsphere.sharding.nanoid.algorithm.keygen.NanoIdKeyGenerateAlgorithm -org.apache.shardingsphere.sharding.cosid.algorithm.keygen.CosIdKeyGenerateAlgorithm -org.apache.shardingsphere.sharding.cosid.algorithm.keygen.CosIdSnowflakeKeyGenerateAlgorithm \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/resources/application.yml b/shardingsphere101/shardingsphere-sequence-algorithm/src/main/resources/application.yml deleted file mode 100644 index 7144f7b7..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/main/resources/application.yml +++ /dev/null @@ -1,78 +0,0 @@ -spring: - shardingsphere: - # 数据源配置 - datasource: - # 数据源名称,多数据源以逗号分隔 ,放在第一个的数据源为未配置分片规则表的默认数据源 - names: db0 , db1 - # 名称与上边 names 保持一致 - db0: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db0?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - db1: - type: com.zaxxer.hikari.HikariDataSource - driver-class-name: com.mysql.cj.jdbc.Driver - jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true - username: root - password: 123456 - rules: - sharding: - # 分片算法定义 - sharding-algorithms: - t_order_database_mod: - type: MOD - props: - sharding-count: 2 # 指定分片数量 - t_order_table_mod: - type: MOD - props: - sharding-count: 3 # 指定分片数量 - key-generators: # 分布式序列算法配置 - # 雪花ID生成算法 - snowflake-gen: - type: SNOWFLAKE - props: - worker-id: 1 # 工作机器唯一标识 - max-vibration-offset: 2 # 最大抖动上限值,范围[0, 4096)。注:若使用此算法生成值作分片值,建议配置此属性。此算法在不同毫秒内所生成的 key 取模 2^n (2^n一般为分库或分表数) 之后结果总为 0 或 1。为防止上述分片问题,建议将此属性值配置为 (2^n)-1 - max-tolerate-time-difference-milliseconds: 10 # 最大容忍时钟回退时间,单位:毫秒 - # UUID生成算法 - uu-id-gen: - type: UUID - # nanoid生成算法 - nanoid-gen: - type: NANOID - # COSID生成算法 - cosId-gen: - type: COSID - props: - id-name: __share__ - as-string: false - # cosId-snowflake生成算法 - cosId-snowflake-gen: - type: COSID_SNOWFLAKE - props: - epoch: 1477929600000 - as-string: false - # 自定义ID生成策略 - xiaofu-id-gen: - type: custom - tables: - t_order: # 逻辑表名称 - actual-data-nodes: db$->{0..1}.t_order_${0..2} # 数据节点:数据库.分片表 - database-strategy: # 分库策略 - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_database_mod - table-strategy: # 分表策略 - standard: - sharding-column: order_id - sharding-algorithm-name: t_order_table_mod - key-generate-strategy: # 分布式主键生成策略 - column: id - keyGeneratorName: xiaofu-id-gen - # 属性配置 - props: - # 展示修改以后的sql语句 - sql-show: true \ No newline at end of file diff --git a/shardingsphere101/shardingsphere-sequence-algorithm/src/test/java/com/shardingsphere_101/keyGenerator/SequenceAlgorithmsTests.java b/shardingsphere101/shardingsphere-sequence-algorithm/src/test/java/com/shardingsphere_101/keyGenerator/SequenceAlgorithmsTests.java deleted file mode 100644 index d8ae8341..00000000 --- a/shardingsphere101/shardingsphere-sequence-algorithm/src/test/java/com/shardingsphere_101/keyGenerator/SequenceAlgorithmsTests.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.shardingsphere_101.keyGenerator; - -import com.alibaba.fastjson.JSON; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.shardingsphere_101.keyGenerator.dao.OrderMapper; -import com.shardingsphere_101.keyGenerator.entity.OrderPo; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.RandomUtils; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.jdbc.core.JdbcTemplate; - -import javax.annotation.Resource; -import java.math.BigDecimal; -import java.util.Date; -import java.util.List; - -/** - * 分布式ID测试类 - * - * @author 公众号:程序员小富 - * @date 2023/12/31 17:25 - */ -@Slf4j -@DisplayName("分布式ID测试类") -@SpringBootTest -class SequenceAlgorithmsTests { - @Resource - private JdbcTemplate jdbcTemplate; - - @Resource - private OrderMapper orderMapper; - - @DisplayName("测试分布式ID生成算法插入数据") - @Test - public void orderComplexCustomAlgorithmTest() { - - int randomId = RandomUtils.nextInt(); - OrderPo order = new OrderPo(); - order.setOrderId(20L); - order.setUserId(100L); - order.setOrderNumber(String.valueOf(randomId)); - order.setCustomerId((long) randomId); - order.setOrderDate(new Date()); - order.setTotalAmount(new BigDecimal("0")); - order.setIntervalValue("2024-03-01 00:00:00"); - orderMapper.insert(order); - } - - /** - * 查询标准策略 - * - * @author 公众号:程序员小富 - */ - @DisplayName("自动义分片算法-范围查询") - @Test - public void queryTableTest() { - QueryWrapper queryWrapper = new QueryWrapper() - .eq("order_id", 20L) - .eq("id", 20L); - queryWrapper.orderByAsc("order_id"); - List orderPos = orderMapper.selectList(queryWrapper); - log.info("查询结果:{}", JSON.toJSONString(orderPos)); - } -} diff --git a/springboot-demo/src/test/java/com/springboot101/BaseShare.java b/springboot-demo/src/test/java/com/springboot101/BaseShare.java index 7792a300..78266ff4 100644 --- a/springboot-demo/src/test/java/com/springboot101/BaseShare.java +++ b/springboot-demo/src/test/java/com/springboot101/BaseShare.java @@ -20,7 +20,7 @@ public void userServiceTest() { User user = new User(); user.setName("公众号:程序员小富"); user.setAge(0); - user.setEmail("vx:程序员小富521"); + user.setEmail("vx:xinzhifu521"); user.setCreateTime(new Date()); user.setUpdateTime(new Date()); userService.insertUser(user); diff --git a/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/IotMqttProducerConfig.java b/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/IotMqttProducerConfig.java index b0b7c3bd..ec88b32f 100644 --- a/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/IotMqttProducerConfig.java +++ b/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/IotMqttProducerConfig.java @@ -12,7 +12,7 @@ import org.springframework.messaging.MessageHandler; /** - * @Author: 程序员小富 + * @Author: xinzhifu * @Description: */ @Configuration diff --git a/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/MqttConfig.java b/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/MqttConfig.java index 128f8eb4..e575eb09 100644 --- a/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/MqttConfig.java +++ b/springboot101/MQTT/springboot-mqtt-messagepush/src/main/java/com/springboot101/config/MqttConfig.java @@ -7,7 +7,7 @@ import org.springframework.stereotype.Component; /** - * @Author: 程序员小富 + * @Author: xinzhifu * @Description: 基础配置类 * @date 2020/6/8 18:25 */ diff --git a/springboot101/README.md b/springboot101/README.md index 566526c2..e69de29b 100644 --- a/springboot101/README.md +++ b/springboot101/README.md @@ -1,33 +0,0 @@ -## SpringBoot101 - -SpringBoot101 是一个SpringBoot从入门到精通的系列教程, - -## 基础 -- Springboot hello(脚手架) - -## 基础 -- springboot多环境打包配置 - -## 模版引擎 -- springboot整合Thymeleaf模板 -- springboot整合Jsp模板 -- springboot整合FreeMarker模板 -- springboot整合Velocity模板 - -## 通用 - -- Springboot自定义启动banner -- Springboot 如何构建一个 RESTful 风格的 Web 服务 -- Springboot 统一返回值 -- Springboot 全局异常捕获 -- Springboot 6种读取配置文件的方案 -- Springboot 3种全局时间格式化方案 -- Springboot 实现flowable工作流 -- Springboot 自定义注解实现Log日志打印 -- Springboot 防盗链的实现 -- Springboot 自定义拦截器 -- Springboot 自定义过滤器 -- Springboot 自定义注解实现AOP切面 -- Springboot 十五个拓展点 - - diff --git a/springboot101/pom.xml b/springboot101/pom.xml index d6a63145..01bcf71c 100644 --- a/springboot101/pom.xml +++ b/springboot101/pom.xml @@ -44,21 +44,10 @@ 通用功能/springboot-global-formatting 通用功能/springboot-jasypt 通用功能/springboot-banner - 通用功能/springboot-valid-params - 通用功能/springboot-streaming 接口文档/springboot-swagger 接口文档/springboot-knife4j - - - 设计模式/springboot-design-chain - - - 模版引擎/springboot-thymeleaf - - - 数据库/springboot-dynamic-datasource diff --git a/springboot101/redis/springboot-aop-redis-lua/pom.xml b/springboot101/redis/springboot-aop-redis-lua/pom.xml index 5718fb79..e10e955b 100644 --- a/springboot101/redis/springboot-aop-redis-lua/pom.xml +++ b/springboot101/redis/springboot-aop-redis-lua/pom.xml @@ -25,7 +25,7 @@ com.google.guava guava - 32.0.0-jre + 29.0-jre diff --git a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/controller/WebhookController.java b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/controller/WebhookController.java index eccda3b2..ae20dc11 100644 --- a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/controller/WebhookController.java +++ b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/controller/WebhookController.java @@ -4,8 +4,7 @@ import com.springboot101.utils.HttpUtil; import com.springboot101.vo.GithubWebhookPullVo; import com.springboot101.vo.WeChatWebhook; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @@ -15,9 +14,10 @@ import java.util.Date; import java.util.List; +@Slf4j @RestController public class WebhookController { - private static final Logger log = LoggerFactory.getLogger(HttpUtil.class); + private static final String WECHAT_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=145a516a-dd15-421f-97a3-ba3bf1479369"; private static final String GITHUB_API = "https://api.github.com/users/"; diff --git a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/utils/HttpUtil.java b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/utils/HttpUtil.java index 3c391919..f24b5230 100644 --- a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/utils/HttpUtil.java +++ b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/utils/HttpUtil.java @@ -1,5 +1,6 @@ package com.springboot101.utils; +import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; @@ -8,8 +9,6 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.IOException; @@ -20,9 +19,8 @@ * @Description: */ @Component - +@Slf4j public class HttpUtil { - private static final Logger log = LoggerFactory.getLogger(HttpUtil.class); /** * 发送post请求 diff --git a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/GithubWebhookPullVo.java b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/GithubWebhookPullVo.java index 1f8c4463..51f7ec17 100644 --- a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/GithubWebhookPullVo.java +++ b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/GithubWebhookPullVo.java @@ -12,7 +12,10 @@ * @date 2021/05/19 */ @NoArgsConstructor +@Data public class GithubWebhookPullVo { + + @JsonProperty("ref") private String ref; @JsonProperty("before") @@ -40,205 +43,8 @@ public class GithubWebhookPullVo { @JsonProperty("head_commit") private HeadCommitDTO headCommit; - public String getRef() { - return ref; - } - - @NoArgsConstructor - @Data - public static class PusherDTO { - @JsonProperty("name") - private String name; - @JsonProperty("email") - private String email; - } - - @NoArgsConstructor - @Data - public static class SenderDTO { - @JsonProperty("login") - private String login; - @JsonProperty("id") - private Integer id; - @JsonProperty("node_id") - private String nodeId; - @JsonProperty("avatar_url") - private String avatarUrl; - @JsonProperty("gravatar_id") - private String gravatarId; - @JsonProperty("url") - private String url; - @JsonProperty("html_url") - private String htmlUrl; - @JsonProperty("followers_url") - private String followersUrl; - @JsonProperty("following_url") - private String followingUrl; - @JsonProperty("gists_url") - private String gistsUrl; - @JsonProperty("starred_url") - private String starredUrl; - @JsonProperty("subscriptions_url") - private String subscriptionsUrl; - @JsonProperty("organizations_url") - private String organizationsUrl; - @JsonProperty("repos_url") - private String reposUrl; - @JsonProperty("events_url") - private String eventsUrl; - @JsonProperty("received_events_url") - private String receivedEventsUrl; - @JsonProperty("type") - private String type; - @JsonProperty("site_admin") - private Boolean siteAdmin; - } - @NoArgsConstructor @Data - public static class HeadCommitDTO { - @JsonProperty("id") - private String id; - @JsonProperty("tree_id") - private String treeId; - @JsonProperty("distinct") - private Boolean distinct; - @JsonProperty("message") - private String message; - @JsonProperty("timestamp") - private String timestamp; - @JsonProperty("url") - private String url; - @JsonProperty("author") - private AuthorDTO author; - @JsonProperty("committer") - private CommitterDTO committer; - @JsonProperty("added") - private List added; - @JsonProperty("removed") - private List removed; - @JsonProperty("modified") - private List modified; - - @NoArgsConstructor - @Data - public static class AuthorDTO { - @JsonProperty("name") - private String name; - @JsonProperty("email") - private String email; - } - - @NoArgsConstructor - @Data - public static class CommitterDTO { - @JsonProperty("name") - private String name; - @JsonProperty("email") - private String email; - } - } - - public void setRef(String ref) { - this.ref = ref; - } - - public String getBefore() { - return before; - } - - public void setBefore(String before) { - this.before = before; - } - - public String getAfter() { - return after; - } - - public void setAfter(String after) { - this.after = after; - } - - public RepositoryDTO getRepository() { - return repository; - } - - public void setRepository(RepositoryDTO repository) { - this.repository = repository; - } - - public PusherDTO getPusher() { - return pusher; - } - - public void setPusher(PusherDTO pusher) { - this.pusher = pusher; - } - - public SenderDTO getSender() { - return sender; - } - - public void setSender(SenderDTO sender) { - this.sender = sender; - } - - public Boolean getCreated() { - return created; - } - - public void setCreated(Boolean created) { - this.created = created; - } - - public Boolean getDeleted() { - return deleted; - } - - public void setDeleted(Boolean deleted) { - this.deleted = deleted; - } - - public Boolean getForced() { - return forced; - } - - public void setForced(Boolean forced) { - this.forced = forced; - } - - public Object getBaseRef() { - return baseRef; - } - - public void setBaseRef(Object baseRef) { - this.baseRef = baseRef; - } - - public String getCompare() { - return compare; - } - - public void setCompare(String compare) { - this.compare = compare; - } - - public List getCommits() { - return commits; - } - - public void setCommits(List commits) { - this.commits = commits; - } - - public HeadCommitDTO getHeadCommit() { - return headCommit; - } - - public void setHeadCommit(HeadCommitDTO headCommit) { - this.headCommit = headCommit; - } - public static class RepositoryDTO { @JsonProperty("id") private Integer id; @@ -391,653 +197,149 @@ public static class RepositoryDTO { @JsonProperty("master_branch") private String masterBranch; - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getNodeId() { - return nodeId; - } - - public void setNodeId(String nodeId) { - this.nodeId = nodeId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; + @NoArgsConstructor + @Data + public static class OwnerDTO { + @JsonProperty("name") + private String name; + @JsonProperty("email") + private String email; + @JsonProperty("login") + private String login; + @JsonProperty("id") + private Integer id; + @JsonProperty("node_id") + private String nodeId; + @JsonProperty("avatar_url") + private String avatarUrl; + @JsonProperty("gravatar_id") + private String gravatarId; + @JsonProperty("url") + private String url; + @JsonProperty("html_url") + private String htmlUrl; + @JsonProperty("followers_url") + private String followersUrl; + @JsonProperty("following_url") + private String followingUrl; + @JsonProperty("gists_url") + private String gistsUrl; + @JsonProperty("starred_url") + private String starredUrl; + @JsonProperty("subscriptions_url") + private String subscriptionsUrl; + @JsonProperty("organizations_url") + private String organizationsUrl; + @JsonProperty("repos_url") + private String reposUrl; + @JsonProperty("events_url") + private String eventsUrl; + @JsonProperty("received_events_url") + private String receivedEventsUrl; + @JsonProperty("type") + private String type; + @JsonProperty("site_admin") + private Boolean siteAdmin; } + } - public Boolean getPrivateX() { - return privateX; - } + @NoArgsConstructor + @Data + public static class PusherDTO { + @JsonProperty("name") + private String name; + @JsonProperty("email") + private String email; + } - public void setPrivateX(Boolean privateX) { - this.privateX = privateX; - } + @NoArgsConstructor + @Data + public static class SenderDTO { + @JsonProperty("login") + private String login; + @JsonProperty("id") + private Integer id; + @JsonProperty("node_id") + private String nodeId; + @JsonProperty("avatar_url") + private String avatarUrl; + @JsonProperty("gravatar_id") + private String gravatarId; + @JsonProperty("url") + private String url; + @JsonProperty("html_url") + private String htmlUrl; + @JsonProperty("followers_url") + private String followersUrl; + @JsonProperty("following_url") + private String followingUrl; + @JsonProperty("gists_url") + private String gistsUrl; + @JsonProperty("starred_url") + private String starredUrl; + @JsonProperty("subscriptions_url") + private String subscriptionsUrl; + @JsonProperty("organizations_url") + private String organizationsUrl; + @JsonProperty("repos_url") + private String reposUrl; + @JsonProperty("events_url") + private String eventsUrl; + @JsonProperty("received_events_url") + private String receivedEventsUrl; + @JsonProperty("type") + private String type; + @JsonProperty("site_admin") + private Boolean siteAdmin; + } - public OwnerDTO getOwner() { - return owner; - } - - public void setOwner(OwnerDTO owner) { - this.owner = owner; - } - - public String getHtmlUrl() { - return htmlUrl; - } - - public void setHtmlUrl(String htmlUrl) { - this.htmlUrl = htmlUrl; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Boolean getFork() { - return fork; - } - - public void setFork(Boolean fork) { - this.fork = fork; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getForksUrl() { - return forksUrl; - } - - public void setForksUrl(String forksUrl) { - this.forksUrl = forksUrl; - } - - public String getKeysUrl() { - return keysUrl; - } - - public void setKeysUrl(String keysUrl) { - this.keysUrl = keysUrl; - } - - public String getCollaboratorsUrl() { - return collaboratorsUrl; - } - - public void setCollaboratorsUrl(String collaboratorsUrl) { - this.collaboratorsUrl = collaboratorsUrl; - } - - public String getTeamsUrl() { - return teamsUrl; - } - - public void setTeamsUrl(String teamsUrl) { - this.teamsUrl = teamsUrl; - } - - public String getHooksUrl() { - return hooksUrl; - } - - public void setHooksUrl(String hooksUrl) { - this.hooksUrl = hooksUrl; - } - - public String getIssueEventsUrl() { - return issueEventsUrl; - } - - public void setIssueEventsUrl(String issueEventsUrl) { - this.issueEventsUrl = issueEventsUrl; - } - - public String getEventsUrl() { - return eventsUrl; - } - - public void setEventsUrl(String eventsUrl) { - this.eventsUrl = eventsUrl; - } - - public String getAssigneesUrl() { - return assigneesUrl; - } - - public void setAssigneesUrl(String assigneesUrl) { - this.assigneesUrl = assigneesUrl; - } - - public String getBranchesUrl() { - return branchesUrl; - } - - public void setBranchesUrl(String branchesUrl) { - this.branchesUrl = branchesUrl; - } - - public String getTagsUrl() { - return tagsUrl; - } - - public void setTagsUrl(String tagsUrl) { - this.tagsUrl = tagsUrl; - } - - public String getBlobsUrl() { - return blobsUrl; - } - - public void setBlobsUrl(String blobsUrl) { - this.blobsUrl = blobsUrl; - } - - public String getGitTagsUrl() { - return gitTagsUrl; - } - - public void setGitTagsUrl(String gitTagsUrl) { - this.gitTagsUrl = gitTagsUrl; - } - - public String getGitRefsUrl() { - return gitRefsUrl; - } - - public void setGitRefsUrl(String gitRefsUrl) { - this.gitRefsUrl = gitRefsUrl; - } - - public String getTreesUrl() { - return treesUrl; - } - - public void setTreesUrl(String treesUrl) { - this.treesUrl = treesUrl; - } - - public String getStatusesUrl() { - return statusesUrl; - } - - public void setStatusesUrl(String statusesUrl) { - this.statusesUrl = statusesUrl; - } - - public String getLanguagesUrl() { - return languagesUrl; - } - - public void setLanguagesUrl(String languagesUrl) { - this.languagesUrl = languagesUrl; - } - - public String getStargazersUrl() { - return stargazersUrl; - } - - public void setStargazersUrl(String stargazersUrl) { - this.stargazersUrl = stargazersUrl; - } - - public String getContributorsUrl() { - return contributorsUrl; - } - - public void setContributorsUrl(String contributorsUrl) { - this.contributorsUrl = contributorsUrl; - } - - public String getSubscribersUrl() { - return subscribersUrl; - } - - public void setSubscribersUrl(String subscribersUrl) { - this.subscribersUrl = subscribersUrl; - } - - public String getSubscriptionUrl() { - return subscriptionUrl; - } - - public void setSubscriptionUrl(String subscriptionUrl) { - this.subscriptionUrl = subscriptionUrl; - } - - public String getCommitsUrl() { - return commitsUrl; - } - - public void setCommitsUrl(String commitsUrl) { - this.commitsUrl = commitsUrl; - } - - public String getGitCommitsUrl() { - return gitCommitsUrl; - } - - public void setGitCommitsUrl(String gitCommitsUrl) { - this.gitCommitsUrl = gitCommitsUrl; - } - - public String getCommentsUrl() { - return commentsUrl; - } - - public void setCommentsUrl(String commentsUrl) { - this.commentsUrl = commentsUrl; - } - - public String getIssueCommentUrl() { - return issueCommentUrl; - } - - public void setIssueCommentUrl(String issueCommentUrl) { - this.issueCommentUrl = issueCommentUrl; - } - - public String getContentsUrl() { - return contentsUrl; - } - - public void setContentsUrl(String contentsUrl) { - this.contentsUrl = contentsUrl; - } - - public String getCompareUrl() { - return compareUrl; - } - - public void setCompareUrl(String compareUrl) { - this.compareUrl = compareUrl; - } - - public String getMergesUrl() { - return mergesUrl; - } - - public void setMergesUrl(String mergesUrl) { - this.mergesUrl = mergesUrl; - } - - public String getArchiveUrl() { - return archiveUrl; - } - - public void setArchiveUrl(String archiveUrl) { - this.archiveUrl = archiveUrl; - } - - public String getDownloadsUrl() { - return downloadsUrl; - } - - public void setDownloadsUrl(String downloadsUrl) { - this.downloadsUrl = downloadsUrl; - } - - public String getIssuesUrl() { - return issuesUrl; - } - - public void setIssuesUrl(String issuesUrl) { - this.issuesUrl = issuesUrl; - } - - public String getPullsUrl() { - return pullsUrl; - } - - public void setPullsUrl(String pullsUrl) { - this.pullsUrl = pullsUrl; - } - - public String getMilestonesUrl() { - return milestonesUrl; - } - - public void setMilestonesUrl(String milestonesUrl) { - this.milestonesUrl = milestonesUrl; - } - - public String getNotificationsUrl() { - return notificationsUrl; - } - - public void setNotificationsUrl(String notificationsUrl) { - this.notificationsUrl = notificationsUrl; - } - - public String getLabelsUrl() { - return labelsUrl; - } - - public void setLabelsUrl(String labelsUrl) { - this.labelsUrl = labelsUrl; - } - - public String getReleasesUrl() { - return releasesUrl; - } - - public void setReleasesUrl(String releasesUrl) { - this.releasesUrl = releasesUrl; - } - - public String getDeploymentsUrl() { - return deploymentsUrl; - } - - public void setDeploymentsUrl(String deploymentsUrl) { - this.deploymentsUrl = deploymentsUrl; - } - - public Integer getCreatedAt() { - return createdAt; - } - - public void setCreatedAt(Integer createdAt) { - this.createdAt = createdAt; - } - - public String getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(String updatedAt) { - this.updatedAt = updatedAt; - } - - public Integer getPushedAt() { - return pushedAt; - } - - public void setPushedAt(Integer pushedAt) { - this.pushedAt = pushedAt; - } - - public String getGitUrl() { - return gitUrl; - } - - public void setGitUrl(String gitUrl) { - this.gitUrl = gitUrl; - } - - public String getSshUrl() { - return sshUrl; - } - - public void setSshUrl(String sshUrl) { - this.sshUrl = sshUrl; - } - - public String getCloneUrl() { - return cloneUrl; - } - - public void setCloneUrl(String cloneUrl) { - this.cloneUrl = cloneUrl; - } - - public String getSvnUrl() { - return svnUrl; - } - - public void setSvnUrl(String svnUrl) { - this.svnUrl = svnUrl; - } - - public String getHomepage() { - return homepage; - } - - public void setHomepage(String homepage) { - this.homepage = homepage; - } - - public Integer getSize() { - return size; - } - - public void setSize(Integer size) { - this.size = size; - } - - public Integer getStargazersCount() { - return stargazersCount; - } - - public void setStargazersCount(Integer stargazersCount) { - this.stargazersCount = stargazersCount; - } - - public Integer getWatchersCount() { - return watchersCount; - } - - public void setWatchersCount(Integer watchersCount) { - this.watchersCount = watchersCount; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public Boolean getHasIssues() { - return hasIssues; - } - - public void setHasIssues(Boolean hasIssues) { - this.hasIssues = hasIssues; - } - - public Boolean getHasProjects() { - return hasProjects; - } - - public void setHasProjects(Boolean hasProjects) { - this.hasProjects = hasProjects; - } - - public Boolean getHasDownloads() { - return hasDownloads; - } - - public void setHasDownloads(Boolean hasDownloads) { - this.hasDownloads = hasDownloads; - } - - public Boolean getHasWiki() { - return hasWiki; - } - - public void setHasWiki(Boolean hasWiki) { - this.hasWiki = hasWiki; - } - - public Boolean getHasPages() { - return hasPages; - } - - public void setHasPages(Boolean hasPages) { - this.hasPages = hasPages; - } - - public Integer getForksCount() { - return forksCount; - } - - public void setForksCount(Integer forksCount) { - this.forksCount = forksCount; - } - - public Object getMirrorUrl() { - return mirrorUrl; - } - - public void setMirrorUrl(Object mirrorUrl) { - this.mirrorUrl = mirrorUrl; - } - - public Boolean getArchived() { - return archived; - } - - public void setArchived(Boolean archived) { - this.archived = archived; - } - - public Boolean getDisabled() { - return disabled; - } - - public void setDisabled(Boolean disabled) { - this.disabled = disabled; - } - - public Integer getOpenIssuesCount() { - return openIssuesCount; - } - - public void setOpenIssuesCount(Integer openIssuesCount) { - this.openIssuesCount = openIssuesCount; - } - - public Object getLicense() { - return license; - } - - public void setLicense(Object license) { - this.license = license; - } - - public Integer getForks() { - return forks; - } - - public void setForks(Integer forks) { - this.forks = forks; - } - - public Integer getOpenIssues() { - return openIssues; - } - - public void setOpenIssues(Integer openIssues) { - this.openIssues = openIssues; - } - - public Integer getWatchers() { - return watchers; - } - - public void setWatchers(Integer watchers) { - this.watchers = watchers; - } - - public String getDefaultBranch() { - return defaultBranch; - } - - public void setDefaultBranch(String defaultBranch) { - this.defaultBranch = defaultBranch; - } - - public Integer getStargazers() { - return stargazers; - } - - public void setStargazers(Integer stargazers) { - this.stargazers = stargazers; - } - - public String getMasterBranch() { - return masterBranch; - } + @NoArgsConstructor + @Data + public static class HeadCommitDTO { + @JsonProperty("id") + private String id; + @JsonProperty("tree_id") + private String treeId; + @JsonProperty("distinct") + private Boolean distinct; + @JsonProperty("message") + private String message; + @JsonProperty("timestamp") + private String timestamp; + @JsonProperty("url") + private String url; + @JsonProperty("author") + private AuthorDTO author; + @JsonProperty("committer") + private CommitterDTO committer; + @JsonProperty("added") + private List added; + @JsonProperty("removed") + private List removed; + @JsonProperty("modified") + private List modified; - public void setMasterBranch(String masterBranch) { - this.masterBranch = masterBranch; + @NoArgsConstructor + @Data + public static class AuthorDTO { + @JsonProperty("name") + private String name; + @JsonProperty("email") + private String email; } @NoArgsConstructor @Data - public static class OwnerDTO { + public static class CommitterDTO { @JsonProperty("name") private String name; @JsonProperty("email") private String email; - @JsonProperty("login") - private String login; - @JsonProperty("id") - private Integer id; - @JsonProperty("node_id") - private String nodeId; - @JsonProperty("avatar_url") - private String avatarUrl; - @JsonProperty("gravatar_id") - private String gravatarId; - @JsonProperty("url") - private String url; - @JsonProperty("html_url") - private String htmlUrl; - @JsonProperty("followers_url") - private String followersUrl; - @JsonProperty("following_url") - private String followingUrl; - @JsonProperty("gists_url") - private String gistsUrl; - @JsonProperty("starred_url") - private String starredUrl; - @JsonProperty("subscriptions_url") - private String subscriptionsUrl; - @JsonProperty("organizations_url") - private String organizationsUrl; - @JsonProperty("repos_url") - private String reposUrl; - @JsonProperty("events_url") - private String eventsUrl; - @JsonProperty("received_events_url") - private String receivedEventsUrl; - @JsonProperty("type") - private String type; - @JsonProperty("site_admin") - private Boolean siteAdmin; } } @NoArgsConstructor + @Data public static class CommitsDTO { @JsonProperty("id") private String id; @@ -1062,94 +364,6 @@ public static class CommitsDTO { @JsonProperty("modified") private List modified; - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getTreeId() { - return treeId; - } - - public void setTreeId(String treeId) { - this.treeId = treeId; - } - - public Boolean getDistinct() { - return distinct; - } - - public void setDistinct(Boolean distinct) { - this.distinct = distinct; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String timestamp) { - this.timestamp = timestamp; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public AuthorDTO getAuthor() { - return author; - } - - public void setAuthor(AuthorDTO author) { - this.author = author; - } - - public CommitterDTO getCommitter() { - return committer; - } - - public void setCommitter(CommitterDTO committer) { - this.committer = committer; - } - - public List getAdded() { - return added; - } - - public void setAdded(List added) { - this.added = added; - } - - public List getRemoved() { - return removed; - } - - public void setRemoved(List removed) { - this.removed = removed; - } - - public List getModified() { - return modified; - } - - public void setModified(List modified) { - this.modified = modified; - } - @NoArgsConstructor @Data public static class AuthorDTO { @@ -1159,27 +373,13 @@ public static class AuthorDTO { private String email; } + @NoArgsConstructor + @Data public static class CommitterDTO { @JsonProperty("name") private String name; @JsonProperty("email") private String email; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } } } } diff --git a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/WeChatWebhook.java b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/WeChatWebhook.java index 71de12af..c06d55fa 100644 --- a/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/WeChatWebhook.java +++ b/springboot101/webhook/springboot-webhook-wechat/src/main/java/com/springboot101/vo/WeChatWebhook.java @@ -1,4 +1,6 @@ -package com.springboot101.vo; +package com.springboot101.vo;//package com.springboot101.webhook.vo; + +import lombok.Data; import java.util.List; @@ -7,28 +9,14 @@ * @Date: 2021/5/19 20:56 * @Description: */ +@Data public class WeChatWebhook { private String msgtype; private TextDTO text; - public String getMsgtype() { - return msgtype; - } - - public void setMsgtype(String msgtype) { - this.msgtype = msgtype; - } - - public TextDTO getText() { - return text; - } - - public void setText(TextDTO text) { - this.text = text; - } - + @Data public static class TextDTO { private String content; @@ -36,29 +24,5 @@ public static class TextDTO { private List mentionedList; private List mentionedMobileList; - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public List getMentionedList() { - return mentionedList; - } - - public void setMentionedList(List mentionedList) { - this.mentionedList = mentionedList; - } - - public List getMentionedMobileList() { - return mentionedMobileList; - } - - public void setMentionedMobileList(List mentionedMobileList) { - this.mentionedMobileList = mentionedMobileList; - } } } diff --git "a/springboot101/\344\272\272\350\204\270\350\257\206\345\210\253/springboot-detect-faces/src/main/java/com/springboot101/service/FaceEngineServiceImpl.java" "b/springboot101/\344\272\272\350\204\270\350\257\206\345\210\253/springboot-detect-faces/src/main/java/com/springboot101/service/FaceEngineServiceImpl.java" index 24503f12..15f59eda 100644 --- "a/springboot101/\344\272\272\350\204\270\350\257\206\345\210\253/springboot-detect-faces/src/main/java/com/springboot101/service/FaceEngineServiceImpl.java" +++ "b/springboot101/\344\272\272\350\204\270\350\257\206\345\210\253/springboot-detect-faces/src/main/java/com/springboot101/service/FaceEngineServiceImpl.java" @@ -9,7 +9,6 @@ import com.arcsoft.face.toolkit.ImageInfo; import com.springboot101.entity.User; import com.springboot101.repository.UserDao; -import com.springboot101.util.Base64Util; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; diff --git "a/springboot101/\344\275\216\344\273\243\347\240\201/springboot-magic-api/src/main/resources/application.yml" "b/springboot101/\344\275\216\344\273\243\347\240\201/springboot-magic-api/src/main/resources/application.yml" index ed0f99e6..c3f8c52b 100644 --- "a/springboot101/\344\275\216\344\273\243\347\240\201/springboot-magic-api/src/main/resources/application.yml" +++ "b/springboot101/\344\275\216\344\273\243\347\240\201/springboot-magic-api/src/main/resources/application.yml" @@ -49,6 +49,6 @@ server: spring: datasource: driver-class-name: com.mysql.jdbc.Driver - password: 123456 + password: xinzhifu521 url: jdbc:mysql://47.93.6.5:3306/magic-api?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root diff --git "a/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/README.md" "b/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/README.md" index 22cc5ac0..2f4c0d31 100644 --- "a/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/README.md" +++ "b/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/README.md" @@ -1,3 +1,256 @@ -### 本案例对应的文章教程 -[我有 7种 实现web实时消息推送的方案,7种!](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247500543&idx=1&sn=2a75dbd8846b1c0ea6ce6c59dfb98cef&chksm=9b865202acf1db14009f2d5bedc463396ed0ac213de1dcc2eaf3daf378996c6f4a0353306f4b&token=755618913&lang=zh_CN#rd) +**大家好,我是小富~** + +我有一个朋友~ + +做了一个小破站,现在要实现一个站内信web消息推送的功能,对,就是下图这个小红点,一个很常用的功能。 + +![](https://files.mdnice.com/order/303/b713bf50-6512-464e-b684-29589f8677b9.png) + +不过他还没想好用什么方式做,这里我帮他整理了一下几种实现方案。 + +![](https://files.mdnice.com/order/303/130a09a0-70fa-4991-81a7-1f7ed0dfbfd9.png) + +### 什么是消息推送(push) + +消息推送(`push`)通常是指网站的运营工作等人员,通过某种工具对用户当前网页或移动设备APP进行的主动消息推送。 + +推送的场景比较多,比如有人关注我的公众号,这时我就会收到一条推送消息,以此来吸引我点击打开应用,消息推送一般又分为`web端消息推送`和`移动端消息推送`。 + +![](https://img-blog.csdnimg.cn/d5b8617c37fd489896603d562f8a98c1.png) + +上边的这种属于移动端消息推送,web端消息推送常见的诸如站内信、未读邮件数量、监控报警数量等,应用的也非常广泛。 + + +![](https://img-blog.csdnimg.cn/img_convert/15ead5d6e8b7afcfdccbcec02a181301.png) + + +在具体实现之前,咱们再来分析一下前边的需求,其实功能很简单,只要触发某个事件(主动分享了资源或者后台主动推送消息),web页面的通知小红点就会实时的`+1`就可以了。 + +消息推送无非是推(`push`)和拉(`pull`)两种形式。通常在服务端会有若干张消息推送表,用来记录用户触发不同事件所推送不同类型的消息,前端主动查询(拉)或者被动接收(推)用户所有未读的消息数。 + +![](https://img-blog.csdnimg.cn/img_convert/198443b7c2f609da3bdf5b507bca0918.png) + + +### 短轮询 + +轮询(`polling`)应该是实现消息推送方案中最简单的一种,这里我们暂且将轮询分为`短轮询`和`长轮询`。 + +短轮询很好理解,指定的时间间隔,由浏览器向服务器发出`HTTP`请求,服务器实时返回未读消息数据给客户端,浏览器再做渲染显示。 + + +![](https://files.mdnice.com/order/303/65699788-5f1c-4f9d-acea-9187a1f25b62.png) + + +一个简单的JS定时器就可以搞定,每秒钟请求一次未读消息数接口,返回的数据展示即可。 + +``` +setInterval(() => { + // 方法请求 + messageCount().then((res) => { + if (res.code === 200) { + this.messageCount = res.data + } + }) +}, 1000); +``` + + +是我们期望的效果,用短轮询实现固然简单,缺点也是显而易见,由于推送数据并不会频繁变更,无论后端此时是否有新的消息产生,客户端都会进行请求,势必会对服务端造成很大压力,浪费带宽和服务器资源。 + +![](https://files.mdnice.com/order/303/5738e243-a0fb-41fd-83fb-59f868b249b3.gif) + + +### 长轮询 + +长轮询是对上边短轮询的一种改进版本,之前我在[Nacos配置中心交互模型是 push 还是 pull ?(原理+源码分析)](https://mp.weixin.qq.com/s/94ftESkDoZI9gAGflLiGwg)一文中就详细介绍过,`Nacos`的配置中心就是基于长轮询方式实现的,可以说用的很溜了,感兴趣的可以了解下。 + + +短轮询的弊端是有太多无效的请求,那么如果控制住请求的频率是不是就行了? + +我们按照`Nacos`的思路简单实现一下,对于客户端发送的请求,服务端不再立即响应, + +![](https://files.mdnice.com/order/303/e60a84bc-029a-4d1b-b02d-49f0d9e98689.png) + + + + + + + + +https://mp.weixin.qq.com/s/94ftESkDoZI9gAGflLiGwg + +https://blog.csdn.net/xingxinggua9620/article/details/113565073 + +https://wenku.baidu.com/view/d4cb42deadf8941ea76e58fafab069dc502247a5.html + +### iframe流 + +iframe流就是在页面中插入一个隐藏的` +``` + +服务端直接组装html、js脚本数据向`response`写入就行了 + +``` +@Controller +@RequestMapping("/iframe") +public class IframeController { + @GetMapping(path = "message") + public void message(HttpServletResponse response) throws IOException, InterruptedException { + while (true) { + response.setHeader("Pragma", "no-cache"); + response.setDateHeader("Expires", 0); + response.setHeader("Cache-Control", "no-cache,no-store"); + response.setStatus(HttpServletResponse.SC_OK); + response.getWriter().print(" "); + } + } +} +``` + +但我个人不推荐,因为它在浏览器上会显示请求未加载完,图标会不停旋转,简直是强迫症杀手。 + +![](https://files.mdnice.com/order/303/c4887635-4e93-40a8-a929-5d1d8476f5ea.gif) + +### SSE (推荐的方式) + +很多人可能不知道,服务端向客户端推送消息,其实除了可以用`WebSocket`这种耳熟能详的机制外,还有一种服务器发送事件(`Server-sent events`),简称`SSE`。 + + +`SSE`它是基于`HTTP`协议的,我们知道一般意义上的HTTP协议是无法做到服务端主动向客户端推送消息的,但SSE是个例外,它变换了一种思路。 + +![](https://files.mdnice.com/order/303/785e576a-122c-4f7f-b494-f1e317fdd290.png) + + +SSE在服务器和客户端之间打开一个单向通道,服务端响应的不再是一次性的数据包而是`text/event-stream`类型的数据流信息,在有数据变更时从服务器流式传输到客户端。 + +整体的实现思路有点类似于在线视频播放,视频流会连续不断的推送到浏览器,你也可以理解成,客户端在完成一次用时很长(网络不畅)的下载。 + +![](https://files.mdnice.com/order/303/e51fb2c5-a713-450e-bdc3-98cee87b32e7.png) + +`SSE`与`WebSocket`作用相似,都可以建立服务端与浏览器之间的通信,实现服务端向客户端推送消息,但还是有些许不同: + +- SSE 是基于HTTP协议的,它们不需要特殊的协议或服务器实现即可工作;`WebSocket`需单独服务器来处理协议。 +- SSE 单向通信,只能由服务端向客户端单向通信;webSocket全双工通信,即通信的双方可以同时发送和接受信息。 +- SSE 实现简单开发成本低,无需引入其他组件;WebSocket传输数据需做二次解析,开发门槛高一些。 +- SSE 默认支持断线重连;WebSocket则需要自己实现。 +- SSE 只能传送文本消息,二进制数据需要经过编码后传送;WebSocket默认支持传送二进制数据。 + +**SSE与WebSocket该如何选择?** + +>技术并没有好坏之分,只有哪个更合适某个场景 + + +SSE 一直被隐藏起来的一个原因是因为后来的 API(如WebSockets )提供了更丰富的协议来执行双向、全双工通信。对于游戏、消息传递应用程序以及需要双向近乎实时更新的情况,拥有双向通道更具吸引力。但是,在某些情况下,不需要从客户端发送数据。您只需要一些服务器操作的更新。一些例子是朋友的状态更新、股票行情、新闻提要或其他自动数据推送机制(例如更新客户端 Web SQL 数据库或 IndexedDB 对象存储)。如果您需要将数据发送到服务器,XMLHttpRequest永远是朋友。 + +SSE 通过传统的 HTTP 发送。这意味着它们不需要特殊的协议或服务器实现即可工作。另一方面,WebSockets 需要全双工连接和新的 Web Socket 服务器来处理协议。此外,Server-Sent Events 具有 WebSockets 在设计上缺乏的多种功能,例如自动重新连接、事件 ID和发送任意事件的能力。 + +```javascript + +``` + +我们模拟服务端推送消息,看下客户端收到了消息,和我们预期的效果一致。 +![](https://files.mdnice.com/order/303/9d79d86d-c84d-43b1-aebc-53ecf384f7b8.gif) + + +SSE不支持 IE 浏览器,其他主流浏览器兼容性做的还不错。 +![](https://files.mdnice.com/order/303/27c6fd5d-a4c0-4a80-bb81-0aacd1c89f03.png) + + + +### MQTT + +### websocket + +http://demos.workerman.net/web-sender/ + + +### MQ + +### goEasy + +https://blog.csdn.net/windrainpy/article/details/105026780 + +https://www.kancloud.cn/fundebug/fundebug-blog/994905 + +https://www.cxyzjd.com/article/momolela/53113598 + +https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html + +https://www.cnblogs.com/hzb462606/p/15422600.html + +https://developer.aliyun.com/article/693576 + +https://baijiahao.baidu.com/s?id=1710213737252683265&wfr=spider&for=pc + +https://blog.csdn.net/wuliu_forever/article/details/88883609 + +https://blog.csdn.net/hj7jay/article/details/89761047 \ No newline at end of file diff --git "a/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/IotMqttProducerConfig.java" "b/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/IotMqttProducerConfig.java" index 61f056a0..c72fe517 100644 --- "a/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/IotMqttProducerConfig.java" +++ "b/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/IotMqttProducerConfig.java" @@ -12,7 +12,7 @@ import org.springframework.messaging.MessageHandler; /** - * @Author: 程序员小富 + * @Author: xinzhifu * @Description: */ @Configuration diff --git "a/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/MqttConfig.java" "b/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/MqttConfig.java" index 128f8eb4..e575eb09 100644 --- "a/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/MqttConfig.java" +++ "b/springboot101/\345\256\236\346\227\266\346\216\250\351\200\201/springboot-realtime-data/src/main/java/com/springboot101/config/MqttConfig.java" @@ -7,7 +7,7 @@ import org.springframework.stereotype.Component; /** - * @Author: 程序员小富 + * @Author: xinzhifu * @Description: 基础配置类 * @date 2020/6/8 18:25 */ diff --git "a/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/config/FlowableConfig.java" "b/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/config/FlowableConfig.java" index a3b23ee6..4b391225 100644 --- "a/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/config/FlowableConfig.java" +++ "b/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/config/FlowableConfig.java" @@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration; /** - * @author 程序员小富 + * @author xinzhifu * @description 设置样式,解决中文乱码 * @date 2020/8/27 15:04 */ diff --git "a/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/controller/LeaveController.java" "b/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/controller/LeaveController.java" index 3fa36e69..9d46ba70 100644 --- "a/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/controller/LeaveController.java" +++ "b/springboot101/\345\267\245\344\275\234\346\265\201/springboot-work-flowable/src/main/java/com/springboot101/flowable/controller/LeaveController.java" @@ -55,7 +55,7 @@ public String startLeaveProcess(String staffId) { /** * @param taskId - * @author 程序员小富 + * @author xinzhifu * @description 批准 * @date 2020/8/27 14:30 */ @@ -74,7 +74,7 @@ public String applyTask(String taskId) { /** * @param taskId - * @author 程序员小富 + * @author xinzhifu * @description 驳回 * @date 2020/8/27 14:30 */ diff --git "a/springboot101/\346\216\245\345\217\243\346\226\207\346\241\243/springboot-swagger/README.md" "b/springboot101/\346\216\245\345\217\243\346\226\207\346\241\243/springboot-swagger/README.md" index 388ca51a..e7631789 100644 --- "a/springboot101/\346\216\245\345\217\243\346\226\207\346\241\243/springboot-swagger/README.md" +++ "b/springboot101/\346\216\245\345\217\243\346\226\207\346\241\243/springboot-swagger/README.md" @@ -1,4 +1,5 @@ -### 本案例对应的文章教程 +此项目为 springboot 脚手架 -[谁家面试往死里问 Swagger 啊?](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247504501&idx=1&sn=edf8fd2f154f9c9241eabdd839271320&chksm=9b864288acf1cb9ea9f5981b8f99a97517c90e99e5cc26155e751d5f0b7c6d132f61be615d95&token=755618913&lang=zh_CN#rd) +已经整合了 jpa 连接mysql,自动根据JAVA实体属性创建对应的表 +起新项目直接复制它即可 diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/README.md" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/README.md" deleted file mode 100644 index cb80a2fb..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/README.md" +++ /dev/null @@ -1 +0,0 @@ -springboot注解实现动态数据源切换 \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/pom.xml" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/pom.xml" deleted file mode 100644 index 17af33ed..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/pom.xml" +++ /dev/null @@ -1,75 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.7.6 - - com.dynamic - springboot-dynamic-datasource - 0.0.1-SNAPSHOT - - 8 - 8 - 3.5.3.1 - 8.0.32 - 1.2.6 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-web - - - - com.mysql - mysql-connector-j - ${mysql.connector.version} - - - - org.projectlombok - lombok - true - - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis.plus.version} - - - - com.alibaba - druid-spring-boot-starter - ${druid.version} - - - org.apache.commons - commons-lang3 - 3.7 - - - org.aspectj - aspectjweaver - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/sql/test.sql" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/sql/test.sql" deleted file mode 100644 index 78cfd049..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/sql/test.sql" +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE `t_dynamic_datasource_data` ( - `id` bigint(20) NOT NULL AUTO_INCREMENT, - `source_name` varchar(25) DEFAULT NULL, - PRIMARY KEY (`id`) -) ; - -insert into t_dynamic_datasource_data (source_name) value ('dynamic_datasource_master'); - -insert into t_dynamic_datasource_data (source_name) value ('dynamic_datasource_slave'); diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/DynamicDatasourceApplication.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/DynamicDatasourceApplication.java" deleted file mode 100644 index 75592071..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/DynamicDatasourceApplication.java" +++ /dev/null @@ -1,13 +0,0 @@ -package com.dynamic; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; - -@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) -public class DynamicDatasourceApplication { - - public static void main(String[] args) { - SpringApplication.run(DynamicDatasourceApplication.class, args); - } -} diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/aspect/DS.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/aspect/DS.java" deleted file mode 100644 index 9e1367e7..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/aspect/DS.java" +++ /dev/null @@ -1,18 +0,0 @@ -package com.dynamic.aspect; - -import java.lang.annotation.*; - -/** - * 定于数据源切换注解 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -public @interface DS { - // 默认数据源master - String value() default "master"; -} \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/aspect/DSAspect.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/aspect/DSAspect.java" deleted file mode 100644 index abbb28eb..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/aspect/DSAspect.java" +++ /dev/null @@ -1,44 +0,0 @@ -package com.dynamic.aspect; - -import com.dynamic.config.DataSourceContextHolder; -import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.stereotype.Component; - -import java.lang.reflect.Method; -import java.util.Objects; - -/** - * 实现@DS注解的AOP切面 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@Aspect -@Component -@Slf4j -public class DSAspect { - - @Pointcut("@annotation(com.dynamic.aspect.DS)") - public void dynamicDataSource() { - } - - @Around("dynamicDataSource()") - public Object datasourceAround(ProceedingJoinPoint point) throws Throwable { - MethodSignature signature = (MethodSignature) point.getSignature(); - Method method = signature.getMethod(); - DS ds = method.getAnnotation(DS.class); - if (Objects.nonNull(ds)) { - DataSourceContextHolder.setDataSource(ds.value()); - } - try { - return point.proceed(); - } finally { - DataSourceContextHolder.removeDataSource(); - } - } -} diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DataSourceContextHolder.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DataSourceContextHolder.java" deleted file mode 100644 index e00d3981..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DataSourceContextHolder.java" +++ /dev/null @@ -1,37 +0,0 @@ -package com.dynamic.config; - -/** - * ThreadLocal存放数据源变量 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -public class DataSourceContextHolder { - - private static final ThreadLocal DATASOURCE_HOLDER = new ThreadLocal<>(); - - /** - * 获取当前线程的数据源 - * - * @return 数据源名称 - */ - public static String getDataSource() { - return DATASOURCE_HOLDER.get(); - } - - /** - * 设置数据源 - * - * @param dataSourceName 数据源名称 - */ - public static void setDataSource(String dataSourceName) { - DATASOURCE_HOLDER.set(dataSourceName); - } - - /** - * 删除当前数据源 - */ - public static void removeDataSource() { - DATASOURCE_HOLDER.remove(); - } -} \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DateSourceConfig.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DateSourceConfig.java" deleted file mode 100644 index 11c9c1fd..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DateSourceConfig.java" +++ /dev/null @@ -1,44 +0,0 @@ -package com.dynamic.config; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; - -import javax.sql.DataSource; -import java.util.HashMap; -import java.util.Map; - -/** - * 注册多个数据源 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@Configuration -public class DateSourceConfig { - - @Bean - @ConfigurationProperties("spring.datasource.druid.master") - public DataSource dynamicDatasourceMaster() { - return DruidDataSourceBuilder.create().build(); - } - - @Bean - @ConfigurationProperties("spring.datasource.druid.slave") - public DataSource dynamicDatasourceSlave() { - return DruidDataSourceBuilder.create().build(); - } - - @Bean(name = "dynamicDataSource") - @Primary - public DynamicDataSource createDynamicDataSource() { - Map dataSourceMap = new HashMap<>(); - // 设置默认的数据源为Master - DataSource defaultDataSource = dynamicDatasourceMaster(); - dataSourceMap.put("master", defaultDataSource); - dataSourceMap.put("slave", dynamicDatasourceSlave()); - return new DynamicDataSource(defaultDataSource, dataSourceMap); - } -} \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DynamicDataSource.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DynamicDataSource.java" deleted file mode 100644 index 7f22cf36..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/config/DynamicDataSource.java" +++ /dev/null @@ -1,30 +0,0 @@ -package com.dynamic.config; - -import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; - -import javax.sql.DataSource; -import java.util.Map; - -/** - * 继承 AbstractRoutingDataSource - * 重置当前的数据库路由,实现切换成想要执行的目标数据库 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -public class DynamicDataSource extends AbstractRoutingDataSource { - - public DynamicDataSource(DataSource defaultDataSource, Map targetDataSources) { - super.setDefaultTargetDataSource(defaultDataSource); - super.setTargetDataSources(targetDataSources); - } - - /** - * 这一步是关键 - * @return - */ - @Override - protected Object determineCurrentLookupKey() { - return DataSourceContextHolder.getDataSource(); - } -} \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/controller/DynamicSwitchController.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/controller/DynamicSwitchController.java" deleted file mode 100644 index db3c1315..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/controller/DynamicSwitchController.java" +++ /dev/null @@ -1,64 +0,0 @@ -package com.dynamic.controller; - -import com.dynamic.aspect.DS; -import com.dynamic.config.DataSourceContextHolder; -import com.dynamic.dao.DynamicDatasourceDataMapper; -import com.dynamic.entity.DynamicDatasourceData; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; - -/** - * 动态数据源切换 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@RestController -public class DynamicSwitchController { - - @Resource - private DynamicDatasourceDataMapper dynamicDatasourceDataMapper; - - @GetMapping("/switchDataSource/{datasourceName}") - public String switchDataSource(@PathVariable("datasourceName") String datasourceName) { - DataSourceContextHolder.setDataSource(datasourceName); - DynamicDatasourceData dynamicDatasourceData = dynamicDatasourceDataMapper.selectOne(null); - DataSourceContextHolder.removeDataSource(); - return dynamicDatasourceData.getSourceName(); - } - - @DS(value = "master") - @GetMapping("/dbMaster") - public String dbMaster() { - DynamicDatasourceData dynamicDatasourceData = dynamicDatasourceDataMapper.selectOne(null); - return dynamicDatasourceData.getSourceName(); - } - - @DS(value = "slave") - @GetMapping("/dbSlave") - public String dbSlave() { - DynamicDatasourceData dynamicDatasourceData = dynamicDatasourceDataMapper.selectOne(null); - return dynamicDatasourceData.getSourceName(); - } - - - /** - * 验证一下事物控制 - */ -// @Transactional(rollbackFor = Exception.class) - @DS(value = "slave") - @GetMapping("/dbTestTransactional") - public void dbTestTransactional() { - - DynamicDatasourceData datasourceData = new DynamicDatasourceData(); - datasourceData.setSourceName("test"); - dynamicDatasourceDataMapper.insert(datasourceData); - - DynamicDatasourceData datasourceData1 = new DynamicDatasourceData(); - datasourceData1.setSourceName("testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"); - dynamicDatasourceDataMapper.insert(datasourceData1); - } -} \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/dao/DynamicDatasourceDataMapper.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/dao/DynamicDatasourceDataMapper.java" deleted file mode 100644 index 80311733..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/dao/DynamicDatasourceDataMapper.java" +++ /dev/null @@ -1,9 +0,0 @@ -package com.dynamic.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.dynamic.entity.DynamicDatasourceData; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface DynamicDatasourceDataMapper extends BaseMapper { -} \ No newline at end of file diff --git "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/entity/DynamicDatasourceData.java" "b/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/entity/DynamicDatasourceData.java" deleted file mode 100644 index 2fa0a61e..00000000 --- "a/springboot101/\346\225\260\346\215\256\345\272\223/springboot-dynamic-datasource/src/main/java/com/dynamic/entity/DynamicDatasourceData.java" +++ /dev/null @@ -1,12 +0,0 @@ -package com.dynamic.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -@TableName("t_dynamic_datasource_data") -@Data -public class DynamicDatasourceData { - - private Long id; - private String sourceName; -} diff --git "a/springboot101/\346\226\207\344\273\266\346\223\215\344\275\234/springboot-file-storage/README.md" "b/springboot101/\346\226\207\344\273\266\346\223\215\344\275\234/springboot-file-storage/README.md" index 41be58b4..bc99be62 100644 --- "a/springboot101/\346\226\207\344\273\266\346\223\215\344\275\234/springboot-file-storage/README.md" +++ "b/springboot101/\346\226\207\344\273\266\346\223\215\344\275\234/springboot-file-storage/README.md" @@ -1,3 +1,5 @@ -### 本案例对应的文章教程 +# 工程简介 + +通过整合 spring-file-storage 包实现本地、二十多个云存储平台文件上传 + -[Springboot 一行代码实现文件上传 20个平台!少写代码到极致](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247502313&idx=1&sn=7ce4a41b0ae9533082e54ace1863d8bc&chksm=9b865914acf1d002127726552e86b3a03816fe915ec56abf779f4801b8d0ec07ee3c367a9dfe&token=755618913&lang=zh_CN#rd) \ No newline at end of file diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/pom.xml" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/pom.xml" index be3f5e51..521f5e79 100644 --- "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/pom.xml" +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/pom.xml" @@ -12,13 +12,7 @@ springboot-thymeleaf - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - + + diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/ValidApplication.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/BaseApplication.java" similarity index 70% rename from "springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/ValidApplication.java" rename to "springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/BaseApplication.java" index fd75b80b..a3fc7929 100644 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/ValidApplication.java" +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/BaseApplication.java" @@ -4,9 +4,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class ValidApplication { +public class BaseApplication { public static void main(String[] args) { - SpringApplication.run(ValidApplication.class, args); + SpringApplication.run(BaseApplication.class, args); } + } diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/ThymeleafApplication.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/ThymeleafApplication.java" deleted file mode 100644 index acd714a8..00000000 --- "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/ThymeleafApplication.java" +++ /dev/null @@ -1,13 +0,0 @@ -package com.springboot101; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ThymeleafApplication { - - public static void main(String[] args) { - SpringApplication.run(ThymeleafApplication.class, args); - } - -} diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/controller/TestController.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/controller/TestController.java" index e44f95e4..43f9f057 100644 --- "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/controller/TestController.java" +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/controller/TestController.java" @@ -1,36 +1,15 @@ package com.springboot101.controller; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.bind.annotation.RestController; -import java.util.Arrays; -import java.util.List; - -@Controller +@RestController public class TestController { - @GetMapping("/example") - public ModelAndView example(ModelAndView modelAndView) { - List fruits = Arrays.asList("Apple", "Banana", "Orange"); - modelAndView.setViewName("fruits"); - modelAndView.addObject("fruits", fruits); - return modelAndView; - } - - @GetMapping("/example1") - public String example1(Model model) { - List fruits = Arrays.asList("Apple", "Banana", "Orange"); - model.addAttribute("fruits", fruits); - return "fruits.html"; - } + @GetMapping("/test") + public String test() { - @GetMapping("/example2") - public String example2(Model model) { - List fruits = Arrays.asList("Apple", "Banana", "Orange"); - model.addAttribute("fruits", fruits); - return "fruits"; + return "test"; } -} \ No newline at end of file +} diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/po/User.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/po/User.java" new file mode 100644 index 00000000..c7ef1048 --- /dev/null +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/po/User.java" @@ -0,0 +1,33 @@ +package com.springboot101.po; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.Date; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "t_user") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + + private Integer age; + + private String email; + + @Column(name = "create_time") + private Date createTime; + + @Column(name = "update_time") + private Date updateTime; +} + diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/repository/UserRepository.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/repository/UserRepository.java" new file mode 100644 index 00000000..00ff5559 --- /dev/null +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/repository/UserRepository.java" @@ -0,0 +1,7 @@ +package com.springboot101.repository; + +import com.springboot101.po.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/service/UserService.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/service/UserService.java" new file mode 100644 index 00000000..2ed82c81 --- /dev/null +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/java/com/springboot101/service/UserService.java" @@ -0,0 +1,20 @@ +package com.springboot101.service; + +import com.springboot101.po.User; +import com.springboot101.repository.UserRepository; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +@Component +public class UserService { + + @Resource + private UserRepository userRepository; + + + public void insertUser(User user){ + + userRepository.save(user); + } +} diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/application.yml" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/application.yml" index 6d3c2346..6de67352 100644 --- "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/application.yml" +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/application.yml" @@ -3,9 +3,17 @@ server: spring: - thymeleaf: - cache: false - prefix: classpath:/templates/ - encoding: UTF-8 #编码 - suffix: .html #模板后缀 - mode: HTML #模板 + # 数据库连接信息 + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/db_1?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8 + username: root + password: 123456 + + jpa: + hibernate: + ddl-auto: update + properties: + hibernate: + dialect: org.hibernate.dialect.MySQL5InnoDBDialect + show-sql: true diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/static/index.html" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/static/index.html" new file mode 100644 index 00000000..e2d94a21 --- /dev/null +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/static/index.html" @@ -0,0 +1,6 @@ + + +

hello word!!!

+

this is a html page

+ + \ No newline at end of file diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/templates/fruits.html" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/templates/fruits.html" deleted file mode 100644 index ab08a4da..00000000 --- "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/main/resources/templates/fruits.html" +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Example Page - - - -

Welcome to Thymeleaf Example Page

- -
-
    -
  • -
-
-
-

No fruits available.

-
- - - - \ No newline at end of file diff --git "a/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/test/java/com/springboot101/BaseShare.java" "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/test/java/com/springboot101/BaseShare.java" new file mode 100644 index 00000000..78266ff4 --- /dev/null +++ "b/springboot101/\346\250\241\347\211\210\345\274\225\346\223\216/springboot-thymeleaf/src/test/java/com/springboot101/BaseShare.java" @@ -0,0 +1,28 @@ +package com.springboot101; + +import java.util.Date; + +import com.springboot101.po.User; +import com.springboot101.service.UserService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; + +@SpringBootTest +class BaseShare { + + @Resource + private UserService userService; + + @Test + public void userServiceTest() { + User user = new User(); + user.setName("公众号:程序员小富"); + user.setAge(0); + user.setEmail("vx:xinzhifu521"); + user.setCreateTime(new Date()); + user.setUpdateTime(new Date()); + userService.insertUser(user); + } +} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/README.md" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/README.md" deleted file mode 100644 index cb80a2fb..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/README.md" +++ /dev/null @@ -1 +0,0 @@ -springboot注解实现动态数据源切换 \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/pom.xml" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/pom.xml" deleted file mode 100644 index fef7869d..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/pom.xml" +++ /dev/null @@ -1,75 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.7.6 - - com.dynamic - springboot-config-order - 0.0.1-SNAPSHOT - - 8 - 8 - 3.5.3.1 - 8.0.32 - 1.2.6 - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-web - - - - com.mysql - mysql-connector-j - ${mysql.connector.version} - - - - org.projectlombok - lombok - true - - - - com.baomidou - mybatis-plus-boot-starter - ${mybatis.plus.version} - - - - com.alibaba - druid-spring-boot-starter - ${druid.version} - - - org.apache.commons - commons-lang3 - 3.7 - - - org.aspectj - aspectjweaver - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/DynamicDatasourceApplication.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/DynamicDatasourceApplication.java" deleted file mode 100644 index 75592071..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/DynamicDatasourceApplication.java" +++ /dev/null @@ -1,13 +0,0 @@ -package com.dynamic; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; - -@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) -public class DynamicDatasourceApplication { - - public static void main(String[] args) { - SpringApplication.run(DynamicDatasourceApplication.class, args); - } -} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/aspect/DS.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/aspect/DS.java" deleted file mode 100644 index 9e1367e7..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/aspect/DS.java" +++ /dev/null @@ -1,18 +0,0 @@ -package com.dynamic.aspect; - -import java.lang.annotation.*; - -/** - * 定于数据源切换注解 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@Target({ElementType.METHOD, ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -public @interface DS { - // 默认数据源master - String value() default "master"; -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/aspect/DSAspect.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/aspect/DSAspect.java" deleted file mode 100644 index abbb28eb..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/aspect/DSAspect.java" +++ /dev/null @@ -1,44 +0,0 @@ -package com.dynamic.aspect; - -import com.dynamic.config.DataSourceContextHolder; -import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.aspectj.lang.reflect.MethodSignature; -import org.springframework.stereotype.Component; - -import java.lang.reflect.Method; -import java.util.Objects; - -/** - * 实现@DS注解的AOP切面 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@Aspect -@Component -@Slf4j -public class DSAspect { - - @Pointcut("@annotation(com.dynamic.aspect.DS)") - public void dynamicDataSource() { - } - - @Around("dynamicDataSource()") - public Object datasourceAround(ProceedingJoinPoint point) throws Throwable { - MethodSignature signature = (MethodSignature) point.getSignature(); - Method method = signature.getMethod(); - DS ds = method.getAnnotation(DS.class); - if (Objects.nonNull(ds)) { - DataSourceContextHolder.setDataSource(ds.value()); - } - try { - return point.proceed(); - } finally { - DataSourceContextHolder.removeDataSource(); - } - } -} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DataSourceContextHolder.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DataSourceContextHolder.java" deleted file mode 100644 index e00d3981..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DataSourceContextHolder.java" +++ /dev/null @@ -1,37 +0,0 @@ -package com.dynamic.config; - -/** - * ThreadLocal存放数据源变量 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -public class DataSourceContextHolder { - - private static final ThreadLocal DATASOURCE_HOLDER = new ThreadLocal<>(); - - /** - * 获取当前线程的数据源 - * - * @return 数据源名称 - */ - public static String getDataSource() { - return DATASOURCE_HOLDER.get(); - } - - /** - * 设置数据源 - * - * @param dataSourceName 数据源名称 - */ - public static void setDataSource(String dataSourceName) { - DATASOURCE_HOLDER.set(dataSourceName); - } - - /** - * 删除当前数据源 - */ - public static void removeDataSource() { - DATASOURCE_HOLDER.remove(); - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DateSourceConfig.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DateSourceConfig.java" deleted file mode 100644 index 11c9c1fd..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DateSourceConfig.java" +++ /dev/null @@ -1,44 +0,0 @@ -package com.dynamic.config; - -import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; - -import javax.sql.DataSource; -import java.util.HashMap; -import java.util.Map; - -/** - * 注册多个数据源 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@Configuration -public class DateSourceConfig { - - @Bean - @ConfigurationProperties("spring.datasource.druid.master") - public DataSource dynamicDatasourceMaster() { - return DruidDataSourceBuilder.create().build(); - } - - @Bean - @ConfigurationProperties("spring.datasource.druid.slave") - public DataSource dynamicDatasourceSlave() { - return DruidDataSourceBuilder.create().build(); - } - - @Bean(name = "dynamicDataSource") - @Primary - public DynamicDataSource createDynamicDataSource() { - Map dataSourceMap = new HashMap<>(); - // 设置默认的数据源为Master - DataSource defaultDataSource = dynamicDatasourceMaster(); - dataSourceMap.put("master", defaultDataSource); - dataSourceMap.put("slave", dynamicDatasourceSlave()); - return new DynamicDataSource(defaultDataSource, dataSourceMap); - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DynamicDataSource.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DynamicDataSource.java" deleted file mode 100644 index 7f22cf36..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/config/DynamicDataSource.java" +++ /dev/null @@ -1,30 +0,0 @@ -package com.dynamic.config; - -import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; - -import javax.sql.DataSource; -import java.util.Map; - -/** - * 继承 AbstractRoutingDataSource - * 重置当前的数据库路由,实现切换成想要执行的目标数据库 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -public class DynamicDataSource extends AbstractRoutingDataSource { - - public DynamicDataSource(DataSource defaultDataSource, Map targetDataSources) { - super.setDefaultTargetDataSource(defaultDataSource); - super.setTargetDataSources(targetDataSources); - } - - /** - * 这一步是关键 - * @return - */ - @Override - protected Object determineCurrentLookupKey() { - return DataSourceContextHolder.getDataSource(); - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/controller/DynamicSwitchController.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/controller/DynamicSwitchController.java" deleted file mode 100644 index db3c1315..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/controller/DynamicSwitchController.java" +++ /dev/null @@ -1,64 +0,0 @@ -package com.dynamic.controller; - -import com.dynamic.aspect.DS; -import com.dynamic.config.DataSourceContextHolder; -import com.dynamic.dao.DynamicDatasourceDataMapper; -import com.dynamic.entity.DynamicDatasourceData; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Resource; - -/** - * 动态数据源切换 - * - * @author 公众号:程序员小富 - * @date 2023/11/27 11:02 - */ -@RestController -public class DynamicSwitchController { - - @Resource - private DynamicDatasourceDataMapper dynamicDatasourceDataMapper; - - @GetMapping("/switchDataSource/{datasourceName}") - public String switchDataSource(@PathVariable("datasourceName") String datasourceName) { - DataSourceContextHolder.setDataSource(datasourceName); - DynamicDatasourceData dynamicDatasourceData = dynamicDatasourceDataMapper.selectOne(null); - DataSourceContextHolder.removeDataSource(); - return dynamicDatasourceData.getSourceName(); - } - - @DS(value = "master") - @GetMapping("/dbMaster") - public String dbMaster() { - DynamicDatasourceData dynamicDatasourceData = dynamicDatasourceDataMapper.selectOne(null); - return dynamicDatasourceData.getSourceName(); - } - - @DS(value = "slave") - @GetMapping("/dbSlave") - public String dbSlave() { - DynamicDatasourceData dynamicDatasourceData = dynamicDatasourceDataMapper.selectOne(null); - return dynamicDatasourceData.getSourceName(); - } - - - /** - * 验证一下事物控制 - */ -// @Transactional(rollbackFor = Exception.class) - @DS(value = "slave") - @GetMapping("/dbTestTransactional") - public void dbTestTransactional() { - - DynamicDatasourceData datasourceData = new DynamicDatasourceData(); - datasourceData.setSourceName("test"); - dynamicDatasourceDataMapper.insert(datasourceData); - - DynamicDatasourceData datasourceData1 = new DynamicDatasourceData(); - datasourceData1.setSourceName("testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttest"); - dynamicDatasourceDataMapper.insert(datasourceData1); - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/dao/DynamicDatasourceDataMapper.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/dao/DynamicDatasourceDataMapper.java" deleted file mode 100644 index 80311733..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/dao/DynamicDatasourceDataMapper.java" +++ /dev/null @@ -1,9 +0,0 @@ -package com.dynamic.dao; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.dynamic.entity.DynamicDatasourceData; -import org.apache.ibatis.annotations.Mapper; - -@Mapper -public interface DynamicDatasourceDataMapper extends BaseMapper { -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/entity/DynamicDatasourceData.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/entity/DynamicDatasourceData.java" deleted file mode 100644 index 2fa0a61e..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-config-order/src/main/java/com/dynamic/entity/DynamicDatasourceData.java" +++ /dev/null @@ -1,12 +0,0 @@ -package com.dynamic.entity; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -@TableName("t_dynamic_datasource_data") -@Data -public class DynamicDatasourceData { - - private Long id; - private String sourceName; -} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/README.md" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/README.md" index b66375ca..17566f74 100644 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/README.md" +++ "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/README.md" @@ -1,4 +1,3 @@ -### 本案例对应的文章教程 - -[6 种方式读取 Springboot 的配置,老鸟都这么玩(原理+实战)](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247504127&idx=1&sn=7416045cdfb893b7f284a160ff168da2&chksm=9b864002acf1c914a055c72a0b943867fc98639fb15917839aaf8d2135a64e65bd030ce7e896&token=755618913&lang=zh_CN#rd) +6 种方式获取配置文件的属性变量 +[详细文章地址](https://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247504127&idx=1&sn=7416045cdfb893b7f284a160ff168da2&chksm=9b864002acf1c914a055c72a0b943867fc98639fb15917839aaf8d2135a64e65bd030ce7e896&token=757548970&lang=zh_CN#rd) diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/src/test/java/com/springboot101/value\346\263\250\350\247\243/EnvVariables3Test.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/src/test/java/com/springboot101/value\346\263\250\350\247\243/EnvVariables3Test.java" new file mode 100644 index 00000000..e250bdfc --- /dev/null +++ "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-env-variables/src/test/java/com/springboot101/value\346\263\250\350\247\243/EnvVariables3Test.java" @@ -0,0 +1,25 @@ +package com.springboot101.value注解; + +import com.springboot101.service.TestService; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; + +@Slf4j +@SpringBootTest +public class EnvVariables3Test { + + /** + * @value注解 引用方式不对 + */ + @Test + public void var7_1Test() { + + TestService testService = new TestService(); + log.info("引用方式不对 注入: {}", testService.getVar7()); + } +} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-jasypt/README.md" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-jasypt/README.md" index 46f2dfa4..b4b31fdc 100644 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-jasypt/README.md" +++ "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-jasypt/README.md" @@ -1,3 +1,29 @@ -### 本案例对应的文章教程 -[Springboot 配置文件、隐私数据脱敏的最佳实践(原理+源码)](http://mp.weixin.qq.com/s?__biz=MzAxNTM4NzAyNg==&mid=2247496247&idx=1&sn=643af4cbe578a1c52bc302af948803ef&chksm=9b8662caacf1ebdc628c48890a6f7274acfaae9fa4a3ec519d41c4dec92182802e46c621658b&token=755618913&lang=zh_CN#rd) + +### 启动命令 并注入 秘钥配置 + +>jasypt.encryptor.password=mypassword + +```java + +java -jar -Djasypt.encryptor.password=mypassword XXX-jasypt.jar + +脚本文件 + +java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar +``` + +### 生成待加密的文本内容 + +> maven包路径 D:\maven_lib\org\jasypt\jasypt\1.9.3\jasypt-1.9.3.jar + +> input 待加密文本 + +> password 秘钥文本 + +```java +java -cp D:\maven_lib\org\jasypt\jasypt\1.9.3\jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="mypassword" password=35579B7F9C8CB15E +``` + +参考文件 https://blog.yamell.com/java/415.html + diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/README.md" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/README.md" deleted file mode 100644 index af76a644..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/README.md" +++ /dev/null @@ -1,2 +0,0 @@ - -实现三种异步流式接口 \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/pom.xml" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/pom.xml" deleted file mode 100644 index ed734a58..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/pom.xml" +++ /dev/null @@ -1,24 +0,0 @@ - - - 4.0.0 - - com.notebook - Springboot-Notebook - 0.0.1-SNAPSHOT - - springboot-streaming - 0.0.1-SNAPSHOT - springboot-streaming - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/StreamingApplication.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/StreamingApplication.java" deleted file mode 100644 index 6f7a0c4f..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/StreamingApplication.java" +++ /dev/null @@ -1,13 +0,0 @@ -package com.springboot101; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class StreamingApplication { - - public static void main(String[] args) { - SpringApplication.run(StreamingApplication.class, args); - } - -} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/ResponseBodyEmitterController.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/ResponseBodyEmitterController.java" deleted file mode 100644 index 201906a5..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/ResponseBodyEmitterController.java" +++ /dev/null @@ -1,42 +0,0 @@ -package com.springboot101.controller; - - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; - -import java.util.Date; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@Controller -public class ResponseBodyEmitterController { - private final ExecutorService nonBlockingService = Executors.newCachedThreadPool(); - - @GetMapping("bodyEmitter") - public ResponseBodyEmitter handle() { - - // 创建一个ResponseBodyEmitter,-1代表不超时 - ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L); - - // 异步执行耗时操作 - CompletableFuture.runAsync(() -> { - try { - // 模拟耗时操作 - for (int i = 0; i < 10000; i++) { - System.out.println("bodyEmitter " + i); - // 发送数据 - emitter.send("bodyEmitter " + i + " @ " + new Date() + "\n"); - Thread.sleep(2000); - } - // 完成 - emitter.complete(); - } catch (Exception e) { - // 发生异常时结束接口 - emitter.completeWithError(e); - } - }); - return emitter; - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/SseEmitterController.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/SseEmitterController.java" deleted file mode 100644 index 79d27fbc..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/SseEmitterController.java" +++ /dev/null @@ -1,68 +0,0 @@ -package com.springboot101.controller; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; - -import java.io.IOException; -import java.time.LocalTime; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; - -@Slf4j -@RestController -public class SseEmitterController { - - private static final Map EMITTER_MAP = new ConcurrentHashMap<>(); - - @GetMapping("/subSseEmitter/{userId}") - public SseEmitter sseEmitter(@PathVariable String userId) { - log.info("sseEmitter: {}", userId); - SseEmitter emitterTmp = new SseEmitter(-1L); - EMITTER_MAP.put(userId, emitterTmp); - CompletableFuture.runAsync(() -> { - try { - SseEmitter.SseEventBuilder event = SseEmitter.event() - .data("sseEmitter" + userId + " @ " + LocalTime.now()) - .id(String.valueOf(userId)) - .name("sseEmitter"); - emitterTmp.send(event); - } catch (Exception ex) { - emitterTmp.completeWithError(ex); - } - }); - return emitterTmp; - } - - @GetMapping("/sendSseMsg/{userId}") - public void sseEmitter(@PathVariable String userId, String msg) throws IOException { - SseEmitter sseEmitter = EMITTER_MAP.get(userId); - if (sseEmitter == null) { - return; - } - sseEmitter.send(msg); - } -// @GetMapping("/sseEmitter/{userId}") -// public SseEmitter sseEmitter(@PathVariable String userId) { -// -// CompletableFuture.runAsync(() -> { -// try { -// for (int i = 0; i < 10000; i++) { -// SseEmitter.SseEventBuilder event = SseEmitter.event() -// .data("sseEmitter" + i + " @ " + LocalTime.now()) -// .id(String.valueOf(i)) -// .name("sseEmitter"); -// emitter.send(event); -// Thread.sleep(1000); -// } -// emitter.complete(); -// } catch (Exception ex) { -// emitter.completeWithError(ex); -// } -// }); -// return emitter; -// } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/StreamingResponseBodyController.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/StreamingResponseBodyController.java" deleted file mode 100644 index ad8f29db..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/StreamingResponseBodyController.java" +++ /dev/null @@ -1,33 +0,0 @@ -package com.springboot101.controller; - -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; - -import java.util.concurrent.TimeUnit; - -@Controller -public class StreamingResponseBodyController { - - @GetMapping("/streamingResponse") - public ResponseEntity handleRbe() { - - StreamingResponseBody stream = out -> { - String message = "streamingResponse"; - for (int i = 0; i < 1000; i++) { - try { - out.write(((message + i) + "\r\n").getBytes()); - out.write("\r\n".getBytes()); - //调用一次flush就会像前端写入一次数据 - out.flush(); - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }; - return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(stream); - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/TestController.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/TestController.java" deleted file mode 100644 index f1763704..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/java/com/springboot101/controller/TestController.java" +++ /dev/null @@ -1,15 +0,0 @@ -package com.springboot101.controller; - - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -public class TestController { - - @GetMapping("/sse") - public String sse(Model model) { - return "sse"; - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/resources/templates/sse.html" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/resources/templates/sse.html" deleted file mode 100644 index 51652d60..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-streaming/src/main/resources/templates/sse.html" +++ /dev/null @@ -1,46 +0,0 @@ - - - - - SSE - - -
-

SSE 接收服务端事件消息数据

-
等待连接...
-
- - - \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/README.md" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/README.md" deleted file mode 100644 index 117755ed..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/README.md" +++ /dev/null @@ -1 +0,0 @@ -springbott参数校验 \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/pom.xml" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/pom.xml" deleted file mode 100644 index 9d6902c2..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/pom.xml" +++ /dev/null @@ -1,29 +0,0 @@ - - - 4.0.0 - - com.springboot101 - springboot101 - 0.0.1-SNAPSHOT - - - springboot-valid-params - - - - org.springframework.boot - spring-boot-starter-validation - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/controller/TestController.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/controller/TestController.java" deleted file mode 100644 index 9aebd420..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/controller/TestController.java" +++ /dev/null @@ -1,22 +0,0 @@ -package com.springboot101.controller; - -import com.springboot101.params.UserVO; -import com.springboot101.params.ValidGroup; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class TestController { - - @PostMapping("/addUserInfo") - public String addUserInfo(@Validated @RequestBody UserVO user) { - return "插入成功!"; - } - - @PostMapping("/editUserInfo") - public String editUserInfo(@Validated({ValidGroup.Update.class}) @RequestBody UserVO user) { - return "编辑成功!"; - } -} diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/domain/ResponseResult.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/domain/ResponseResult.java" deleted file mode 100644 index ef6a5ece..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/domain/ResponseResult.java" +++ /dev/null @@ -1,50 +0,0 @@ -package com.springboot101.domain; - -import com.springboot101.enums.ResultCode; -import lombok.Data; - - -@Data -public class ResponseResult { - - private int code; - private String message; - private T data; - private long timestamp ; - - - public ResponseResult(){ - this.timestamp = System.currentTimeMillis(); - } - - public ResponseResult(int code) { - this.code = code; - } - - public ResponseResult(int code, String message) { - this.code = code; - this.message = message; - } - - public ResponseResult(int code, String message, T data) { - this.code = code; - this.message = message; - this.data = data; - } - - public static ResponseResult success(T data) { - ResponseResult resultData = new ResponseResult<>(); - resultData.setCode(ResultCode.OK.getCode()); - resultData.setMessage(ResultCode.OK.getMessage()); - resultData.setData(data); - return resultData; - } - - public static ResponseResult fail(int code, String message) { - ResponseResult resultData = new ResponseResult<>(); - resultData.setCode(code); - resultData.setMessage(message); - return resultData; - } - -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/enums/ResultCode.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/enums/ResultCode.java" deleted file mode 100644 index 92ef17c9..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/enums/ResultCode.java" +++ /dev/null @@ -1,49 +0,0 @@ -package com.springboot101.enums; - - -public enum ResultCode { - - /** - * 操作成功 - */ - OK(100, "操作成功"), - - /** - * 操作失败 - */ - OPS_ERROR(-1, "操作失败"), - - /** - * 参数校验不通过 - */ - PARAMETER_ERROR(204, "参数校验不通过"), - - /** - * 服务异常 - */ - SYSTEM_ERROR(500, "系统异常,请稍后重试"); - - /** - * 自定义状态码 - **/ - private final int code; - - /** - * 自定义描述 - **/ - private final String message; - - ResultCode(int code, String message) { - this.code = code; - this.message = message; - } - - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/exception/GlobalExceptionHandler.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/exception/GlobalExceptionHandler.java" deleted file mode 100644 index aaf23e2d..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/exception/GlobalExceptionHandler.java" +++ /dev/null @@ -1,90 +0,0 @@ -package com.springboot101.exception; - -import com.springboot101.enums.ResultCode; -import com.springboot101.domain.ResponseResult; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpStatus; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.validation.ObjectError; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestControllerAdvice; - -import java.util.List; - -@Slf4j -@RestControllerAdvice -public class GlobalExceptionHandler { - - /** - * 忽略参数异常处理器 - * - * @param e 忽略参数异常 - * @return ResponseResult - */ - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler(MissingServletRequestParameterException.class) - public ResponseResult parameterMissingExceptionHandler(MissingServletRequestParameterException e) { - log.error("", e); - return new ResponseResult(ResultCode.PARAMETER_ERROR.getCode(), "请求参数 " + e.getParameterName() + " 不能为空"); - } - - /** - * 缺少请求体异常处理器 - * - * @param e 缺少请求体异常 - * @return ResponseResult - */ - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseResult parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) { - log.error("", e); - return new ResponseResult(ResultCode.PARAMETER_ERROR.getCode(), "参数体不能为空"); - } - - /** - * 参数效验异常处理器 - * - * @param e 参数验证异常 - * @return ResponseInfo - */ - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseResult parameterExceptionHandler(MethodArgumentNotValidException e) { - log.error("", e); - // 获取异常信息 - BindingResult exceptions = e.getBindingResult(); - // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息 - if (exceptions.hasErrors()) { - List errors = exceptions.getAllErrors(); - if (!errors.isEmpty()) { - // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可 - FieldError fieldError = (FieldError) errors.get(0); - return new ResponseResult(ResultCode.PARAMETER_ERROR.getCode(), fieldError.getDefaultMessage()); - } - } - return new ResponseResult(ResultCode.PARAMETER_ERROR.getCode()); - } - - /** - * 自定义参数错误异常处理器 - * - * @param e 自定义参数 - * @return ResponseInfo - */ - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler({ParamsErrorException.class}) - public ResponseResult paramExceptionHandler(ParamsErrorException e) { - log.error("", e); - // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息 - if (!StringUtils.isEmpty(e.getMessage())) { - return new ResponseResult(ResultCode.PARAMETER_ERROR.getCode(), e.getMessage()); - } - return new ResponseResult(ResultCode.PARAMETER_ERROR.getCode()); - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/exception/ParamsErrorException.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/exception/ParamsErrorException.java" deleted file mode 100644 index 6bf5a0db..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/exception/ParamsErrorException.java" +++ /dev/null @@ -1,16 +0,0 @@ -package com.springboot101.exception; - - -public class ParamsErrorException extends RuntimeException { - - private final int code; - - public ParamsErrorException(int code, String message) { - super(message); - this.code = code; - } - - public int getCode() { - return code; - } -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/params/UserVO.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/params/UserVO.java" deleted file mode 100644 index 710f559f..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/params/UserVO.java" +++ /dev/null @@ -1,41 +0,0 @@ -package com.springboot101.params; - - -import lombok.Data; -import org.springframework.web.bind.annotation.GetMapping; - -import javax.validation.constraints.*; -import java.util.Date; - -/** - * gon - */ -@Data -public class UserVO { - - @NotBlank(message = "姓名不为空", groups = ValidGroup.Insert.class) - private String username; - - @NotBlank(message = "密码不为空", groups = ValidGroup.Update.class) - private String password; - - @Min(value = 18, message = "年龄不小于18", groups = {ValidGroup.Update.class, ValidGroup.Insert.class}) - @Max(value = 100, message = "年龄不大于100", groups = {ValidGroup.Update.class, ValidGroup.Insert.class}) - @NotNull(message = "age不为空", groups = {ValidGroup.Update.class, ValidGroup.Insert.class}) - private int age; - - @Email(message = "邮件格式不对") - @NotBlank(message = "邮件不为空", groups = ValidGroup.Insert.class) - private String email; - - // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") -// @Future(message = "必须是将来时间") - @NotNull(message = "createTime不为空", groups = {ValidGroup.Update.class, ValidGroup.Insert.class}) - private Date createTime; - - @GetMapping("/hello") - public String getStr() { - return "hello,javadaily"; - } - -} \ No newline at end of file diff --git "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/params/ValidGroup.java" "b/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/params/ValidGroup.java" deleted file mode 100644 index 469c0b52..00000000 --- "a/springboot101/\351\200\232\347\224\250\345\212\237\350\203\275/springboot-valid-params/src/main/java/com/springboot101/params/ValidGroup.java" +++ /dev/null @@ -1,32 +0,0 @@ -package com.springboot101.params; - -import javax.validation.GroupSequence; - -/** - * 分组校验 - 定义分组 - */ - -/** - * 分组校验 - 定义分组 - * @author 公众号:程序员小富 - * @date 2023/10/24 11:02 - */ -public class ValidGroup { - - // 新增使用 - public interface Insert { - } - - // 更新使用 - public interface Update { - } - - // 删除使用 - public interface Delete { - } - - // 属性必须有这两个分组的才验证(配合spring的@Validated功能分组使用) - @GroupSequence({Insert.class, Update.class, Delete.class}) - public interface All { - } -} \ No newline at end of file