From 58548aed10f8c456716be2729e80997200dbe4e4 Mon Sep 17 00:00:00 2001 From: zihong Date: Wed, 11 Dec 2019 16:47:48 +0800 Subject: [PATCH 01/14] =?UTF-8?q?=E4=BD=BF=E7=94=A8alibaba=20sentinel?= =?UTF-8?q?=E7=9B=91=E6=8E=A7=E5=BA=94=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Alibaba-Sentinel/.gitignore | 32 +++++++++++++++++ SpringBoot-Alibaba-Sentinel/Dockerfile | 6 ++++ SpringBoot-Alibaba-Sentinel/README.md | 30 ++++++++++++++++ SpringBoot-Alibaba-Sentinel/build.gradle | 35 +++++++++++++++++++ .../sentinel/SentinelApplication.java | 21 +++++++++++ .../learning/sentinel/api/TestApi.java | 32 +++++++++++++++++ .../src/main/resources/application.properties | 6 ++++ settings.gradle | 9 ++--- 8 files changed, 167 insertions(+), 4 deletions(-) create mode 100644 SpringBoot-Alibaba-Sentinel/.gitignore create mode 100644 SpringBoot-Alibaba-Sentinel/Dockerfile create mode 100644 SpringBoot-Alibaba-Sentinel/README.md create mode 100644 SpringBoot-Alibaba-Sentinel/build.gradle create mode 100644 SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/SentinelApplication.java create mode 100644 SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/api/TestApi.java create mode 100644 SpringBoot-Alibaba-Sentinel/src/main/resources/application.properties diff --git a/SpringBoot-Alibaba-Sentinel/.gitignore b/SpringBoot-Alibaba-Sentinel/.gitignore new file mode 100644 index 0000000..6c01878 --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/.gitignore @@ -0,0 +1,32 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/SpringBoot-Alibaba-Sentinel/Dockerfile b/SpringBoot-Alibaba-Sentinel/Dockerfile new file mode 100644 index 0000000..4a0c5e7 --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/Dockerfile @@ -0,0 +1,6 @@ +FROM openjdk:8 +LABEL maintainer="15017263266@163.com" +WORKDIR / +ARG JAR_FILE +ADD ${JAR_FILE} app.jar +EXPOSE 8080 diff --git a/SpringBoot-Alibaba-Sentinel/README.md b/SpringBoot-Alibaba-Sentinel/README.md new file mode 100644 index 0000000..cb760ea --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/README.md @@ -0,0 +1,30 @@ +## 使用阿里巴巴开源项目 -- Sentinel 进行项目的监控、降级、流控 +### 手动接入 Sentinel 以及控制台 +启动控制台: +下载sentinel 的dashboard包,该项目为springboot项目,可编译后启动。 +https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard + +导包,springboot 2.1.0以下用 +``` + compile 'org.springframework.cloud:spring-cloud-starter-alibaba-sentinel:0.2.2.RELEASE' +``` +配置如下: +```properties +server.port=8720 +spring.application.name=TestSentinel +spring.cloud.sentinel.eager=true +spring.cloud.sentinel.transport.port=8721 +spring.cloud.sentinel.transport.dashboard=127.0.0.1:8719 +spring.cloud.sentinel.transport.heartbeat-interval-ms=500 +``` +需要为应用提供两个可使用端口,server.port为应用端口, +spring.cloud.sentinel.transport.port 端口配置会在应用对应的机器上启动一个 Http Server, +该 Server 会与 Sentinel 控制台做交互。比如 Sentinel 控制台添加了1个限流规则, +会把规则数据 push 给这个 Http Server 接收,Http Server 再将规则注册到 Sentinel 中。 + +接着在需要监控的API上添加注解:@SentinelResource 后,启动项目,访问相应的api,即可在dashboard上看到记录,可根据自己应用情况进行 +限流、降级等处理。 + + +参考链接: +https://github.com/alibaba/Sentinel \ No newline at end of file diff --git a/SpringBoot-Alibaba-Sentinel/build.gradle b/SpringBoot-Alibaba-Sentinel/build.gradle new file mode 100644 index 0000000..f7571f2 --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/build.gradle @@ -0,0 +1,35 @@ +buildscript { + repositories { + maven { url "https://plugins.gradle.org/m2/" } + maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.4.RELEASE") + //引入gradle-docker + classpath('gradle.plugin.com.palantir.gradle.docker:gradle-docker:0.19.2') + } +} +//引入构建docker插件 +apply plugin: 'com.palantir.docker' +apply plugin: 'org.springframework.boot' +apply plugin: 'application' + +group = 'registry.acs.aliyun.com/35013893' +version = project.findProperty('projVersion') ?: '1.0.0' +mainClassName = 'com.dashuai.learning.sentinel.SentinelApplication' + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} +dependencies { + compile project(':SpringBoot-Utils') + compile 'org.springframework.cloud:spring-cloud-starter-alibaba-sentinel:0.2.2.RELEASE' +} +//具体配置生成镜像 +docker { + dockerfile file('Dockerfile') + name "${project.group}/springboot-sentinel-test:${project.version}" + files jar.archivePath + buildArgs(['JAR_FILE': "${jar.archiveName}"]) +} diff --git a/SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/SentinelApplication.java b/SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/SentinelApplication.java new file mode 100644 index 0000000..a3a9fe3 --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/SentinelApplication.java @@ -0,0 +1,21 @@ +package com.dashuai.learning.sentinel; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.alibaba.sentinel.annotation.SentinelRestTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; + +@SpringBootApplication +public class SentinelApplication { + + public static void main(String[] args) { + SpringApplication.run(SentinelApplication.class, args); + } + + @Bean + @SentinelRestTemplate + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/api/TestApi.java b/SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/api/TestApi.java new file mode 100644 index 0000000..d5bd90f --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/src/main/java/com/dashuai/learning/sentinel/api/TestApi.java @@ -0,0 +1,32 @@ +package com.dashuai.learning.sentinel.api; + +import com.alibaba.csp.sentinel.annotation.SentinelResource; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Date; + +@RestController +public class TestApi { + @RequestMapping("/test") + @SentinelResource("test") + public String health() { + return new Date().toString(); + } + + @GetMapping(value = "/mye") + @SentinelResource("mye") + public String mye() { + if (true) { + throw new RuntimeException("mye"); + } + return "mye Sentinel"; + } + + @GetMapping(value = "/myrate") + @SentinelResource("myrate") + public String myrate() { + return "myrate Sentinel"; + } +} \ No newline at end of file diff --git a/SpringBoot-Alibaba-Sentinel/src/main/resources/application.properties b/SpringBoot-Alibaba-Sentinel/src/main/resources/application.properties new file mode 100644 index 0000000..7312770 --- /dev/null +++ b/SpringBoot-Alibaba-Sentinel/src/main/resources/application.properties @@ -0,0 +1,6 @@ +server.port=8720 +spring.application.name=TestSentinel +spring.cloud.sentinel.eager=true +spring.cloud.sentinel.transport.port=8721 +spring.cloud.sentinel.transport.dashboard=sentinel2.zjk.taeapp.com +spring.cloud.sentinel.transport.heartbeat-interval-ms=500 \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index caa223b..4dab9b6 100644 --- a/settings.gradle +++ b/settings.gradle @@ -30,16 +30,17 @@ rootProject.name = 'springboot' //include(':SpringBoot-Oauth2-Code') //include(':SpringBoot-Thrift-Server') //include(':SpringBoot-Thrift-Client') -include(':SpringBoot-Grpc') -include(':SpringBoot-Grpc:SpringBoot-Grpc-Server') -include(':SpringBoot-Grpc:SpringBoot-Grpc-Lib') -include(':SpringBoot-Grpc:SpringBoot-Grpc-Client') +//include(':SpringBoot-Grpc') +//include(':SpringBoot-Grpc:SpringBoot-Grpc-Server') +//include(':SpringBoot-Grpc:SpringBoot-Grpc-Lib') +//include(':SpringBoot-Grpc:SpringBoot-Grpc-Client') //include(':SpringBoot-SpringSecurity') //include(':SpringBoot-Redis-Sentinel') //include(':SpringBoot-Rocketmq') //include(':SpringBoot-Nacos-Config') //include(':SpringBoot-Builder-Docker') //include(':SpringBoot-Test-Starter') +include(':SpringBoot-Alibaba-Sentinel') include(':SpringBoot-Utils') // spring-boot-starter-webflux模块与web冲突,如果web模块的类不能用,请注释下面的模块 //include(':SpringBoot-WebFlux') From 978646774e0869cab1937ebaf926589e5553c4be Mon Sep 17 00:00:00 2001 From: zihong Date: Wed, 11 Dec 2019 16:48:22 +0800 Subject: [PATCH 02/14] =?UTF-8?q?=E9=99=90=E6=B5=81=E6=B3=A8=E8=A7=A3?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=BB=98=E8=AE=A4=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ratelimiter/annotation/RateLimiterAnnotation.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java index 66fda80..b8e2df0 100644 --- a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java +++ b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java @@ -13,12 +13,12 @@ * * @return */ - String name(); + String name() default ""; /** * 每秒限流次数 * * @return */ - double count(); + double count() default 1000; } From 91e45e7958c85fd1bcb98d5bc0eb52fb62e129cd Mon Sep 17 00:00:00 2001 From: zihong Date: Thu, 12 Dec 2019 17:32:08 +0800 Subject: [PATCH 03/14] =?UTF-8?q?feat:=20springboot=20mybatis=20plus=20?= =?UTF-8?q?=E7=9A=84=E5=BA=94=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 + SpringBoot-Mybatis-Plus/.gitignore | 32 +++++ SpringBoot-Mybatis-Plus/README.md | 22 +++ SpringBoot-Mybatis-Plus/build.gradle | 9 ++ .../learning/mybatisplus/CodeGenerator.java | 130 ++++++++++++++++++ .../mybatisplus/MybatisPlusApplication.java | 15 ++ .../config/MyMetaObjectHandler.java | 32 +++++ .../mybatisplus/config/MybatisPlusConfig.java | 32 +++++ .../user/controller/UserController.java | 18 +++ .../mybatisplus/user/entity/User.java | 53 +++++++ .../mybatisplus/user/mapper/UserMapper.java | 17 +++ .../user/service/IUserService.java | 16 +++ .../user/service/impl/UserServiceImpl.java | 19 +++ .../src/main/resources/application.properties | 12 ++ .../src/main/resources/user.sql | 23 ++++ .../MybatisPlusApplicationTests.java | 107 ++++++++++++++ build.gradle | 2 +- settings.gradle | 3 +- 18 files changed, 546 insertions(+), 2 deletions(-) create mode 100644 SpringBoot-Mybatis-Plus/.gitignore create mode 100644 SpringBoot-Mybatis-Plus/README.md create mode 100644 SpringBoot-Mybatis-Plus/build.gradle create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/CodeGenerator.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/MybatisPlusApplication.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MyMetaObjectHandler.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MybatisPlusConfig.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/controller/UserController.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/entity/User.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/mapper/UserMapper.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/IUserService.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/impl/UserServiceImpl.java create mode 100644 SpringBoot-Mybatis-Plus/src/main/resources/application.properties create mode 100644 SpringBoot-Mybatis-Plus/src/main/resources/user.sql create mode 100644 SpringBoot-Mybatis-Plus/src/test/java/com/dashuai/learning/mybatisplus/MybatisPlusApplicationTests.java diff --git a/README.md b/README.md index 5f3c183..2128281 100644 --- a/README.md +++ b/README.md @@ -147,5 +147,11 @@ SpringBoot 使用Gradle做依赖管理时,配置打包docker镜像的DEMO #### SpringBoot-Thrift-Client(Thrift 实现远程服务调用 客戶端) SpringBoot基于Thrift实现RPC客户端 +#### SpringBoot-Mybatis-Plus +SpringBoot 集成Mybatis Plus,内置乐观锁,crud,自动填充示例 + +#### SpringBoot-Alibaba-Sentinel +SpringBoot 使用 Alibaba开源监控平台 sentinel 示例 + #### SpringBoot-Utils 各项目的依赖模块,存放一些工具类 diff --git a/SpringBoot-Mybatis-Plus/.gitignore b/SpringBoot-Mybatis-Plus/.gitignore new file mode 100644 index 0000000..6c01878 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/.gitignore @@ -0,0 +1,32 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/SpringBoot-Mybatis-Plus/README.md b/SpringBoot-Mybatis-Plus/README.md new file mode 100644 index 0000000..f806f53 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/README.md @@ -0,0 +1,22 @@ +### SpringBoot 集成 Mybatis Plus 示例 + +#### 简介 +MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 +#### 特性 + + 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑 + 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作 + 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求 + 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错 + 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题 + 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作 + 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere ) + 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用 + 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询 + 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库 + 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询 + 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作 + + +详情可参考Mybatis plus 官网,链接: +https://mp.baomidou.com/guide/quick-start.html \ No newline at end of file diff --git a/SpringBoot-Mybatis-Plus/build.gradle b/SpringBoot-Mybatis-Plus/build.gradle new file mode 100644 index 0000000..7dafd27 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/build.gradle @@ -0,0 +1,9 @@ +dependencies { + compile project(':SpringBoot-Utils') + compile 'com.baomidou:mybatis-plus-boot-starter:3.0.1' + //代码生成器 + compile 'com.baomidou:mybatis-plus-generator:3.0.1' + compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46' + compile 'org.apache.velocity:velocity-engine-core:2.1' + testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE' +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/CodeGenerator.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/CodeGenerator.java new file mode 100644 index 0000000..4fcaf4a --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/CodeGenerator.java @@ -0,0 +1,130 @@ +package com.dashuai.learning.mybatisplus; + +import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; +import com.baomidou.mybatisplus.core.toolkit.StringPool; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.generator.AutoGenerator; +import com.baomidou.mybatisplus.generator.InjectionConfig; +import com.baomidou.mybatisplus.generator.config.*; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class CodeGenerator { + /** + *

+ * 读取控制台内容 + *

+ */ + public static String scanner(String tip) { + Scanner scanner = new Scanner(System.in); + System.out.println("请输入" + tip + ":"); + if (scanner.hasNext()) { + String ipt = scanner.next(); + if (StringUtils.isNotEmpty(ipt)) { + return ipt; + } + } + throw new MybatisPlusException("请输入正确的" + tip + "!"); + } + + public static void main(String[] args) { + // 代码生成器 + AutoGenerator mpg = new AutoGenerator(); + + // 全局配置 + GlobalConfig gc = new GlobalConfig(); + String projectPath = System.getProperty("user.dir"); + gc.setOutputDir(projectPath + "/SpringBoot-Mybatis-Plus/src/main/java"); + gc.setAuthor("zoey"); + gc.setOpen(false); + // gc.setSwagger2(true); 实体属性 Swagger2 注解 + mpg.setGlobalConfig(gc); + + // 数据源配置 + DataSourceConfig dsc = new DataSourceConfig(); + dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8"); + // dsc.setSchemaName("public"); + dsc.setDriverName("com.mysql.jdbc.Driver"); + dsc.setUsername("root"); + dsc.setPassword("root"); + mpg.setDataSource(dsc); + + // 包配置 + PackageConfig pc = new PackageConfig(); + pc.setModuleName(scanner("模块名")); + pc.setParent("com.dashuai.learning.mybatisplus"); + mpg.setPackageInfo(pc); + + // 自定义配置 + InjectionConfig cfg = new InjectionConfig() { + @Override + public void initMap() { + // to do nothing + } + }; + + // 如果模板引擎是 freemarker +// String templatePath = "/templates/mapper.xml.ftl"; + // 如果模板引擎是 velocity + String templatePath = "/templates/mapper.xml.vm"; + + // 自定义输出配置 + List focList = new ArrayList<>(); + // 自定义配置会被优先输出 + focList.add(new FileOutConfig(templatePath) { + @Override + public String outputFile(TableInfo tableInfo) { + // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! + return projectPath + "/SpringBoot-Mybatis-Plus/src/main/resources/mapper/" + pc.getModuleName() + + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; + } + }); + /* + cfg.setFileCreate(new IFileCreate() { + @Override + public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { + // 判断自定义文件夹是否需要创建 + checkDir("调用默认方法创建的目录"); + return false; + } + }); + */ + cfg.setFileOutConfigList(focList); + mpg.setCfg(cfg); + + // 配置模板 + TemplateConfig templateConfig = new TemplateConfig(); + + // 配置自定义输出模板 + //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 + // templateConfig.setEntity("templates/entity2.java"); + // templateConfig.setService(); + // templateConfig.setController(); + + templateConfig.setXml(null); + mpg.setTemplate(templateConfig); + + // 策略配置 + StrategyConfig strategy = new StrategyConfig(); + strategy.setNaming(NamingStrategy.underline_to_camel); + strategy.setColumnNaming(NamingStrategy.underline_to_camel); +// strategy.setSuperEntityClass("com.dashuai.learning.mybatisplus.common.BaseEntity"); + strategy.setEntityLombokModel(true); + strategy.setRestControllerStyle(true); + // 公共父类 +// strategy.setSuperControllerClass("com.dashuai.learning.mybatisplus.common.BaseController"); + // 写于父类中的公共字段 + strategy.setSuperEntityColumns("id"); + strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); + strategy.setControllerMappingHyphenStyle(true); + strategy.setTablePrefix(pc.getModuleName() + "_"); + mpg.setStrategy(strategy); +// mpg.setTemplateEngine(new FreemarkerTemplateEngine()); + mpg.execute(); + } + +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/MybatisPlusApplication.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/MybatisPlusApplication.java new file mode 100644 index 0000000..a19f90c --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/MybatisPlusApplication.java @@ -0,0 +1,15 @@ +package com.dashuai.learning.mybatisplus; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan("com.dashuai.learning.mybatisplus.user.mapper") +public class MybatisPlusApplication { + + public static void main(String[] args) { + SpringApplication.run(MybatisPlusApplication.class, args); + } + +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MyMetaObjectHandler.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MyMetaObjectHandler.java new file mode 100644 index 0000000..724ca91 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MyMetaObjectHandler.java @@ -0,0 +1,32 @@ +package com.dashuai.learning.mybatisplus.config; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import org.apache.ibatis.reflection.MetaObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * Created in 2019.12.12 + * 配置自动填充 + * + * @author Liaozihong + */ +@Component +public class MyMetaObjectHandler implements MetaObjectHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class); + + @Override + public void insertFill(MetaObject metaObject) { + LOGGER.info("start insert fill ...."); + this.setFieldValByName("createAt", new Date(), metaObject); + } + + @Override + public void updateFill(MetaObject metaObject) { + LOGGER.info("start update fill ...."); + this.setFieldValByName("updateAt", new Date(), metaObject); + } +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MybatisPlusConfig.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MybatisPlusConfig.java new file mode 100644 index 0000000..dde8ca1 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/config/MybatisPlusConfig.java @@ -0,0 +1,32 @@ +package com.dashuai.learning.mybatisplus.config; + +import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MybatisPlusConfig { + /** + * 乐观锁配置,记得需要使用乐观锁的实体添加@Version,系统会自动帮你添加version + * + * @return + */ + @Bean + public OptimisticLockerInterceptor optimisticLockerInterceptor() { + return new OptimisticLockerInterceptor(); + } + + /** + * 可配置多租户信息等 + * + * @return + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + PaginationInterceptor page = new PaginationInterceptor(); + //设置方言类型 + page.setDialectType("mysql"); + return page; + } +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/controller/UserController.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/controller/UserController.java new file mode 100644 index 0000000..9369b8a --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/controller/UserController.java @@ -0,0 +1,18 @@ +package com.dashuai.learning.mybatisplus.user.controller; + + +import org.springframework.web.bind.annotation.RestController; + +/** + *

+ * 前端控制器 + *

+ * + * @author zoey + * @since 2019-12-12 + */ +@RestController +public class UserController { + +} + diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/entity/User.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/entity/User.java new file mode 100644 index 0000000..3b3a7e4 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/entity/User.java @@ -0,0 +1,53 @@ +package com.dashuai.learning.mybatisplus.user.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.Version; +import lombok.Data; +import lombok.experimental.Accessors; + +import java.util.Date; + +/** + *

+ * + *

+ * + * @author zoey + * @since 2019-12-12 + */ +@Accessors(chain = true) +@Data +public class User { + + private static final long serialVersionUID = 1L; + + + @TableId + private Long id; + /** + * 姓名 + */ + private String name; + + /** + * 年龄 + */ + private Integer age; + + /** + * 邮箱 + */ + private String email; + + @TableField(fill = FieldFill.INSERT) + private Date createAt; + + @TableField(fill = FieldFill.UPDATE) + private Date updateAt; + + @Version + private Integer version; + +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/mapper/UserMapper.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/mapper/UserMapper.java new file mode 100644 index 0000000..e5ea760 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/mapper/UserMapper.java @@ -0,0 +1,17 @@ +package com.dashuai.learning.mybatisplus.user.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.dashuai.learning.mybatisplus.user.entity.User; + +/** + *

+ * Mapper 接口 + *

+ * + * @author zoey + * @since 2019-12-12 + */ +public interface UserMapper extends BaseMapper { + + +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/IUserService.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/IUserService.java new file mode 100644 index 0000000..a6dfd11 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/IUserService.java @@ -0,0 +1,16 @@ +package com.dashuai.learning.mybatisplus.user.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.dashuai.learning.mybatisplus.user.entity.User; + +/** + *

+ * 服务类 + *

+ * + * @author zoey + * @since 2019-12-12 + */ +public interface IUserService extends IService { + +} diff --git a/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/impl/UserServiceImpl.java b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..79498c8 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/java/com/dashuai/learning/mybatisplus/user/service/impl/UserServiceImpl.java @@ -0,0 +1,19 @@ +package com.dashuai.learning.mybatisplus.user.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.dashuai.learning.mybatisplus.user.entity.User; +import com.dashuai.learning.mybatisplus.user.mapper.UserMapper; +import com.dashuai.learning.mybatisplus.user.service.IUserService; +import org.springframework.stereotype.Service; + +/** + *

+ * 服务实现类 + *

+ * + * @author zoey + * @since 2019-12-12 + */ +@Service +public class UserServiceImpl extends ServiceImpl implements IUserService { +} diff --git a/SpringBoot-Mybatis-Plus/src/main/resources/application.properties b/SpringBoot-Mybatis-Plus/src/main/resources/application.properties new file mode 100644 index 0000000..d14ca0a --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/resources/application.properties @@ -0,0 +1,12 @@ +##�˿ں� +server.port=8888 +spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8 +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.username=root +spring.datasource.password=root +##��־���� +logging.level.com.dashuai.learning.mybatisplus.user.mapper=debug +##mybatis-plus mapper xml �ļ���ַ +mybatis-plus.mapper-locations=classpath*:mapper/*Mapper.xml +##mybatis-plus type-aliases �ļ���ַ +mybatis-plus.type-aliases-package=com.dashuai.learning.mybatisplus.user.entity \ No newline at end of file diff --git a/SpringBoot-Mybatis-Plus/src/main/resources/user.sql b/SpringBoot-Mybatis-Plus/src/main/resources/user.sql new file mode 100644 index 0000000..99c6bfb --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/main/resources/user.sql @@ -0,0 +1,23 @@ +CREATE DATABASE test; +use test; +DROP TABLE IF EXISTS user; + + +CREATE TABLE user +( + id BIGINT(20) NOT NULL COMMENT '主键ID', + name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', + age INT(11) NULL DEFAULT NULL COMMENT '年龄', + email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱', + create_at datetime NULL DEFAULT null COMMENT '创建时间', + update_at datetime null default null COMMENT '修改时间', + version int(11) NOT NULL DEFAULT 1 COMMENT '版本号', + PRIMARY KEY (id) +); + +INSERT INTO user (id, name, age, email) VALUES +(1, 'Jone', 18, 'test1@baomidou.com'), +(2, 'Jack', 20, 'test2@baomidou.com'), +(3, 'Tom', 28, 'test3@baomidou.com'), +(4, 'Sandy', 21, 'test4@baomidou.com'), +(5, 'Billie', 24, 'test5@baomidou.com'); diff --git a/SpringBoot-Mybatis-Plus/src/test/java/com/dashuai/learning/mybatisplus/MybatisPlusApplicationTests.java b/SpringBoot-Mybatis-Plus/src/test/java/com/dashuai/learning/mybatisplus/MybatisPlusApplicationTests.java new file mode 100644 index 0000000..3e38859 --- /dev/null +++ b/SpringBoot-Mybatis-Plus/src/test/java/com/dashuai/learning/mybatisplus/MybatisPlusApplicationTests.java @@ -0,0 +1,107 @@ +package com.dashuai.learning.mybatisplus; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.dashuai.learning.mybatisplus.user.entity.User; +import com.dashuai.learning.mybatisplus.user.mapper.UserMapper; +import com.dashuai.learning.mybatisplus.user.service.IUserService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@RunWith(SpringRunner.class) +public class MybatisPlusApplicationTests { + + @Autowired + IUserService userService; + + + @Autowired + private UserMapper userMapper; + + @Test + public void testSelect() { + System.out.println(("----- selectAll method test ------")); + List userList = userMapper.selectList(null); + Assert.assertEquals(5, userList.size()); + userList.forEach(System.out::println); + } + + @Test + public void testUpdate() { +// User user = userMapper.selectById(2); +// assertThat(user.getAge()).isEqualTo(36); +// assertThat(user.getName()).isEqualTo("keep"); + User user = new User(); + user.setEmail("123@123"); + userMapper.update( + user, new UpdateWrapper().lambda() + .eq(User::getId, 2) + ); + assertThat(userMapper.selectById(2).getEmail()).isEqualTo("123@123"); + } + + /** + * 基于乐观锁修改 + */ + @Test + public void testOptimisticUpdate() { + User user = userMapper.selectById(2); + User user2 = new User(); + user2.setEmail("123@1234.com"); + user2.setVersion(user.getVersion()); + user2.setId(2L); + userMapper.updateById(user2); + assertThat(userMapper.selectById(2).getEmail()).isEqualTo("123@1234.com"); + } + + @Test + public void testSelectOne() { + User user = userMapper.selectById(1L); + System.out.println(user); + } + + @Test + public void testDelete() { +// assertThat(userMapper.deleteById(3L)).isGreaterThan(0); + assertThat(userMapper.delete(new QueryWrapper() + .lambda().eq(User::getName, "Zoey"))).isGreaterThan(0); + } + + @Test + public void testInsert() { + User user = new User(); + user.setName("Zoey"); + user.setAge(21); + user.setEmail("neo@tooool.org"); + user.setId(6L); + assertThat(userMapper.insert(user)).isGreaterThan(0); + // 成功直接拿会写的 ID + assertThat(user.getId()).isNotNull(); + } + + @Test + public void testPage() { + System.out.println("----- baseMapper 自带分页 ------"); + // current 当前页数,一页开始, size 每页条数 + Page page = new Page<>(1, 2); + IPage userIPage = userMapper.selectPage(page, new QueryWrapper() + .gt("age", 6)); +// assertThat(page).isSameAs(userIPage); + System.out.println("总条数 ------> " + userIPage.getTotal()); + System.out.println("当前页数 ------> " + userIPage.getCurrent()); + System.out.println("当前每页显示数 ------> " + userIPage.getSize()); + System.out.println(userIPage.getRecords()); + System.out.println("----- baseMapper 自带分页 ------"); + } +} diff --git a/build.gradle b/build.gradle index 0a622b6..0181d72 100644 --- a/build.gradle +++ b/build.gradle @@ -18,7 +18,7 @@ subprojects { maven { url 'http://maven.aliyun.com/nexus/content/groups/public' } } dependencies { - compile group: 'org.projectlombok', name: 'lombok', version: '1.18.4' + compileOnly 'org.projectlombok:lombok:1.18.8' compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2' compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2' testCompile group: 'junit', name: 'junit', version: '4.12' diff --git a/settings.gradle b/settings.gradle index 4dab9b6..dc58d18 100644 --- a/settings.gradle +++ b/settings.gradle @@ -40,7 +40,8 @@ rootProject.name = 'springboot' //include(':SpringBoot-Nacos-Config') //include(':SpringBoot-Builder-Docker') //include(':SpringBoot-Test-Starter') -include(':SpringBoot-Alibaba-Sentinel') +//include(':SpringBoot-Alibaba-Sentinel') +include(':SpringBoot-Mybatis-Plus') include(':SpringBoot-Utils') // spring-boot-starter-webflux模块与web冲突,如果web模块的类不能用,请注释下面的模块 //include(':SpringBoot-WebFlux') From d6bee8b563d1804d76bcf8668023f8a31ece68f6 Mon Sep 17 00:00:00 2001 From: zihong Date: Thu, 23 Apr 2020 15:15:26 +0800 Subject: [PATCH 04/14] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=A4=9A?= =?UTF-8?q?=E5=AF=B9=E5=A4=9A=E6=9F=A5=E8=AF=A2id=E5=86=B2=E7=AA=81?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-JWT/README.md | 6 +++--- SpringBoot-JWT/build.gradle | 3 ++- .../learning/jwt/api/LoginController.java | 6 ++---- .../jwt/service/impl/UserInfoServiceImpl.java | 2 ++ .../src/main/resources/mapper/RoleMapper.xml | 4 ++-- .../src/main/resources/sql/shiro.sql | 10 ++++----- .../com/dashuai/learning/jwt/MysqlTest.java | 21 +++++++++++++++++++ 7 files changed, 37 insertions(+), 15 deletions(-) create mode 100644 SpringBoot-JWT/src/test/java/com/dashuai/learning/jwt/MysqlTest.java diff --git a/SpringBoot-JWT/README.md b/SpringBoot-JWT/README.md index 0c940d7..1f938d2 100644 --- a/SpringBoot-JWT/README.md +++ b/SpringBoot-JWT/README.md @@ -481,11 +481,11 @@ public class SwaggerConfig { } ``` 调用授权api,登录成功,会返回token: -![](https://ws1.sinaimg.cn/large/006mOQRagy1fyfnrtqb5kj315u0q5dhx.jpg) +![](https://ww1.sinaimg.cn/large/006mOQRagy1fyfnrtqb5kj315u0q5dhx.jpg) 拿到返回的token,调用接口,可以看到成功调用: -![](https://ws1.sinaimg.cn/large/006mOQRagy1fyfntf2bhuj31aw0n8764.jpg) +![](https://ww1.sinaimg.cn/large/006mOQRagy1fyfntf2bhuj31aw0n8764.jpg) 去掉token或使用错误的token将会报token认证失败: -![](https://ws1.sinaimg.cn/large/006mOQRagy1fyfnuknvrkj310a0lz0u1.jpg) +![](https://ww1.sinaimg.cn/large/006mOQRagy1fyfnuknvrkj310a0lz0u1.jpg) JWT 弊端,如果使用JWT来着做会话管理,那么注销、改密、续签等问题,你将要慢慢爬坑。 具体可参考大佬写的一篇文章:http://blog.didispace.com/learn-how-to-use-jwt-xjf/ diff --git a/SpringBoot-JWT/build.gradle b/SpringBoot-JWT/build.gradle index 85447ab..6c554e2 100644 --- a/SpringBoot-JWT/build.gradle +++ b/SpringBoot-JWT/build.gradle @@ -1,5 +1,5 @@ dependencies { - compile project(':SpringBoot-Utils') + compile project(':SpringBoot-Support') compile 'com.auth0:java-jwt:3.4.0' compile 'org.apache.shiro:shiro-spring:1.4.0' compile group: 'org.springframework.boot', name: 'spring-boot-devtools', version: '2.0.4.RELEASE' @@ -7,4 +7,5 @@ dependencies { compile group: 'com.alibaba', name: 'druid', version: '1.1.10' compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46' compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2' + testCompile('org.springframework.boot:spring-boot-starter-test:2.0.4.RELEASE') } diff --git a/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/api/LoginController.java b/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/api/LoginController.java index 5c97d94..2b642a2 100644 --- a/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/api/LoginController.java +++ b/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/api/LoginController.java @@ -11,8 +11,7 @@ import io.swagger.annotations.ApiOperation; import org.apache.shiro.crypto.hash.SimpleHash; import org.springframework.beans.factory.annotation.Autowired; - -import java.io.UnsupportedEncodingException; +import org.springframework.web.bind.annotation.*; /** * Login controller @@ -65,10 +64,9 @@ public ApiResult login(@RequestParam("username") String username, * * @param message the message * @return the api result - * @throws UnsupportedEncodingException the unsupported encoding exception */ @GetMapping(path = "/unauthorized/{message}") - public ApiResult unauthorized(@PathVariable String message) throws UnsupportedEncodingException { + public ApiResult unauthorized(@PathVariable String message) { return ApiResult.prepare().error(null, 401, message); } } diff --git a/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/service/impl/UserInfoServiceImpl.java b/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/service/impl/UserInfoServiceImpl.java index 3babfe9..40f3cfa 100644 --- a/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/service/impl/UserInfoServiceImpl.java +++ b/SpringBoot-JWT/src/main/java/com/dashuai/learning/jwt/service/impl/UserInfoServiceImpl.java @@ -15,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.*; + @Service @Slf4j public class UserInfoServiceImpl implements UserInfoService { diff --git a/SpringBoot-JWT/src/main/resources/mapper/RoleMapper.xml b/SpringBoot-JWT/src/main/resources/mapper/RoleMapper.xml index 6fba703..f57ff4a 100644 --- a/SpringBoot-JWT/src/main/resources/mapper/RoleMapper.xml +++ b/SpringBoot-JWT/src/main/resources/mapper/RoleMapper.xml @@ -9,7 +9,7 @@ - + @@ -23,7 +23,7 @@ id, available, description, role + + select + + from user + + + + + + delete from user + where id = #{id,jdbcType=INTEGER} + + + + insert into user (id, name) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) + + + + insert into user + + + id, + + + name, + + + + + #{id,jdbcType=INTEGER}, + + + #{name,jdbcType=VARCHAR}, + + + + + + update user + + + name = #{name,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + + update user + set name = #{name,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file From bbc3f55ea9e506f4ed49313c8b7a663369c943f6 Mon Sep 17 00:00:00 2001 From: zihong Date: Mon, 11 May 2020 15:52:40 +0800 Subject: [PATCH 07/14] chore:update README --- SpringBoot-Mysql-Master-Slave/README.md | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/SpringBoot-Mysql-Master-Slave/README.md b/SpringBoot-Mysql-Master-Slave/README.md index 4fba604..36cbda8 100644 --- a/SpringBoot-Mysql-Master-Slave/README.md +++ b/SpringBoot-Mysql-Master-Slave/README.md @@ -1,7 +1,27 @@ ### SpringBoot 操作Mysql读写分离 思路: 使用AOP对读写的数据源进行切换,配置主数据源和从数据源, -aop拦截到方法,判断前缀是查还是增删改,对其进行相应的数据源切换操作。 +aop拦截到方法,判断前缀是查还是增删改,对其进行相应的数据源切换操作。 +优点: +1. 负载均衡:通常情况下,会使用 主服务器 对数据进行 更新、删除 和 新建 等操作,而将 查询 工作落到 从库 头上。 +2. 异地容灾备份: 可以将主服务器上的数据同步到 异地从服务器 上,极大地提高了 数据安全性。 +3. 高可用:数据库的复制功能实现了 主服务器 与 从服务器间 的数据同步,一旦主服务器出了 故障,从服务器立即担当起主服务器的角色,保障系统持续稳定运作。 +4. 高扩展性:主从复制 模式支持 2 种扩展方式: + scale-up + 向上扩展或者 纵向扩展,主要是提供比现在服务器 性能更好 的服务器,比如 增加 CPU 和 内存 以及 磁盘阵列等,因为有多台服务器,所以可扩展性比单台更大。 + scale-out + 向外扩展或者 横向扩展,是指增加 服务器数量 的扩展,这样主要能分散各个服务器的压力。 +缺点: +1. 成本增加: 搭建主从肯定会增加成本,毕竟一台服务器和两台服务器的成本完全不同,另外由于主从必须要开启 二进制日志,所以也会造成额外的 性能消耗。 +2. 数据延迟: 从库 从 主库 复制数据肯定是会有一定的 数据延迟 的。所以当刚插入就出现查询的情况,可能查询不出来。当然如果是插入者自己查询,那么可以直接从 主库 中查询出来,当然这个也是需要用代码来控制的。 +3. 写入更慢:主从复制 主要是针对 读远大于写 或者对 数据备份实时性 要求较高的系统中。因为 主服务器在写中需要更多操作,而且 只有一台 可以写入的 主库,所以写入的压力并不能被分散。这时可以考虑使用数据库中间件进行分库分表了。 + +主从复制的前提条件 + + 主从服务器 操作系统版本 和 位数 一致。 + 主数据库和从数据库的 版本 要一致。 + 主数据库和从数据库中的 数据 要一致。 + 主数据库 开启 二进制日志,主数据库和从数据库的 server_id 在局域网内必须 唯一。 From 01b2cdf587da46c167c96edac08c3ac055148dd5 Mon Sep 17 00:00:00 2001 From: dashuai <15017263266@163.com> Date: Sat, 4 Jul 2020 16:38:59 +0800 Subject: [PATCH 08/14] =?UTF-8?q?feat:=E6=94=AF=E4=BB=98=E5=AE=9D=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Alipay/.gitignore | 26 +++ SpringBoot-Alipay/README.md | 14 ++ SpringBoot-Alipay/build.gradle | 4 + .../learning/alipay/AlipayApplication.java | 12 ++ .../learning/alipay/api/AlipayApi.java | 95 +++++++++++ .../alipay/config/AlipayConfiguration.java | 45 +++++ .../learning/alipay/config/SwaggerConfig.java | 52 ++++++ .../learning/alipay/model/AlipayParam.java | 11 ++ .../alipay/service/AlipayService.java | 31 ++++ .../service/impl/AlipayServiceImpl.java | 158 ++++++++++++++++++ .../learning/alipay/utils/AlipayUtils.java | 5 + .../src/main/resources/application.properties | 21 +++ .../alipay/AlipayApplicationTests.java | 16 ++ .../docker/DockerApplicationTests.java | 17 ++ 14 files changed, 507 insertions(+) create mode 100644 SpringBoot-Alipay/.gitignore create mode 100644 SpringBoot-Alipay/README.md create mode 100644 SpringBoot-Alipay/build.gradle create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/AlipayApplication.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/api/AlipayApi.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/AlipayConfiguration.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/SwaggerConfig.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/model/AlipayParam.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/AlipayService.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/impl/AlipayServiceImpl.java create mode 100644 SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/utils/AlipayUtils.java create mode 100644 SpringBoot-Alipay/src/main/resources/application.properties create mode 100644 SpringBoot-Alipay/src/test/java/com/dashuai/learning/alipay/AlipayApplicationTests.java create mode 100644 SpringBoot-Builder-Docker/src/test/java/com/dashuai/learning/docker/DockerApplicationTests.java diff --git a/SpringBoot-Alipay/.gitignore b/SpringBoot-Alipay/.gitignore new file mode 100644 index 0000000..9243c63 --- /dev/null +++ b/SpringBoot-Alipay/.gitignore @@ -0,0 +1,26 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/SpringBoot-Alipay/README.md b/SpringBoot-Alipay/README.md new file mode 100644 index 0000000..e6d46e7 --- /dev/null +++ b/SpringBoot-Alipay/README.md @@ -0,0 +1,14 @@ +## 接入支付宝 +### 使用沙箱环境 +https://openhome.alipay.com/platform/appDaily.htm?tab=account + +配置公钥和私钥、异步回调、同步回调 + +### PC场景支付API + +https://docs.open.alipay.com/270/alipay.trade.page.pay + +### 签名问题 +https://docs.open.alipay.com/291/105974/ + +### 注意回调必须是外网地址,不然支付宝通知不到 diff --git a/SpringBoot-Alipay/build.gradle b/SpringBoot-Alipay/build.gradle new file mode 100644 index 0000000..1d6937d --- /dev/null +++ b/SpringBoot-Alipay/build.gradle @@ -0,0 +1,4 @@ +dependencies { + compile project(':SpringBoot-Utils') + compile 'com.alipay.sdk:alipay-sdk-java:3.4.49.ALL' +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/AlipayApplication.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/AlipayApplication.java new file mode 100644 index 0000000..8c975da --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/AlipayApplication.java @@ -0,0 +1,12 @@ +package com.dashuai.learning.alipay; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AlipayApplication { + + public static void main(String[] args) { + SpringApplication.run(AlipayApplication.class, args); + } +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/api/AlipayApi.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/api/AlipayApi.java new file mode 100644 index 0000000..bc87f5f --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/api/AlipayApi.java @@ -0,0 +1,95 @@ +package com.dashuai.learning.alipay.api; + +import com.dashuai.learning.alipay.service.AlipayService; +import com.dashuai.learning.utils.result.ApiResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +@RestController +public class AlipayApi { + @Autowired + private AlipayService alipayService; + + private final static Logger logger = LoggerFactory.getLogger(AlipayApi.class); + + //1.申请付款 +// @ApiOperation("申请付款") + @RequestMapping(value = "/order", method = RequestMethod.GET) + public String alipay() { + return alipayService.alipay(); + } + + //2.a1lipay支持同步返回地址 +// @ApiOperation("同步") + @RequestMapping(value = "/getReturnUrlInfo", method = RequestMethod.GET) + public ApiResult alipayReturnUrlInfo(HttpServletRequest request) { + Map params = new HashMap<>(); + Map requestParams = request.getParameterMap(); + return ApiResult.prepare().success(requestParams, 200, "支付成功!"); + } + + @RequestMapping("/") + public String index() { + return "你妹哦"; + } + + //3.alipay异步通知调用地址 +// @ApiOperation("异步通知") + @RequestMapping(value = "/getNotifyUrlInfo", method = RequestMethod.POST) + public void alipayNotifyUrlInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { + + boolean verifyResult = alipayService.rsaCheckV1(request); + System.out.println(verifyResult); + if (verifyResult) {// 验证成功 + //验证成功 + //请在这里加上商户的业务逻辑程序代码,如保存支付宝交易号 + //商户订单号 + String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8"); + //支付宝交易号 + String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8"); + // 交易状态 + String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8"); + // ——请根据您的业务逻辑来编写程序(以下代码仅作参考)—— + + if (trade_status.equals("TRADE_FINISHED")) { + // 判断该笔订单是否在商户网站中已经做过处理 + // 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 + // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 + // 如果有做过处理,不执行商户的业务程序 + System.out.println("交易完成"); + // 注意: + // 如果签约的是可退款协议,退款日期超过可退款期限后(如三个月可退款),支付宝系统发送该交易状态通知 + // 如果没有签约可退款协议,那么付款完成后,支付宝系统发送该交易状态通知。 + } else if (trade_status.equals("TRADE_SUCCESS")) { + System.out.println("交易成功"); + // 判断该笔订单是否在商户网站中已经做过处理 + // 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 + // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 + // 如果有做过处理,不执行商户的业务程序 + + // 注意: + // 如果签约的是可退款协议,那么付款完成后,支付宝系统发送该交易状态通知。 + } else if (trade_status.equals("WAIT_BUYER_PAY")) { + System.out.println("交易创建,等待付款"); + + } + // ——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— + + System.out.println("支付成功"); + + } else {// 验证失败 + System.out.println("支付失败"); + } + + } +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/AlipayConfiguration.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/AlipayConfiguration.java new file mode 100644 index 0000000..3f16628 --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/AlipayConfiguration.java @@ -0,0 +1,45 @@ +package com.dashuai.learning.alipay.config; + +import com.alipay.api.AlipayClient; +import com.alipay.api.DefaultAlipayClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class AlipayConfiguration { + @Value("${alipay.ali_return_url}") + private String ali_return_url; + + @Value("${alipay.ali_notify_url}") + private String ali_notify_url; + +// @Value("${alipay.product_no}") +// private String product_no; + + @Value("${alipay.time_express}") + private String time_express; + + @Value("${alipay.gatewary.url}") + private String url; + + @Value("${alipay.appid}") + private String appid; + + @Value("${alipay.private_key}") + private String private_key; + + @Value("${alipay.ali_public_key}") + private String ali_public_key; + + @Value("${alipay.sign_type}") + private String sign_type; + + + @Bean + public AlipayClient alipayClient() { + return new DefaultAlipayClient(url, appid + , private_key, "json", "UTF-8" + , ali_public_key, sign_type); + } +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/SwaggerConfig.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/SwaggerConfig.java new file mode 100644 index 0000000..532a2f0 --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/config/SwaggerConfig.java @@ -0,0 +1,52 @@ +package com.dashuai.learning.alipay.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * Swagger config + *

+ * Created in 2018.11.08 + *

+ * + * @author Liaodashuai + */ +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + /** + * Create rest api docket. + * + * @return the docket + */ + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(metaData()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.dashuai.learning.alipay.api")) + .paths(PathSelectors.any()) + .build(); + + } + + private ApiInfo metaData() { + + return new ApiInfoBuilder() + .title("SpringBoot Elasticsearch Demo API文档") + .description("SpringBoot 集成支付宝支付demo") + .termsOfServiceUrl("") + .contact(new Contact("dashuai", "", "")) + .version("1.0") + .build(); + } +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/model/AlipayParam.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/model/AlipayParam.java new file mode 100644 index 0000000..1c50a85 --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/model/AlipayParam.java @@ -0,0 +1,11 @@ +package com.dashuai.learning.alipay.model; + +import lombok.Data; + +@Data +public class AlipayParam { + private String amount; + private String orderName; + private String orderId; + +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/AlipayService.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/AlipayService.java new file mode 100644 index 0000000..b637182 --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/AlipayService.java @@ -0,0 +1,31 @@ +package com.dashuai.learning.alipay.service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public interface AlipayService { + /** + * 付款 + * + * @return + */ + String alipay(); + + /** + * 付款同步返回地址 + * + * @param request + * @return + */ + String synchronous(HttpServletRequest request); + + /** + * 付款异步通知地址 + * + * @param request + * @param response + */ + void notify(HttpServletRequest request, HttpServletResponse response); + + boolean rsaCheckV1(HttpServletRequest request); +} diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/impl/AlipayServiceImpl.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/impl/AlipayServiceImpl.java new file mode 100644 index 0000000..6bc3904 --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/service/impl/AlipayServiceImpl.java @@ -0,0 +1,158 @@ +package com.dashuai.learning.alipay.service.impl; + +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.domain.AlipayTradeWapPayModel; +import com.alipay.api.internal.util.AlipaySignature; +import com.alipay.api.request.AlipayTradePagePayRequest; +import com.alipay.api.request.AlipayTradePayRequest; +import com.alipay.api.response.AlipayTradePayResponse; +import com.dashuai.learning.alipay.service.AlipayService; +import com.dashuai.learning.utils.json.JSONParseUtils; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.UUID; + +@Service +@Slf4j +public class AlipayServiceImpl implements AlipayService { + + @Value("${alipay.ali_return_url}") + private String ali_return_url; + + @Value("${alipay.ali_notify_url}") + private String ali_notify_url; + + @Value("${alipay.product_no}") + private String product_no; + + @Value("${alipay.time_express}") + private String time_express; + + @Value("${alipay.gatewary.url}") + private String url; + + @Value("${alipay.appid}") + private String appid; + + @Value("${alipay.private_key}") + private String private_key; + + @Value("${alipay.ali_public_key}") + private String ali_public_key; + + @Value("${alipay.sign_type}") + private String sign_type; + @Autowired + private AlipayClient alipayClient; + + public static final String TRADE_SUCCESS = "TRADE_SUCCESS"; //支付成功标识 + public static final String TRADE_CLOSED = "TRADE_CLOSED";//交易关闭 + + private final static Logger logger = LoggerFactory.getLogger(AlipayServiceImpl.class); + + /** + * 接口地址:https://docs.open.alipay.com/270/alipay.trade.page.pay + * @return + */ + @Override + public String alipay() { + //创建Alipay支付请求对象 + AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); + request.setReturnUrl(ali_return_url); //同步通知url + request.setNotifyUrl(ali_notify_url);//异步通知url + // 销售产品码 必填 + AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); + model.setOutTradeNo(String.valueOf(UUID.randomUUID())); + model.setBody("出售男神"); + model.setSubject("男神一枚"); + model.setTotalAmount("0.01"); + model.setTimeoutExpress(time_express); + model.setProductCode("FAST_INSTANT_TRADE_PAY"); +// ExtendParams extendParams = new ExtendParams(); +// extendParams.setSysServiceProviderId("2088511833207846"); +// model.setExtendParams(extendParams); + model.setPassbackParams("merchantBizType%3d3C%26merchantBizNo%3d2016010101111"); + request.setBizModel(model); + try { + return alipayClient.pageExecute(request).getBody(); //调用SDK生成表单 + } catch (Exception e) { + logger.info("支付请求发送失败"); + throw new RuntimeException("支付请求发送失败,请联系我们客服协助处理"); + } + + } + + @Override + public String synchronous(HttpServletRequest request) { + return null; + } + + @Override + public void notify(HttpServletRequest request, HttpServletResponse response) { + //接收参数进行校验 + + } + /** + * 统一收单交易支付接口 @备注: + * + * @param model + * @return + * @throws AlipayApiException + */ + public String alipaPay(AlipayTradeWapPayModel model) throws AlipayApiException { + AlipayTradePayRequest request = new AlipayTradePayRequest(); + request.setBizModel(model); + request.setNotifyUrl(ali_notify_url); + request.setReturnUrl(ali_return_url); + AlipayTradePayResponse response = alipayClient.execute(request); + if (response.isSuccess()) { + return response.getBody(); + } else { + return null; + } + } + + /** + * 校验签名 + * + * @param request + * @return + */ + @Override + public boolean rsaCheckV1(HttpServletRequest request) { + // https://docs.open.alipay.com/54/106370 + // 获取支付宝POST过来反馈信息 + Map params = new HashMap<>(); + Map requestParams = request.getParameterMap(); + for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) { + String name = (String) iter.next(); + String[] values = (String[]) requestParams.get(name); + String valueStr = ""; + for (int i = 0; i < values.length; i++) { + valueStr = (i == values.length - 1) ? valueStr + values[i] + : valueStr + values[i] + ","; + } + params.put(name, valueStr); + } + System.out.println(JSONParseUtils.object2JsonString(params)); + + try { + return AlipaySignature.rsaCheckV1(params, ali_public_key, "UTF-8", "RSA2"); + } catch (AlipayApiException e) { + logger.warn("verify sigin error, exception is:{}", e); + return false; + } + } + +} \ No newline at end of file diff --git a/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/utils/AlipayUtils.java b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/utils/AlipayUtils.java new file mode 100644 index 0000000..1a4b517 --- /dev/null +++ b/SpringBoot-Alipay/src/main/java/com/dashuai/learning/alipay/utils/AlipayUtils.java @@ -0,0 +1,5 @@ +package com.dashuai.learning.alipay.utils; + +public class AlipayUtils { + +} diff --git a/SpringBoot-Alipay/src/main/resources/application.properties b/SpringBoot-Alipay/src/main/resources/application.properties new file mode 100644 index 0000000..a9f8c0a --- /dev/null +++ b/SpringBoot-Alipay/src/main/resources/application.properties @@ -0,0 +1,21 @@ +#支付宝配置 +#支付同步返回地址 +alipay.ali_return_url=http://xxxxx.com/getReturnUrlInfo +#支付异步通知地址 +alipay.ali_notify_url=http://xxxxx.com/getNotifyUrlInfo +#产品码 +alipay.product_no=FAST_INSTANT_TRADE_PAY +#超时时、间 +alipay.time_express=15m +#支付网关 +alipay.gatewary.url=https://openapi.alipaydev.com/gateway.do +#商户号 +alipay.appid=201609240058498 +#私钥 +alipay.private_key=MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBwggSiAgEAAoIBAQCHZM7URWZSNaRi9ZXaiKxfGMKiuVr4fR1AnGFx0L432whd2gf9MOWZtoq1QiUczbzt2/CTb9l1sFnp/LViWC+FbUeEUU3xXkFmEE+XgMld5g2X0zZOsAScm1vz+IEMcrk5PgBLC1avdgEBDDHUmwExQ2FF6vXoRq5SvTNa1jKuCBBTjwHWzVnoG4m9zAVfuIiU8ZpmwH/UvYrkT9Xjz6dzpvmhEFP/nHQlyE4P8alBN0q0NpUXxxPoYhTHNKM5uyrwNGS90yf/K6BPrAr0HRJyksuEdag1MqL2zYxRscu5s6Mh91RyDxzKFZHTmvOxZ0x2YYETVkPKxeglca/kzwg9AgMBAAECggEAY3nOeKmQtwAQimCzvD9Eng4cGuCilQWfs3PyKGRdDb7RE9t4mS8O0nQKz4gMqnACyqQYysqX9F8ggMkaH2p5Z8fVjsMJyDgfRrTfNYn66RF4lT8qnH+4s7N1yPehIRs9OXBzWK+4/etua22hQvqr0p0V3//0srcTp1i5XZkY3UGeWgaV/VBujaGdiRiXLoLz2SRfRhuQUcppt+RY1X2VrmBZJI7aXwYxFfGbadW4es+DuX3uynI2M+wWEkt1A9vR57kU5s0zlNzTqltNyWPmv1kY5zMNRNbrdT0E+bBmNMaSVB83XPgRKGz1ptO7LfMBuh0PnBglePB4MXgMfw0bYQKBgQDO8ue2B51nNhMcuEBc339ywyL7X7ChA6Sz2FtQ+e1ONoogsRGtVrkac6Pxqun9SnpJVsLaNjsXmBvvcqCN822gou17r8iPYrjznGnmnUO20LIfxs7tibzygSiZ492wUMvNTyfhkdjtkU18PNm5j23dYJ2iUyBW7iyi4LltVj0BVQKBgQCnfCKoRV+Nu5NIvh8eQKgrJNtPSrd5Y9Teq0nJ1WsXQSc06617lHQQAyRmzAGzExo5USa5BgYoZe6tUQpDq8VvszJKC93JJWbPeaXT3Qak4hu/Z8cVZJf5ehzxEyg4wE/T2kb8GhCQP03vUjHxx9tasffbfayx/DIUb4szsO8LSQKBgBpcXp+VQLuQ68ZQwgIShg18Rcx3V+xqpmQyPw+FhnDcCaQ4aeQGk/WGnW9/MecNwZ3t60wYdFaBDa3mkAUE6QX5Ov7yWT3KeXyug97YUXPMCaR6kok3blYFlcJkgCyhXhR87LuS9Grug0w8BA/a8UetsuamaAwqsozcy0HeJk8xAoGADXKMHdKkH28mHjsVqIosdnpZGX64SIjZeJ9sJ0Z5eL6EdV1O6pM61mZKL+7FXCl2e4+mekififLVPRk6p8BM8/EBYqydPB9Cp/nudJpUhDybWbztYSxYf3FsjXaqThQy1KG7/VXiapKKoWKKHA2d8SRE8Fyg1xGWu8lQ9e+I4fECgYB3A97u/ADY1VRBuDhXsBvJVC507SEmHp/betHCeXtjXMO0aT6t/J2R62aU3XNIWIWob5FOTMfuQNQULxWmoKJ870gsKSOLyzy/jKnXYPtst5W+S2c0mNuSifZzTLE2ElaFwTXWEO0U81FqLR2/+ns8mHqg36dTV+XTjAvXe/O54A== +#公钥 +alipay.ali_public_key=MIIBIjANBgkqhkiG9w0BAQEFAAOC8AMIIBCgKCAQEAh2TO1EVmUjWkYvWV2oisXxjCorla+H0dQJxhcdC+N9sIXdoH/TDlmbaKtUIlHM287dvwk2/ZdbBZ6fy1YlgvhW1HhFFN8V5BZhBPl4DJXeYNl9M2TrAEnJtb8/iBDHK5OT4ASwtWr3YBAQwx1JsBMUNhRer16EauUr0zWtYyrggQU48B1s1Z6BuJvcwFX7iIlPGaZsB/1L2K5E/V48+nc6b5oRBT/5x0JchOD/GpQTdKtDaVF8cT6GIUxzSjObsq8DRkvdMn/yugT6wK9B0ScpLLhHWoNTKi9s2MUbHLubOjIfdUcg8cyhWR05rzsWdMdmGBE1ZDysXoJXGv5M8IPQIDAQAB +#加密方式 +alipay.sign_type=RSA2 + +server.port=8080 \ No newline at end of file diff --git a/SpringBoot-Alipay/src/test/java/com/dashuai/learning/alipay/AlipayApplicationTests.java b/SpringBoot-Alipay/src/test/java/com/dashuai/learning/alipay/AlipayApplicationTests.java new file mode 100644 index 0000000..d42de33 --- /dev/null +++ b/SpringBoot-Alipay/src/test/java/com/dashuai/learning/alipay/AlipayApplicationTests.java @@ -0,0 +1,16 @@ +package com.dashuai.learning.alipay; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class AlipayApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/SpringBoot-Builder-Docker/src/test/java/com/dashuai/learning/docker/DockerApplicationTests.java b/SpringBoot-Builder-Docker/src/test/java/com/dashuai/learning/docker/DockerApplicationTests.java new file mode 100644 index 0000000..08e9179 --- /dev/null +++ b/SpringBoot-Builder-Docker/src/test/java/com/dashuai/learning/docker/DockerApplicationTests.java @@ -0,0 +1,17 @@ +package com.dashuai.learning.docker; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class DockerApplicationTests { + + @Test + public void contextLoads() { + } + +} + From a47a3dc7bd5e9c3e73b3ca915853313ed771d3ce Mon Sep 17 00:00:00 2001 From: liaozihong Date: Wed, 8 Jul 2020 20:27:33 +0800 Subject: [PATCH 09/14] =?UTF-8?q?feat:=E6=B7=BB=E5=8A=A0freemarker?= =?UTF-8?q?=E7=94=9F=E6=88=90java=E7=B1=BB=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Mybatis-Freemarker/.gitignore | 32 ++++ SpringBoot-Mybatis-Freemarker/README.md | 1 + SpringBoot-Mybatis-Freemarker/build.gradle | 8 + .../mybatis/freemarker/CodeGenerator.java | 146 +++++++++++++++++ ...pringBootMybatisFreemarkerApplication.java | 48 ++++++ .../freemarker/config/MybatisPlusConfig.java | 37 +++++ .../WaNewbieActivityListController.java | 36 +++++ .../dao/WaNewbieActivityListDao.java | 16 ++ .../entity/WaNewbieActivityList.java | 87 ++++++++++ .../handler/IntegerListHandler.java | 53 ++++++ .../handler/JavaObjectTypeHandler.java | 66 ++++++++ .../freemarker/handler/ListJsonHandler.java | 52 ++++++ .../service/WaNewbieActivityListService.java | 16 ++ .../impl/WaNewbieActivityListServiceImpl.java | 20 +++ .../freemarker/utils/JSONParseUtils.java | 58 +++++++ .../src/main/resources/application.yml | 40 +++++ .../mappers/WaNewbieActivityListMapper.xml | 24 +++ .../main/resources/mybatis/mybatis-config.xml | 18 +++ .../resources/templates/controller.java.ftl | 39 +++++ .../main/resources/templates/entity.java.ftl | 152 ++++++++++++++++++ .../main/resources/templates/mapper.java.ftl | 20 +++ .../main/resources/templates/mapper.xml.ftl | 39 +++++ .../main/resources/templates/service.java.ftl | 20 +++ .../resources/templates/serviceImpl.java.ftl | 26 +++ SpringBoot-Rocketmq/README.md | 6 + settings.gradle | 5 +- 26 files changed, 1063 insertions(+), 2 deletions(-) create mode 100644 SpringBoot-Mybatis-Freemarker/.gitignore create mode 100644 SpringBoot-Mybatis-Freemarker/README.md create mode 100644 SpringBoot-Mybatis-Freemarker/build.gradle create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/CodeGenerator.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/SpringBootMybatisFreemarkerApplication.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/config/MybatisPlusConfig.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/controller/WaNewbieActivityListController.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/dao/WaNewbieActivityListDao.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/entity/WaNewbieActivityList.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/IntegerListHandler.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/JavaObjectTypeHandler.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/ListJsonHandler.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/WaNewbieActivityListService.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/impl/WaNewbieActivityListServiceImpl.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/utils/JSONParseUtils.java create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/application.yml create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/mappers/WaNewbieActivityListMapper.xml create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/mybatis/mybatis-config.xml create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/templates/controller.java.ftl create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/templates/entity.java.ftl create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.java.ftl create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.xml.ftl create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/templates/service.java.ftl create mode 100644 SpringBoot-Mybatis-Freemarker/src/main/resources/templates/serviceImpl.java.ftl diff --git a/SpringBoot-Mybatis-Freemarker/.gitignore b/SpringBoot-Mybatis-Freemarker/.gitignore new file mode 100644 index 0000000..6c01878 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/.gitignore @@ -0,0 +1,32 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/SpringBoot-Mybatis-Freemarker/README.md b/SpringBoot-Mybatis-Freemarker/README.md new file mode 100644 index 0000000..dba3799 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/README.md @@ -0,0 +1 @@ +### 使用freemarker模板生成java类 \ No newline at end of file diff --git a/SpringBoot-Mybatis-Freemarker/build.gradle b/SpringBoot-Mybatis-Freemarker/build.gradle new file mode 100644 index 0000000..d32ef8f --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/build.gradle @@ -0,0 +1,8 @@ +dependencies { + compile project(':SpringBoot-Support') + compile 'com.alibaba:druid-spring-boot-starter:1.1.16' + compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46' + compile group: 'org.freemarker', name: 'freemarker', version: '2.3.30' + compile 'com.baomidou:mybatis-plus-generator:3.1.2' + compile 'com.baomidou:mybatis-plus-boot-starter:3.1.2' +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/CodeGenerator.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/CodeGenerator.java new file mode 100644 index 0000000..1e476f4 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/CodeGenerator.java @@ -0,0 +1,146 @@ +package com.dashuai.learning.mybatis.freemarker; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.generator.AutoGenerator; +import com.baomidou.mybatisplus.generator.InjectionConfig; +import com.baomidou.mybatisplus.generator.config.*; +import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; +import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CodeGenerator { + public static void main(String[] args) { + String projectName = "SpringBoot-Mybatis-Freemarker"; + String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); + final String projectPath = path.substring(0, path.indexOf(projectName) + projectName.length() + 1); + System.out.println(projectPath); + AutoGenerator generator = new AutoGenerator(); + generator.setTemplateEngine(new FreemarkerTemplateEngine()); + GlobalConfig gc = new GlobalConfig(); + gc.setAuthor("liaozihong"); + gc.setOutputDir(projectPath + "src/main/java"); + gc.setFileOverride(false);// 是否覆盖同名文件,默认是false + gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false + gc.setEnableCache(false);// XML 二级缓存 + gc.setBaseResultMap(true);// XML ResultMap + gc.setBaseColumnList(true);// XML columList + /* 自定义文件命名,注意 %s 会自动填充表实体属性! */ + gc.setMapperName("%sDao"); + gc.setXmlName("%sMapper"); + gc.setServiceName("%sService"); + gc.setServiceImplName("%sServiceImpl"); +// gc.setControllerName("%sController"); + generator.setGlobalConfig(gc); + + // 数据源配置 + DataSourceConfig dsc = new DataSourceConfig(); + dsc.setDbType(DbType.MYSQL); + dsc.setDriverName("com.mysql.jdbc.Driver"); + dsc.setUsername("root"); + dsc.setPassword("root"); + dsc.setUrl("jdbc:mysql://127.0.0.1:3306/fantan?useUnicode=true&characterEncoding=utf-8"); + dsc.setTypeConvert(new MySqlTypeConvert()); + generator.setDataSource(dsc); + + // 策略配置 + StrategyConfig strategy = new StrategyConfig(); +// strategy.setTablePrefix(new String[] { "wa" });// 表前缀 + // 表名生成策略 + strategy.setNaming(NamingStrategy.underline_to_camel); + // 需要生成的表 + strategy.setInclude("wa_newbie_activity_list"); + strategy.setEntityLombokModel(true); + // strategy.setExclude(new String[]{"test"}); // 排除生成的表 + // 自定义实体父类 + // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); + // 自定义实体,公共字段 + // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); + // 自定义 mapper 父类 + // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); + // 自定义 service 父类 + // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); + // 自定义 service 实现类父类 + // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); + // 自定义 controller 父类 + // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); + // 【实体】是否生成字段常量(默认 false) + // public static final String ID = "test_id"; + // strategy.setEntityColumnConstant(true); + // 【实体】是否为构建者模型(默认 false) + // public User setName(String name) {this.name = name; return this;} + // strategy.setEntityBuilderModel(true); + generator.setStrategy(strategy); + + // 包配置 + PackageConfig pc = new PackageConfig(); + pc.setParent("com.dashuai.learning.mybatis.freemarker"); + //控制器可选生成 +// pc.setController("controller"); + pc.setService("service"); + pc.setServiceImpl("service.impl"); + pc.setMapper("dao"); + pc.setEntity("entity"); +// pc.setXml(null); + generator.setPackageInfo(pc); + + // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 + InjectionConfig cfg = new InjectionConfig() { + @Override + public void initMap() { + Map map = new HashMap<>(); + map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); + this.setMap(map); + } + }; + // + // // 自定义 xxList.jsp 生成 + List focList = new ArrayList<>(); + // focList.add(new FileOutConfig("/template/list.jsp.vm") { + // @Override + // public String outputFile(TableInfo tableInfo) { + // // 自定义输入文件名称 + // return "D://my_" + tableInfo.getEntityName() + ".jsp"; + // } + // }); + // cfg.setFileOutConfigList(focList); + // generator.setCfg(cfg); + // + // 调整 xml 生成目录演示 + focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { + @Override + public String outputFile(TableInfo tableInfo) { + return projectPath + "src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper.xml"; + } + }); + cfg.setFileOutConfigList(focList); + generator.setCfg(cfg); + + // + // // 关闭默认 xml 生成,调整生成 至 根目录 + TemplateConfig tc = new TemplateConfig(); + tc.setXml(null); + generator.setTemplate(tc); + + // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改, + // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称 +// TemplateConfig tc = new TemplateConfig(); +// tc.setController(""); +// tc.setEntity("..."); +// tc.setMapper("..."); +// tc.setXml("..."); +// tc.setService("..."); +// tc.setServiceImpl("..."); + // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。 +// generator.setTemplate(tc); + + // 执行生成 + generator.execute(); + + } +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/SpringBootMybatisFreemarkerApplication.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/SpringBootMybatisFreemarkerApplication.java new file mode 100644 index 0000000..6a8b59e --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/SpringBootMybatisFreemarkerApplication.java @@ -0,0 +1,48 @@ +package com.dashuai.learning.mybatis.freemarker; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +/** + * Spring boot mybatis freemarker application + * Created in 2020.07.08 + * + * @author Liaozihong + */ +@SpringBootApplication(scanBasePackages = "com.dashuai.learning.mybatis.freemarker") +@MapperScan(basePackages = "com.dashuai.learning.mybatis.freemarker.dao") +public class SpringBootMybatisFreemarkerApplication { + + /** + * The entry point of application. + * + * @param args the input arguments + */ + public static void main(String[] args) { + SpringApplication.run(SpringBootMybatisFreemarkerApplication.class, args); + } + + /** + * 更改springboot 默认的json解析 + * + * @return + */ + @Bean + @Primary + @ConditionalOnMissingBean(ObjectMapper.class) + public ObjectMapper jacksonObjectMapper() { + ObjectMapper objectMapper=new ObjectMapper(); + objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); + return objectMapper; + } + + +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/config/MybatisPlusConfig.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/config/MybatisPlusConfig.java new file mode 100644 index 0000000..2bfe41e --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/config/MybatisPlusConfig.java @@ -0,0 +1,37 @@ +package com.dashuai.learning.mybatis.freemarker.config; + +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; + +/** + * Mybatis plus config + * Created in 2020.07.08 + * + * @author Liaozihong + * @Description mybatisPlus配置类 + */ +@Configuration +public class MybatisPlusConfig { + /** + * 分页插件 + * + * @return the pagination interceptor + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + return new PaginationInterceptor(); + } + + /** + * SQL执行效率插件 + * + * @return the performance interceptor + */ + @Bean + public PerformanceInterceptor performanceInterceptor() { + return new PerformanceInterceptor(); + } +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/controller/WaNewbieActivityListController.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/controller/WaNewbieActivityListController.java new file mode 100644 index 0000000..631b2e4 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/controller/WaNewbieActivityListController.java @@ -0,0 +1,36 @@ +package com.dashuai.learning.mybatis.freemarker.controller; + + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.dashuai.learning.mybatis.freemarker.entity.WaNewbieActivityList; +import com.dashuai.learning.mybatis.freemarker.service.WaNewbieActivityListService; +import com.dashuai.learning.mybatis.freemarker.utils.JSONParseUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.bind.annotation.RequestMapping; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + *

+ * 活动列表 前端控制器 + *

+ * + * @author liaozihong + * @since 2020-07-08 + */ +@RestController +@RequestMapping("/waNewbieActivityList") +public class WaNewbieActivityListController { + @Autowired + WaNewbieActivityListService waNewbieActivityListService; + + @RequestMapping("/getList") + public List getList(){ + List waNewbieActivityListList = waNewbieActivityListService.getBaseMapper().selectList(Wrappers.lambdaQuery()); + return waNewbieActivityListList; + } +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/dao/WaNewbieActivityListDao.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/dao/WaNewbieActivityListDao.java new file mode 100644 index 0000000..dc54a84 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/dao/WaNewbieActivityListDao.java @@ -0,0 +1,16 @@ +package com.dashuai.learning.mybatis.freemarker.dao; + +import com.dashuai.learning.mybatis.freemarker.entity.WaNewbieActivityList; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + *

+ * 活动列表 Mapper 接口 + *

+ * + * @author liaozihong + * @since 2020-07-08 + */ +public interface WaNewbieActivityListDao extends BaseMapper { + +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/entity/WaNewbieActivityList.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/entity/WaNewbieActivityList.java new file mode 100644 index 0000000..2ab3bd3 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/entity/WaNewbieActivityList.java @@ -0,0 +1,87 @@ +package com.dashuai.learning.mybatis.freemarker.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import com.baomidou.mybatisplus.annotation.TableId; + +import java.time.LocalDateTime; +import java.io.Serializable; +import java.util.Date; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +/** + *

+ * 活动列表 + *

+ * + * @author liaozihong + * @since 2020-07-08 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +public class WaNewbieActivityList extends Model { + + private static final long serialVersionUID = -1L; + + /** + * 主键ID + */ + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + + /** + * 标题 + */ + private String title; + + /** + * 内容 + */ + private String content; + + /** + * 活动图片 + */ + private String activityImg; + + /** + * 按钮颜色 + */ + private String buttonColor; + + /** + * 按钮文案 + */ + private String buttonText; + + /** + * 跳转路径类型,0:小程序客服,1:接龙详情,2:微信列表,3:团购编辑页 + */ + private Boolean jumpType; + + /** + * 是否启用,0启用,1不启用 + */ + private Boolean isEnable; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 修改时间 + */ + private Date updateTime; + + + @Override + protected Serializable pkVal() { + return this.id; + } + +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/IntegerListHandler.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/IntegerListHandler.java new file mode 100644 index 0000000..a4861fc --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/IntegerListHandler.java @@ -0,0 +1,53 @@ +package com.dashuai.learning.mybatis.freemarker.handler; + +import com.dashuai.learning.mybatis.freemarker.utils.JSONParseUtils; +import com.google.common.reflect.TypeToken; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + + +//@MappedTypes({Integer.class}) +@MappedJdbcTypes(JdbcType.VARCHAR) +public class IntegerListHandler extends BaseTypeHandler> { + @Override + public void setNonNullParameter(PreparedStatement ps, int columnIndex, List list, JdbcType jdbcType) throws SQLException { + ps.setString(columnIndex, JSONParseUtils.object2JsonString(list)); + } + + @Override + public List getNullableResult(ResultSet resultSet, String columnName) throws SQLException { + String sqlJson = resultSet.getString(columnName); + if (null != sqlJson) { + return JSONParseUtils.json2GenericObject(sqlJson, new TypeToken>() { + }); + } + return null; + } + + @Override + public List getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException { + String sqlJson = resultSet.getString(columnIndex); + if (null != sqlJson) { + return JSONParseUtils.json2GenericObject(sqlJson, new TypeToken>() { + }); + } + return null; + } + + @Override + public List getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException { + String sqlJson = callableStatement.getString(columnIndex); + if (null != sqlJson) { + return JSONParseUtils.json2GenericObject(sqlJson, new TypeToken>() { + }); + } + return null; + } +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/JavaObjectTypeHandler.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/JavaObjectTypeHandler.java new file mode 100644 index 0000000..7e8819d --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/JavaObjectTypeHandler.java @@ -0,0 +1,66 @@ +package com.dashuai.learning.mybatis.freemarker.handler; + +import com.dashuai.learning.mybatis.freemarker.utils.JSONParseUtils; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * @description 用以mysql中json格式的字段,进行转换的自定义转换器,转换为实体类的JSONObject属性 + * MappedTypes注解中的类代表此转换器可以自动转换为的java对象 + * MappedJdbcTypes注解中设置的是对应的jdbctype + **/ +@MappedJdbcTypes(JdbcType.VARCHAR) +public class JavaObjectTypeHandler extends BaseTypeHandler { + + private Class clazz; + + //这个构造器是用来获取类型的,如果是泛型的typehandler必须要写 + public JavaObjectTypeHandler(Class clazz) { + if (clazz == null) { + throw new IllegalArgumentException("Type argument cannot be null"); + } + this.clazz = clazz; + } + + //设置非空参数 + @Override + public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { + ps.setString(i, JSONParseUtils.object2JsonString(parameter)); + } + + //根据列名,获取可以为空的结果 + @Override + public T getNullableResult(ResultSet rs, String columnName) throws SQLException { + String sqlJson = rs.getString(columnName); + if (null != sqlJson) { + return JSONParseUtils.json2Object(sqlJson, clazz); + } + return null; + } + + //根据列索引,获取可以为空的结果 + @Override + public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + String sqlJson = rs.getString(columnIndex); + if (null != sqlJson) { + return JSONParseUtils.json2Object(sqlJson, clazz); + } + return null; + } + + @Override + public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + String sqlJson = cs.getString(columnIndex); + if (null != sqlJson) { + return JSONParseUtils.json2Object(sqlJson, clazz); + } + return null; + } +} + diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/ListJsonHandler.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/ListJsonHandler.java new file mode 100644 index 0000000..8c65d70 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/handler/ListJsonHandler.java @@ -0,0 +1,52 @@ +package com.dashuai.learning.mybatis.freemarker.handler; + +import com.dashuai.learning.mybatis.freemarker.utils.JSONParseUtils; +import com.google.common.reflect.TypeToken; +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; +import org.apache.ibatis.type.MappedJdbcTypes; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; + +//@MappedTypes({JSONObject.class}) +@MappedJdbcTypes(JdbcType.VARCHAR) +public class ListJsonHandler extends BaseTypeHandler> { + @Override + public void setNonNullParameter(PreparedStatement ps, int columnIndex, List list, JdbcType jdbcType) throws SQLException { + ps.setString(columnIndex, JSONParseUtils.object2JsonString(list)); + } + + @Override + public List getNullableResult(ResultSet resultSet, String columnName) throws SQLException { + String sqlJson = resultSet.getString(columnName); + if (null != sqlJson) { + return JSONParseUtils.json2GenericObject(sqlJson, new TypeToken() { + }); + } + return null; + } + + @Override + public List getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException { + String sqlJson = resultSet.getString(columnIndex); + if (null != sqlJson) { + return JSONParseUtils.json2GenericObject(sqlJson, new TypeToken() { + }); + } + return null; + } + + @Override + public List getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException { + String sqlJson = callableStatement.getString(columnIndex); + if (null != sqlJson) { + return JSONParseUtils.json2GenericObject(sqlJson, new TypeToken() { + }); + } + return null; + } +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/WaNewbieActivityListService.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/WaNewbieActivityListService.java new file mode 100644 index 0000000..4d5ab7f --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/WaNewbieActivityListService.java @@ -0,0 +1,16 @@ +package com.dashuai.learning.mybatis.freemarker.service; + +import com.dashuai.learning.mybatis.freemarker.entity.WaNewbieActivityList; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + *

+ * 活动列表 服务类 + *

+ * + * @author liaozihong + * @since 2020-07-08 + */ +public interface WaNewbieActivityListService extends IService { + +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/impl/WaNewbieActivityListServiceImpl.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/impl/WaNewbieActivityListServiceImpl.java new file mode 100644 index 0000000..75b4180 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/service/impl/WaNewbieActivityListServiceImpl.java @@ -0,0 +1,20 @@ +package com.dashuai.learning.mybatis.freemarker.service.impl; + +import com.dashuai.learning.mybatis.freemarker.entity.WaNewbieActivityList; +import com.dashuai.learning.mybatis.freemarker.dao.WaNewbieActivityListDao; +import com.dashuai.learning.mybatis.freemarker.service.WaNewbieActivityListService; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.springframework.stereotype.Service; + +/** + *

+ * 活动列表 服务实现类 + *

+ * + * @author liaozihong + * @since 2020-07-08 + */ +@Service +public class WaNewbieActivityListServiceImpl extends ServiceImpl implements WaNewbieActivityListService { + +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/utils/JSONParseUtils.java b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/utils/JSONParseUtils.java new file mode 100644 index 0000000..fb46ecd --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/java/com/dashuai/learning/mybatis/freemarker/utils/JSONParseUtils.java @@ -0,0 +1,58 @@ +package com.dashuai.learning.mybatis.freemarker.utils; + +import com.google.common.base.Strings; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +/** + * Json parse utils + *

+ * Created in 2018.11.08 + *

+ * + * @author Liaodashuai + */ +public class JSONParseUtils { + private static Gson gson = (new GsonBuilder()).setDateFormat("yyyy-MM-dd HH:mm:ss").disableHtmlEscaping().create(); + + /** + * Instantiates a new Json parse utils. + */ + public JSONParseUtils() { + } + + /** + * Object 2 json string string. + * + * @param obj the obj + * @return the string + */ + public static String object2JsonString(Object obj) { + return obj == null ? null : gson.toJson(obj); + } + + /** + * Json 2 object t. + * + * @param the type parameter + * @param jsonString the json string + * @param resultType the result type + * @return the t + */ + public static T json2Object(String jsonString, Class resultType) { + return Strings.isNullOrEmpty(jsonString) ? null : gson.fromJson(jsonString, resultType); + } + + /** + * Json 2 generic object t. + * + * @param the type parameter + * @param jsonString the json string + * @param typeToken the type token + * @return the t + */ + public static T json2GenericObject(String jsonString, TypeToken typeToken) { + return gson.fromJson(jsonString, typeToken.getType()); + } +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/application.yml b/SpringBoot-Mybatis-Freemarker/src/main/resources/application.yml new file mode 100644 index 0000000..053ea1a --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/application.yml @@ -0,0 +1,40 @@ +spring: + datasource: + druid: + url: jdbc:mysql://127.0.0.1:3306/fantan?useAffectedRows=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai + username: root + password: 'root' + # 配置初始化大小、最小、最大 + max-active: 10 + initial-size: 2 + min-idle: 2 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + time-between-eviction-runs-millis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: SELECT 'x' + test-while-idle: true + test-on-borrow: false + test-on-return: false + max-open-prepared-statements: 20 + remove-abandoned: true + remove-abandoned-timeout: 1800 + log-abandoned: true + filter: + stat: + log-slow-sql: true + slow-sql-millis: 100 + filters: stat,wall,slf4j + web-stat-filter: + enabled: true + url-pattern: '/*' + exclusions: '/druid/*' + stat-view-servlet: + login-username: admin + login-password: 123456 + enabled: true + +mybatis-plus: + type-aliases-package: com.dashuai.learning.mybatis.freemarker.entity + config-location: classpath:mybatis/mybatis-config.xml + mapper-locations: classpath*:mappers/*.xml diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/mappers/WaNewbieActivityListMapper.xml b/SpringBoot-Mybatis-Freemarker/src/main/resources/mappers/WaNewbieActivityListMapper.xml new file mode 100644 index 0000000..2857d52 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/mappers/WaNewbieActivityListMapper.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + id, title, content, activity_img, button_color, button_text, jump_type, is_enable, create_time, update_time + + + diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/mybatis/mybatis-config.xml b/SpringBoot-Mybatis-Freemarker/src/main/resources/mybatis/mybatis-config.xml new file mode 100644 index 0000000..facc7d4 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/mybatis/mybatis-config.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/controller.java.ftl b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/controller.java.ftl new file mode 100644 index 0000000..69a9f81 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/controller.java.ftl @@ -0,0 +1,39 @@ +package ${package.Controller}; + + +import org.springframework.web.bind.annotation.RequestMapping; + +<#if restControllerStyle> +import org.springframework.web.bind.annotation.RestController; +<#else> +import org.springframework.stereotype.Controller; + +<#if superControllerClassPackage??> +import ${superControllerClassPackage}; + + +/** + *

+ * ${table.comment!} 前端控制器 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if restControllerStyle> +@RestController +<#else> +@Controller + +@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") +<#if kotlin> +class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}() +<#else> +<#if superControllerClass??> +public class ${table.controllerName} extends ${superControllerClass} { +<#else> +public class ${table.controllerName} { + + +} + diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/entity.java.ftl b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/entity.java.ftl new file mode 100644 index 0000000..e399243 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/entity.java.ftl @@ -0,0 +1,152 @@ +package ${package.Entity}; + +<#list table.importPackages as pkg> + import ${pkg}; + +<#if swagger2> + import io.swagger.annotations.ApiModel; + import io.swagger.annotations.ApiModelProperty; + +<#if entityLombokModel> + import lombok.Data; + import lombok.EqualsAndHashCode; + import lombok.experimental.Accessors; + + +/** +*

+ * ${table.comment!} + *

+* +* @author ${author} +* @since ${date} +*/ +<#if entityLombokModel> + @Data + <#if superEntityClass??> + @EqualsAndHashCode(callSuper = true) + <#else> + @EqualsAndHashCode(callSuper = false) + + @Accessors(chain = true) + +<#if table.convert> + @TableName("${table.name}") + +<#if swagger2> + @ApiModel(value="${entity}对象", description="${table.comment!}") + +<#if superEntityClass??> + public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { +<#elseif activeRecord> + public class ${entity} extends Model<${entity}> { +<#else> + public class ${entity} implements Serializable { + + +<#if entitySerialVersionUID> + private static final long serialVersionUID = 1L; + +<#-- ---------- BEGIN 字段循环遍历 ----------> +<#list table.fields as field> + <#if field.keyFlag> + <#assign keyPropertyName="${field.propertyName}"/> + + + <#if field.comment!?length gt 0> + <#if swagger2> + @ApiModelProperty(value = "${field.comment}") + <#else> + /** + * ${field.comment} + */ + + + <#if field.keyFlag> + <#-- 主键 --> + <#if field.keyIdentityFlag> + @TableId(value = "${field.name}", type = IdType.AUTO) + <#elseif idType??> + @TableId(value = "${field.name}", type = IdType.${idType}) + <#elseif field.convert> + @TableId("${field.name}") + + <#-- 普通字段 --> + <#elseif field.fill??> + <#-- ----- 存在字段填充设置 -----> + <#if field.convert> + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) + <#else> + @TableField(fill = FieldFill.${field.fill}) + + <#elseif field.convert> + @TableField("${field.name}") + +<#-- 乐观锁注解 --> + <#if (versionFieldName!"") == field.name> + @Version + +<#-- 逻辑删除注解 --> + <#if (logicDeleteFieldName!"") == field.name> + @TableLogic + + private ${field.propertyType} ${field.propertyName}; + +<#------------ END 字段循环遍历 ----------> + +<#if !entityLombokModel> + <#list table.fields as field> + <#if field.propertyType == "boolean"> + <#assign getprefix="is"/> + <#else> + <#assign getprefix="get"/> + + public ${field.propertyType} ${getprefix}${field.capitalName}() { + return ${field.propertyName}; + } + + <#if entityBuilderModel> + public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + <#else> + public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + + this.${field.propertyName} = ${field.propertyName}; + <#if entityBuilderModel> + return this; + + } + + + +<#if entityColumnConstant> + <#list table.fields as field> + public static final String ${field.name?upper_case} = "${field.name}"; + + + +<#if activeRecord> + @Override + protected Serializable pkVal() { + <#if keyPropertyName??> + return this.${keyPropertyName}; + <#else> + return null; + + } + + +<#if !entityLombokModel> + @Override + public String toString() { + return "${entity}{" + + <#list table.fields as field> + <#if field_index==0> + "${field.propertyName}=" + ${field.propertyName} + + <#else> + ", ${field.propertyName}=" + ${field.propertyName} + + + + "}"; + } + +} diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.java.ftl b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.java.ftl new file mode 100644 index 0000000..53da4ae --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.java.ftl @@ -0,0 +1,20 @@ +package ${package.Mapper}; + +import ${package.Entity}.${entity}; +import ${superMapperClassPackage}; + +/** + *

+ * ${table.comment!} Mapper 接口 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if kotlin> +interface ${table.mapperName} : ${superMapperClass}<${entity}> +<#else> +public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { + +} + diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.xml.ftl b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.xml.ftl new file mode 100644 index 0000000..d9ca71c --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/mapper.xml.ftl @@ -0,0 +1,39 @@ + + + + +<#if enableCache> + + + + +<#if baseResultMap> + + +<#list table.fields as field> +<#if field.keyFlag><#--生成主键排在第一位--> + + + +<#list table.commonFields as field><#--生成公共字段 --> + + +<#list table.fields as field> +<#if !field.keyFlag><#--生成普通字段 --> + + + + + + +<#if baseColumnList> + + +<#list table.commonFields as field> + ${field.name}, + + ${table.fieldNames} + + + + diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/service.java.ftl b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/service.java.ftl new file mode 100644 index 0000000..e3232f3 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/service.java.ftl @@ -0,0 +1,20 @@ +package ${package.Service}; + +import ${package.Entity}.${entity}; +import ${superServiceClassPackage}; + +/** + *

+ * ${table.comment!} 服务类 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if kotlin> +interface ${table.serviceName} : ${superServiceClass}<${entity}> +<#else> +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { + +} + diff --git a/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/serviceImpl.java.ftl b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/serviceImpl.java.ftl new file mode 100644 index 0000000..aeebd14 --- /dev/null +++ b/SpringBoot-Mybatis-Freemarker/src/main/resources/templates/serviceImpl.java.ftl @@ -0,0 +1,26 @@ +package ${package.ServiceImpl}; + +import ${package.Entity}.${entity}; +import ${package.Mapper}.${table.mapperName}; +import ${package.Service}.${table.serviceName}; +import ${superServiceImplClassPackage}; +import org.springframework.stereotype.Service; + +/** + *

+ * ${table.comment!} 服务实现类 + *

+ * + * @author ${author} + * @since ${date} + */ +@Service +<#if kotlin> +open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { + +} +<#else> +public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { + +} + diff --git a/SpringBoot-Rocketmq/README.md b/SpringBoot-Rocketmq/README.md index e20dae0..1bff0ea 100644 --- a/SpringBoot-Rocketmq/README.md +++ b/SpringBoot-Rocketmq/README.md @@ -1,3 +1,9 @@ ### SpringBoot 集成 RocketMq +注意,客户端rocketmq版本要和服务端一致,才能创建topic成功 + + +参考链接: +https://jianshu.com/p/c85237034e50 +[rocketmq 发送时异常:system busy 和 broker busy 解决方案](https://www.cnblogs.com/enenen/p/10138511.html) \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 0b89da4..3548285 100644 --- a/settings.gradle +++ b/settings.gradle @@ -8,7 +8,7 @@ rootProject.name = 'springboot' //include(':SpringBoot-Mybatis-Mycat') //include(':SpringBoot-Mybatis-Ehcache') //include(':SpringBoot-Mybatis-Multisource') -include(':SpringBoot-Mysql-Master-Slave') +//include(':SpringBoot-Mysql-Master-Slave') //include(':SpringBoot-ActiveMq') //include(':SpringBoot-Nsq-Consumer') //include(':SpringBoot-Nsq-Producer') @@ -24,7 +24,7 @@ include(':SpringBoot-Mysql-Master-Slave') //include(':SpringBoot-WebSocket') //include(':SpringBoot-Email') //include(':SpringBoot-Redis-Distributed-Redlock') -include(':SpringBoot-JWT') +//include(':SpringBoot-JWT') //include(':SpringBoot-JTA-Atomikos') //include(':SpringBoot-Kafka') //include(':SpringBoot-Validator') @@ -43,6 +43,7 @@ include(':SpringBoot-JWT') //include(':SpringBoot-Builder-Docker') //include(':SpringBoot-Test-Starter') //include(':SpringBoot-Alibaba-Sentinel') +include(':SpringBoot-Mybatis-Freemarker') include(':SpringBoot-Support') // spring-boot-starter-webflux模块与web冲突,如果web模块的类不能用,请注释下面的模块 //include(':SpringBoot-WebFlux') From 82a1dd2e57116282e7dc0df11e229a3450351c82 Mon Sep 17 00:00:00 2001 From: liaozihong Date: Mon, 3 Aug 2020 17:41:26 +0800 Subject: [PATCH 10/14] =?UTF-8?q?fix:support=E6=97=A0=E6=B3=95=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E5=BC=95=E7=94=A8=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dashuai/learnin/elasticsearchadvance/api/FilmApi.java | 1 + .../elasticsearchadvance/config/EsConfiguration.java | 6 +++--- .../learning/elasticsearch/api/UserOperationApi.java | 1 + .../learning/elasticsearch/config/SpringConfiguration.java | 4 ++-- SpringBoot-Rocketmq/build.gradle | 2 +- .../src/main/resources/application.properties | 4 +++- SpringBoot-Support/build.gradle | 7 +++++++ 7 files changed, 18 insertions(+), 7 deletions(-) diff --git a/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/api/FilmApi.java b/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/api/FilmApi.java index 46cd9c1..f9f1c5e 100644 --- a/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/api/FilmApi.java +++ b/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/api/FilmApi.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; /** * Film api diff --git a/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/config/EsConfiguration.java b/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/config/EsConfiguration.java index 9922687..626da45 100644 --- a/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/config/EsConfiguration.java +++ b/SpringBoot-Elasticsearch-Query/src/main/java/com/dashuai/learnin/elasticsearchadvance/config/EsConfiguration.java @@ -4,7 +4,7 @@ import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.transport.InetSocketTransportAddress; +import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -44,9 +44,9 @@ public Client transportClient() { .put("cluster.name", "docker-cluster") .put("xpack.security.user", "elastic:changeme") .build()) - .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("120.79.58.138"), 9300)); + .addTransportAddress(new TransportAddress(InetAddress.getByName("120.79.58.138"), 9300)); } catch (UnknownHostException e) { - log.error("elasticsearch 连接失败 !"); +// log.error("elasticsearch 连接失败 !"); } return client; } diff --git a/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/api/UserOperationApi.java b/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/api/UserOperationApi.java index a67ac1c..9a10cc5 100644 --- a/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/api/UserOperationApi.java +++ b/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/api/UserOperationApi.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; /** * User operation api diff --git a/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/config/SpringConfiguration.java b/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/config/SpringConfiguration.java index 4102f63..d20ccfd 100644 --- a/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/config/SpringConfiguration.java +++ b/SpringBoot-Elasticsearch/src/main/java/com/dashuai/learning/elasticsearch/config/SpringConfiguration.java @@ -2,7 +2,7 @@ import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.transport.InetSocketTransportAddress; +import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -33,7 +33,7 @@ public TransportClient transportClient() throws UnknownHostException { .put("cluster.name", "docker-cluster") .put("xpack.security.user", "elastic:changeme") .build()) - .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("120.79.58.138"), 9300)); + .addTransportAddress(new TransportAddress(InetAddress.getByName("120.79.58.138"), 9300)); return client; } } diff --git a/SpringBoot-Rocketmq/build.gradle b/SpringBoot-Rocketmq/build.gradle index a3e24a2..f36080d 100644 --- a/SpringBoot-Rocketmq/build.gradle +++ b/SpringBoot-Rocketmq/build.gradle @@ -1,6 +1,6 @@ dependencies { compile project(':SpringBoot-Support') - compile 'org.apache.rocketmq:rocketmq-client:4.3.0' + compile 'org.apache.rocketmq:rocketmq-client:4.7.1' compile 'com.alibaba:fastjson:1.2.47' testCompile('org.springframework.boot:spring-boot-starter-test') } diff --git a/SpringBoot-Rocketmq/src/main/resources/application.properties b/SpringBoot-Rocketmq/src/main/resources/application.properties index a23dd76..714d058 100644 --- a/SpringBoot-Rocketmq/src/main/resources/application.properties +++ b/SpringBoot-Rocketmq/src/main/resources/application.properties @@ -1,4 +1,6 @@ apache.rocketmq.consumer.pushConsumer=testConsumer #生产者的配置 apache.rocketmq.producer.producerGroup=testProducer -apache.rocketmq.namesrvAddr=192.168.2.7:9876 \ No newline at end of file +apache.rocketmq.namesrvAddr=192.168.11.41:9876 + +server.port=8088 \ No newline at end of file diff --git a/SpringBoot-Support/build.gradle b/SpringBoot-Support/build.gradle index 5a70d06..0faccd2 100644 --- a/SpringBoot-Support/build.gradle +++ b/SpringBoot-Support/build.gradle @@ -1,3 +1,10 @@ +bootJar { + enabled = false +} + +jar { + enabled = true +} dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0' From fb41583ad8e478415e60b0fbca466a15d681e7ce Mon Sep 17 00:00:00 2001 From: liaozihong Date: Wed, 19 Aug 2020 11:11:01 +0800 Subject: [PATCH 11/14] =?UTF-8?q?feat:=E6=96=B0=E5=A2=9EGecco=E7=88=AC?= =?UTF-8?q?=E8=99=AB=E6=A1=86=E6=9E=B6=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Gecco-Reptile/.gitignore | 34 ++++++++ SpringBoot-Gecco-Reptile/README.md | 3 + SpringBoot-Gecco-Reptile/build.gradle | 4 + .../learning/reptile/FinishGitHubEntity.java | 20 +++++ .../dashuai/learning/reptile/MyGitHub.java | 79 +++++++++++++++++++ .../learning/reptile/ReptileApplication.java | 13 +++ .../src/main/resources/application.properties | 1 + .../annotation/RateLimiterAnnotation.java | 12 ++- .../service/RateLimiterService.java | 6 +- .../service/impl/AopTestServiceImpl.java | 5 +- settings.gradle | 3 +- 11 files changed, 170 insertions(+), 10 deletions(-) create mode 100644 SpringBoot-Gecco-Reptile/.gitignore create mode 100644 SpringBoot-Gecco-Reptile/README.md create mode 100644 SpringBoot-Gecco-Reptile/build.gradle create mode 100644 SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/FinishGitHubEntity.java create mode 100644 SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/MyGitHub.java create mode 100644 SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/ReptileApplication.java create mode 100644 SpringBoot-Gecco-Reptile/src/main/resources/application.properties diff --git a/SpringBoot-Gecco-Reptile/.gitignore b/SpringBoot-Gecco-Reptile/.gitignore new file mode 100644 index 0000000..84695dc --- /dev/null +++ b/SpringBoot-Gecco-Reptile/.gitignore @@ -0,0 +1,34 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/SpringBoot-Gecco-Reptile/README.md b/SpringBoot-Gecco-Reptile/README.md new file mode 100644 index 0000000..0ad8562 --- /dev/null +++ b/SpringBoot-Gecco-Reptile/README.md @@ -0,0 +1,3 @@ +### 接入爬虫框架 + +Gecco 简单实例 \ No newline at end of file diff --git a/SpringBoot-Gecco-Reptile/build.gradle b/SpringBoot-Gecco-Reptile/build.gradle new file mode 100644 index 0000000..7129eae --- /dev/null +++ b/SpringBoot-Gecco-Reptile/build.gradle @@ -0,0 +1,4 @@ +dependencies { + compile project(':SpringBoot-Support') + compile 'com.geccocrawler:gecco:1.3.2' +} diff --git a/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/FinishGitHubEntity.java b/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/FinishGitHubEntity.java new file mode 100644 index 0000000..f7132eb --- /dev/null +++ b/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/FinishGitHubEntity.java @@ -0,0 +1,20 @@ +package com.dashuai.learning.reptile; + + +import com.dashuai.learning.utils.json.JSONParseUtils; +import com.geccocrawler.gecco.annotation.PipelineName; +import com.geccocrawler.gecco.pipeline.Pipeline; + +/** + * Finish git hub entity + * Created in 2020.08.14 + * + * @author Liaozihong + */ +@PipelineName("finishPipeline") +public class FinishGitHubEntity implements Pipeline { + @Override + public void process(MyGitHub bean) { + System.out.println("结果如下:" + JSONParseUtils.object2JsonString(bean)); + } +} diff --git a/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/MyGitHub.java b/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/MyGitHub.java new file mode 100644 index 0000000..61092a3 --- /dev/null +++ b/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/MyGitHub.java @@ -0,0 +1,79 @@ +package com.dashuai.learning.reptile; + +import com.geccocrawler.gecco.GeccoEngine; +import com.geccocrawler.gecco.annotation.*; +import com.geccocrawler.gecco.spider.HtmlBean; + +@Gecco(matchUrl = "https://github.com/{user}/{project}", pipelines = "finishPipeline") +public class MyGitHub implements HtmlBean { + + private static final long serialVersionUID = -7127412585200687225L; + + @RequestParameter("user") + private String user; + + @RequestParameter("project") + private String project; + + @Text + @HtmlField(cssPath = ".pagehead-actions li:nth-child(2) .social-count") + private String star; + + @Text + @HtmlField(cssPath = ".pagehead-actions li:nth-child(3) .social-count") + private String fork; + + @Html + @HtmlField(cssPath = ".entry-content") + private String readme; + + public String getReadme() { + return readme; + } + + public void setReadme(String readme) { + this.readme = readme; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getProject() { + return project; + } + + public void setProject(String project) { + this.project = project; + } + + public String getStar() { + return star; + } + + public void setStar(String star) { + this.star = star; + } + + public String getFork() { + return fork; + } + + public void setFork(String fork) { + this.fork = fork; + } + + public static void main(String[] args) { + GeccoEngine.create() + .classpath("com.dashuai.learning.reptile") + .start("https://github.com/liaozihong/SpringBoot-Learning") + .thread(1) + .interval(2000) + .loop(false) + .mobile(false).run(); + } +} \ No newline at end of file diff --git a/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/ReptileApplication.java b/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/ReptileApplication.java new file mode 100644 index 0000000..7a6a5c7 --- /dev/null +++ b/SpringBoot-Gecco-Reptile/src/main/java/com/dashuai/learning/reptile/ReptileApplication.java @@ -0,0 +1,13 @@ +package com.dashuai.learning.reptile; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ReptileApplication { + + public static void main(String[] args) { + SpringApplication.run(ReptileApplication.class, args); + } + +} diff --git a/SpringBoot-Gecco-Reptile/src/main/resources/application.properties b/SpringBoot-Gecco-Reptile/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/SpringBoot-Gecco-Reptile/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java index b8e2df0..9789bcb 100644 --- a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java +++ b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/annotation/RateLimiterAnnotation.java @@ -5,20 +5,26 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Rate limiter annotation + * Created in 2020.08.06 + * + * @author Liaozihong + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RateLimiterAnnotation { /** * 限流服务名 * - * @return + * @return string */ String name() default ""; /** * 每秒限流次数 * - * @return + * @return double */ - double count() default 1000; + int count() default 500; } diff --git a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/RateLimiterService.java b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/RateLimiterService.java index 12d59be..fa1c81c 100644 --- a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/RateLimiterService.java +++ b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/RateLimiterService.java @@ -1,7 +1,6 @@ package com.dashuai.learning.ratelimiter.service; import com.google.common.util.concurrent.RateLimiter; -import org.springframework.stereotype.Service; /** * Rate limiter service @@ -11,13 +10,12 @@ * * @author Liaozihong */ -@Service public class RateLimiterService { private RateLimiter rateLimiter; - public RateLimiterService(double count) { - rateLimiter = RateLimiter.create(count); + public RateLimiterService(Integer count) { + rateLimiter = RateLimiter.create(Double.valueOf(count)); } /** diff --git a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/impl/AopTestServiceImpl.java b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/impl/AopTestServiceImpl.java index d5f545c..1452c26 100644 --- a/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/impl/AopTestServiceImpl.java +++ b/SpringBoot-RateLimiter/src/main/java/com/dashuai/learning/ratelimiter/service/impl/AopTestServiceImpl.java @@ -14,15 +14,16 @@ */ @Service public class AopTestServiceImpl implements AopTestService { + @Override - @RateLimiterAnnotation(name = "v1", count = 5.0) + @RateLimiterAnnotation(name = "v1", count = 5) public String testRateLimiter(Double count, String context) { System.out.println(count + " " + context); return "测试"; } @Override - @RateLimiterAnnotation(name = "v2", count = 7.0) + @RateLimiterAnnotation(name = "v2", count = 7) public String testRateLimiterv2(Double count, String context) { System.out.println("V2版本发出:" + count + " " + context); return "测试第二个"; diff --git a/settings.gradle b/settings.gradle index 3548285..356ba5a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -43,7 +43,8 @@ rootProject.name = 'springboot' //include(':SpringBoot-Builder-Docker') //include(':SpringBoot-Test-Starter') //include(':SpringBoot-Alibaba-Sentinel') -include(':SpringBoot-Mybatis-Freemarker') +//include(':SpringBoot-Mybatis-Freemarker') +include(':SpringBoot-Gecco-Reptile') include(':SpringBoot-Support') // spring-boot-starter-webflux模块与web冲突,如果web模块的类不能用,请注释下面的模块 //include(':SpringBoot-WebFlux') From 2d3d712c64ef520849955c9307f1ad08b4b32ae7 Mon Sep 17 00:00:00 2001 From: liaozihong Date: Mon, 30 Aug 2021 17:22:43 +0800 Subject: [PATCH 12/14] =?UTF-8?q?kafka=E6=A8=A1=E5=9D=97=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Kafka/build.gradle | 2 +- .../learning/kafka/KafkaApplication.java | 18 +++++++--- .../dashuai/learning/kafka/model/Message.java | 36 ++----------------- .../learning/kafka/queue/ConsumerMsg.java | 9 ++--- .../learning/kafka/queue/ProductMsg.java | 13 ++++--- .../src/main/resources/application.properties | 2 +- 6 files changed, 31 insertions(+), 49 deletions(-) diff --git a/SpringBoot-Kafka/build.gradle b/SpringBoot-Kafka/build.gradle index b5760b2..d5b6956 100644 --- a/SpringBoot-Kafka/build.gradle +++ b/SpringBoot-Kafka/build.gradle @@ -1,5 +1,5 @@ dependencies { compile project(':SpringBoot-Support') - compile 'org.springframework.kafka:spring-kafka:2.1.5.RELEASE' + compile 'org.springframework.kafka:spring-kafka:2.2.8.RELEASE' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE' } diff --git a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/KafkaApplication.java b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/KafkaApplication.java index 485ec24..7cf3a1d 100644 --- a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/KafkaApplication.java +++ b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/KafkaApplication.java @@ -5,6 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + /** * Kafka application *

@@ -24,11 +27,16 @@ public class KafkaApplication { */ public static void main(String[] args) throws InterruptedException { ApplicationContext app = SpringApplication.run(KafkaApplication.class, args); - while (true) { - ProductMsg sender = app.getBean(ProductMsg.class); - sender.sendMessage(); -// sender.sendMessage2(); - Thread.sleep(200); + Executor executor = Executors.newFixedThreadPool(100); + for (int i = 0; i < 100000; i++) { + executor.execute(()->{ + ProductMsg sender = app.getBean(ProductMsg.class); + try { + sender.sendMessage(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); } } diff --git a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/model/Message.java b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/model/Message.java index ad3ae90..85d692c 100644 --- a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/model/Message.java +++ b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/model/Message.java @@ -11,60 +11,30 @@ * @author Liaozihong */ public class Message { - private Long id; + private Integer id; private String msg; private Date sendTime; - /** - * Gets id. - * - * @return the id - */ - public Long getId() { + public Integer getId() { return id; } - /** - * Sets id. - * - * @param id the id - */ - public void setId(Long id) { + public void setId(Integer id) { this.id = id; } - /** - * Gets msg. - * - * @return the msg - */ public String getMsg() { return msg; } - /** - * Sets msg. - * - * @param msg the msg - */ public void setMsg(String msg) { this.msg = msg; } - /** - * Gets send time. - * - * @return the send time - */ public Date getSendTime() { return sendTime; } - /** - * Sets send time. - * - * @param sendTime the send time - */ public void setSendTime(Date sendTime) { this.sendTime = sendTime; } diff --git a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ConsumerMsg.java b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ConsumerMsg.java index 4b9aba6..afe10fb 100644 --- a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ConsumerMsg.java +++ b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ConsumerMsg.java @@ -1,18 +1,19 @@ package com.dashuai.learning.kafka.queue; import com.dashuai.learning.kafka.model.Message; +import com.dashuai.learning.utils.json.JSONParseUtils; import com.google.gson.Gson; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; @Component public class ConsumerMsg { - private Gson gson = new Gson(); - @KafkaListener(topics = {"test"}) +// @KafkaListener(topics = {"test_ch"}) public void processMessage(String content) { - Message m = gson.fromJson(content, Message.class); - System.out.println("test1--消费消息:" + m.getMsg()); + System.out.println(content); + Message m = JSONParseUtils.json2Object(content, Message.class); + System.out.println("test1--消费消息:" + JSONParseUtils.object2JsonString(m)); } // @KafkaListener(topics = {"test2"}) diff --git a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ProductMsg.java b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ProductMsg.java index d00dd3f..c957f85 100644 --- a/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ProductMsg.java +++ b/SpringBoot-Kafka/src/main/java/com/dashuai/learning/kafka/queue/ProductMsg.java @@ -2,6 +2,7 @@ import com.dashuai.learning.kafka.model.Message; +import com.dashuai.learning.utils.json.JSONParseUtils; import com.google.gson.Gson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; @@ -9,23 +10,25 @@ import java.util.Date; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; @Component public class ProductMsg { @Autowired KafkaTemplate kafkaTemplate; - private Gson gson = new Gson(); - + private AtomicInteger atomicInteger = new AtomicInteger(1); public void sendMessage() throws InterruptedException { Message m = new Message(); - m.setId(System.currentTimeMillis()); + m.setId(atomicInteger.getAndIncrement()); m.setMsg(UUID.randomUUID().toString()); m.setSendTime(new Date()); - System.out.println("1生产了" + m.getMsg()); Thread.sleep(1000); - kafkaTemplate.send("test", gson.toJson(m)); + String content = JSONParseUtils.object2JsonString(m); + System.out.println("生产了" + content); + kafkaTemplate.send("test_ch",content); } + // public void sendMessage2() throws InterruptedException { // Message m = new Message(); // m.setId(System.currentTimeMillis()); diff --git a/SpringBoot-Kafka/src/main/resources/application.properties b/SpringBoot-Kafka/src/main/resources/application.properties index 0d0bbba..bad8947 100644 --- a/SpringBoot-Kafka/src/main/resources/application.properties +++ b/SpringBoot-Kafka/src/main/resources/application.properties @@ -1,5 +1,5 @@ #spring.kafka.bootstrap-servers=120.77.39.34:9092 -spring.kafka.bootstrap-servers=127.0.0.1:9092 +spring.kafka.bootstrap-servers=PLAINTEXT://192.168.0.11:6667,PLAINTEXT://192.168.0.12:6667,PLAINTEXT://192.168.0.13:6667,PLAINTEXT://192.168.0.15:6667 # 生产者配置 spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer From 888c3ae4e661a30c3f71f6b99ab102bc2b7f408f Mon Sep 17 00:00:00 2001 From: liaozihong Date: Mon, 30 Aug 2021 17:23:00 +0800 Subject: [PATCH 13/14] =?UTF-8?q?=E5=9F=BA=E7=A1=80=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Mybatis-Multisource/build.gradle | 11 ++++- SpringBoot-Support/build.gradle | 1 + .../learning/utils/BeanMapperUtils.java | 49 +++++++++++++++++++ settings.gradle | 4 +- 4 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 SpringBoot-Support/src/main/java/com/dashuai/learning/utils/BeanMapperUtils.java diff --git a/SpringBoot-Mybatis-Multisource/build.gradle b/SpringBoot-Mybatis-Multisource/build.gradle index 9859c86..49792f0 100644 --- a/SpringBoot-Mybatis-Multisource/build.gradle +++ b/SpringBoot-Mybatis-Multisource/build.gradle @@ -1,7 +1,16 @@ +plugins{ + id "com.arenagod.gradle.MybatisGenerator" version "1.4" +} dependencies { compile project(":SpringBoot-Support") compile group: 'com.alibaba', name: 'druid', version: '1.1.10' compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.46' compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2' + compile group: 'org.mybatis.generator', name: 'mybatis-generator-core', version:'1.3.2' testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.0.4.RELEASE' -} \ No newline at end of file +} + +mybatisGenerator { + verbose = true + configFile = 'D:\\projects\\SpringBoot-Learning\\SpringBoot-Mybatis-Multisource\\src\\main\\resources\\SpringGenerator.xml' +} diff --git a/SpringBoot-Support/build.gradle b/SpringBoot-Support/build.gradle index 0faccd2..ba31358 100644 --- a/SpringBoot-Support/build.gradle +++ b/SpringBoot-Support/build.gradle @@ -8,4 +8,5 @@ jar { dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0' + compile 'ma.glasnost.orika:orika-core:1.5.2' } diff --git a/SpringBoot-Support/src/main/java/com/dashuai/learning/utils/BeanMapperUtils.java b/SpringBoot-Support/src/main/java/com/dashuai/learning/utils/BeanMapperUtils.java new file mode 100644 index 0000000..f123942 --- /dev/null +++ b/SpringBoot-Support/src/main/java/com/dashuai/learning/utils/BeanMapperUtils.java @@ -0,0 +1,49 @@ +package com.dashuai.learning.utils; + + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import ma.glasnost.orika.MapperFactory; +import ma.glasnost.orika.impl.DefaultMapperFactory; + +/** + * Bean mapper utils + *

+ * Created in 2018.09.11 + *

+ * bean映射,相同的Bean映射工具还有Dozer + * + * @author Liaozihong + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BeanMapperUtils { + private static MapperFactory mapperFactory; + + static { + mapperFactory = new DefaultMapperFactory.Builder().build(); + } + + /** + * 转换源对象中对应的属性值到新的Bean对象中(使用Orika的实现方式,性能更优) + * + * @param 泛型 + * @param src 源对象 + * @param targetType 结果对象类型 + * @return 新的结果对象 t + */ + public static T mapperFast(Object src, Class targetType) { + if (null == src) { + return null; + } + return mapperFactory.getMapperFacade().map(src, targetType); + } + + /** + * 提供一个实例容许自定义设置 + * + * @return + */ + public static MapperFactory getMapperFacade() { + return mapperFactory; + } +} diff --git a/settings.gradle b/settings.gradle index 356ba5a..12e3ca9 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,7 +7,7 @@ rootProject.name = 'springboot' //include(':SpringBoot-Mybatis-Plus') //include(':SpringBoot-Mybatis-Mycat') //include(':SpringBoot-Mybatis-Ehcache') -//include(':SpringBoot-Mybatis-Multisource') +include(':SpringBoot-Mybatis-Multisource') //include(':SpringBoot-Mysql-Master-Slave') //include(':SpringBoot-ActiveMq') //include(':SpringBoot-Nsq-Consumer') @@ -44,7 +44,7 @@ rootProject.name = 'springboot' //include(':SpringBoot-Test-Starter') //include(':SpringBoot-Alibaba-Sentinel') //include(':SpringBoot-Mybatis-Freemarker') -include(':SpringBoot-Gecco-Reptile') +//include(':SpringBoot-Gecco-Reptile') include(':SpringBoot-Support') // spring-boot-starter-webflux模块与web冲突,如果web模块的类不能用,请注释下面的模块 //include(':SpringBoot-WebFlux') From 7673177a4050e1e512f19253a3e1a050e9ca8fbd Mon Sep 17 00:00:00 2001 From: liaozihong Date: Wed, 13 Oct 2021 16:33:21 +0800 Subject: [PATCH 14/14] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=9B=86=E6=88=90neo4j?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SpringBoot-Neo4j/.gitignore | 37 ++++++++++++++ SpringBoot-Neo4j/build.gradle | 5 ++ .../learning/neo4j/Neo4jApplication.java | 14 ++++++ .../learning/neo4j/connect/Neo4jConnect.java | 48 +++++++++++++++++++ .../src/main/resources/application.properties | 6 +++ SpringBoot-Support/build.gradle | 1 + settings.gradle | 3 +- 7 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 SpringBoot-Neo4j/.gitignore create mode 100644 SpringBoot-Neo4j/build.gradle create mode 100644 SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/Neo4jApplication.java create mode 100644 SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/connect/Neo4jConnect.java create mode 100644 SpringBoot-Neo4j/src/main/resources/application.properties diff --git a/SpringBoot-Neo4j/.gitignore b/SpringBoot-Neo4j/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/SpringBoot-Neo4j/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/SpringBoot-Neo4j/build.gradle b/SpringBoot-Neo4j/build.gradle new file mode 100644 index 0000000..7b4a287 --- /dev/null +++ b/SpringBoot-Neo4j/build.gradle @@ -0,0 +1,5 @@ +dependencies { + compile project(':SpringBoot-Support') + compile 'org.neo4j.driver:neo4j-java-driver:4.3.4' + compile('org.springframework.boot:spring-boot-starter-data-neo4j') +} diff --git a/SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/Neo4jApplication.java b/SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/Neo4jApplication.java new file mode 100644 index 0000000..5272344 --- /dev/null +++ b/SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/Neo4jApplication.java @@ -0,0 +1,14 @@ +package com.dashuai.learning.neo4j; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; + +@SpringBootApplication +public class Neo4jApplication { + + public static void main(String[] args) { + SpringApplication.run(Neo4jApplication.class, args); + } + +} diff --git a/SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/connect/Neo4jConnect.java b/SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/connect/Neo4jConnect.java new file mode 100644 index 0000000..53fbf73 --- /dev/null +++ b/SpringBoot-Neo4j/src/main/java/com/dashuai/learning/neo4j/connect/Neo4jConnect.java @@ -0,0 +1,48 @@ +package com.dashuai.learning.neo4j.connect; + +import org.neo4j.driver.*; + +import static org.neo4j.driver.Values.parameters; + +public class Neo4jConnect implements AutoCloseable { + private final Driver driver; + + public Neo4jConnect( String uri, String user, String password ) + { + driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) ); + } + + @Override + public void close() throws Exception + { + driver.close(); + } + + public void printGreeting( final String message ) + { + try ( Session session = driver.session() ) + { + String greeting = session.writeTransaction( new TransactionWork() + { + @Override + public String execute( Transaction tx ) + { + Result result = tx.run( "CREATE (a:JAVA) " + + "SET a.message = $message " + + "RETURN a.message + ', from node ' + id(a)", + parameters( "message", message ) ); + return result.single().get( 0 ).asString(); + } + } ); + System.out.println( greeting ); + } + } + + public static void main( String... args ) throws Exception + { + try ( Neo4jConnect greeter = new Neo4jConnect( "bolt://localhost:7687", "neo4j", "123456" ) ) + { + greeter.printGreeting( "hello, world neo4j" ); + } + } +} diff --git a/SpringBoot-Neo4j/src/main/resources/application.properties b/SpringBoot-Neo4j/src/main/resources/application.properties new file mode 100644 index 0000000..d0a4506 --- /dev/null +++ b/SpringBoot-Neo4j/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.data.neo4j.uri=bolt://localhost:7687 +spring.data.neo4j.username=neo4j +spring.data.neo4j.password=123456 +spring.data.neo4j.database=hello +logging.level.org.springframework.data.neo4j=DEBUG +spring.main.allow-bean-definition-overriding=true diff --git a/SpringBoot-Support/build.gradle b/SpringBoot-Support/build.gradle index ba31358..e817a23 100644 --- a/SpringBoot-Support/build.gradle +++ b/SpringBoot-Support/build.gradle @@ -9,4 +9,5 @@ dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0' compile 'ma.glasnost.orika:orika-core:1.5.2' + } diff --git a/settings.gradle b/settings.gradle index 12e3ca9..93658be 100644 --- a/settings.gradle +++ b/settings.gradle @@ -7,7 +7,7 @@ rootProject.name = 'springboot' //include(':SpringBoot-Mybatis-Plus') //include(':SpringBoot-Mybatis-Mycat') //include(':SpringBoot-Mybatis-Ehcache') -include(':SpringBoot-Mybatis-Multisource') +//include(':SpringBoot-Mybatis-Multisource') //include(':SpringBoot-Mysql-Master-Slave') //include(':SpringBoot-ActiveMq') //include(':SpringBoot-Nsq-Consumer') @@ -45,6 +45,7 @@ include(':SpringBoot-Mybatis-Multisource') //include(':SpringBoot-Alibaba-Sentinel') //include(':SpringBoot-Mybatis-Freemarker') //include(':SpringBoot-Gecco-Reptile') +include(':SpringBoot-Neo4j') include(':SpringBoot-Support') // spring-boot-starter-webflux模块与web冲突,如果web模块的类不能用,请注释下面的模块 //include(':SpringBoot-WebFlux')