From d76eb3c8f1137621c0e996c9f1c676559315a0ed Mon Sep 17 00:00:00 2001 From: fujichuan Date: Tue, 23 Jul 2024 14:36:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 44 +++ README.MD | 0 hydrogen-applet/.gitignore | 44 +++ hydrogen-applet/pom.xml | 127 ++++++++ .../hydrogen/HydrogenAppletApplication.java | 15 + .../java/com/hydrogen/ServletInitializer.java | 13 + .../applet/config/FeignConfiguration.java | 18 ++ .../applet/config/FeignOkHttpConfig.java | 39 +++ .../applet/config/MyBatisPlusConfig.java | 27 ++ .../applet/config/MybatisGenerator.java | 145 +++++++++ .../hydrogen/applet/config/SwaggerConfig.java | 40 +++ .../filter/AuthenticationInterceptor.java | 85 +++++ .../GlobalParameterValidationHandler.java | 38 +++ .../filter/InteceptorChainConfigFilter.java | 59 ++++ .../src/main/resources/application-dev.yml | 45 +++ .../src/main/resources/application-prod.yml | 43 +++ .../src/main/resources/application.yml | 71 +++++ .../src/main/resources/logback-spring.xml | 54 ++++ hydrogen-brand-manager/.gitignore | 44 +++ hydrogen-brand-manager/pom.xml | 127 ++++++++ .../HydrogenBrandManagerApplication.java | 15 + .../java/com/hydrogen/ServletInitializer.java | 13 + .../config/FeignConfiguration.java | 18 ++ .../config/FeignOkHttpConfig.java | 39 +++ .../config/MyBatisPlusConfig.java | 27 ++ .../brandManager/config/MybatisGenerator.java | 145 +++++++++ .../brandManager/config/SwaggerConfig.java | 40 +++ .../filter/AuthenticationInterceptor.java | 78 +++++ .../GlobalParameterValidationHandler.java | 38 +++ .../filter/InteceptorChainConfigFilter.java | 59 ++++ .../src/main/resources/application-prod.yml | 109 +++++++ .../src/main/resources/application.yml | 111 +++++++ .../src/main/resources/logback-spring.xml | 54 ++++ hydrogen-mbg/.gitignore | 44 +++ hydrogen-mbg/pom.xml | 20 ++ .../java/com/hydrogen/mbg/bean/PageBean.java | 61 ++++ .../com/hydrogen/mbg/dto/BaseListDTO.java | 51 +++ .../com/hydrogen/mbg/utils/JwtTokenUtil.java | 111 +++++++ .../com/hydrogen/mbg/utils/RedisUtil.java | 111 +++++++ .../java/com/hydrogen/mbg/vo/DrhtResult.java | 162 ++++++++++ .../main/java/com/hydrogen/mbg/vo/ListVO.java | 63 ++++ pom.xml | 294 ++++++++++++++++++ 42 files changed, 2741 insertions(+) create mode 100644 .gitignore create mode 100644 README.MD create mode 100644 hydrogen-applet/.gitignore create mode 100644 hydrogen-applet/pom.xml create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/HydrogenAppletApplication.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/ServletInitializer.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignConfiguration.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignOkHttpConfig.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/config/MyBatisPlusConfig.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/config/MybatisGenerator.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/config/SwaggerConfig.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/filter/AuthenticationInterceptor.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/filter/GlobalParameterValidationHandler.java create mode 100644 hydrogen-applet/src/main/java/com/hydrogen/applet/filter/InteceptorChainConfigFilter.java create mode 100644 hydrogen-applet/src/main/resources/application-dev.yml create mode 100644 hydrogen-applet/src/main/resources/application-prod.yml create mode 100644 hydrogen-applet/src/main/resources/application.yml create mode 100644 hydrogen-applet/src/main/resources/logback-spring.xml create mode 100644 hydrogen-brand-manager/.gitignore create mode 100644 hydrogen-brand-manager/pom.xml create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/HydrogenBrandManagerApplication.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/ServletInitializer.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignConfiguration.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignOkHttpConfig.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MyBatisPlusConfig.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MybatisGenerator.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/SwaggerConfig.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/AuthenticationInterceptor.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/GlobalParameterValidationHandler.java create mode 100644 hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/InteceptorChainConfigFilter.java create mode 100644 hydrogen-brand-manager/src/main/resources/application-prod.yml create mode 100644 hydrogen-brand-manager/src/main/resources/application.yml create mode 100644 hydrogen-brand-manager/src/main/resources/logback-spring.xml create mode 100644 hydrogen-mbg/.gitignore create mode 100644 hydrogen-mbg/pom.xml create mode 100644 hydrogen-mbg/src/main/java/com/hydrogen/mbg/bean/PageBean.java create mode 100644 hydrogen-mbg/src/main/java/com/hydrogen/mbg/dto/BaseListDTO.java create mode 100644 hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/JwtTokenUtil.java create mode 100644 hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/RedisUtil.java create mode 100644 hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/DrhtResult.java create mode 100644 hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/ListVO.java create mode 100644 pom.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1ea203b --- /dev/null +++ b/.gitignore @@ -0,0 +1,44 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/misc.xml +.idea/libraries/ +.idea/misc.xml/ +.idea/vcs.xml/ +.idea/uiDesigner.xml/ +*.iws +*.iml +*.ipr +.idea/dataSources.xml +.idea/mybatisx/templates.xml + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..e69de29 diff --git a/hydrogen-applet/.gitignore b/hydrogen-applet/.gitignore new file mode 100644 index 0000000..1ea203b --- /dev/null +++ b/hydrogen-applet/.gitignore @@ -0,0 +1,44 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/misc.xml +.idea/libraries/ +.idea/misc.xml/ +.idea/vcs.xml/ +.idea/uiDesigner.xml/ +*.iws +*.iml +*.ipr +.idea/dataSources.xml +.idea/mybatisx/templates.xml + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/hydrogen-applet/pom.xml b/hydrogen-applet/pom.xml new file mode 100644 index 0000000..9f5f3c0 --- /dev/null +++ b/hydrogen-applet/pom.xml @@ -0,0 +1,127 @@ + + + 4.0.0 + + com.hydrogen + hydrogen + 1.0-SNAPSHOT + + com.hydrogen + hydrogen-applet + 0.0.1-SNAPSHOT + hydrogen-applet + 吸氢机小程序 + war + + + 8 + 8 + UTF-8 + + + + + mysql + mysql-connector-java + + + + com.alibaba + druid-spring-boot-starter + + + + com.baomidou + mybatis-plus-boot-starter + + + + com.baomidou + mybatis-plus-generator + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + com.hydrogen + hydrogen-mbg + 1.0-SNAPSHOT + + + + + nexus + Nexus Repository + http://nexus.derunht.cn/repository/maven-public/ + + true + + + true + + + + + + + nexus + Nexus Plugin Repository + http://nexus.derunht.cn/repository/maven-public/ + + true + + + true + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.2.RELEASE + + + com.hydrogen.examSystem.ExamSystemApplication + + + + + repackage + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.2.3 + + false + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 8 + 8 + + + + + + \ No newline at end of file diff --git a/hydrogen-applet/src/main/java/com/hydrogen/HydrogenAppletApplication.java b/hydrogen-applet/src/main/java/com/hydrogen/HydrogenAppletApplication.java new file mode 100644 index 0000000..7684e5a --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/HydrogenAppletApplication.java @@ -0,0 +1,15 @@ +package com.hydrogen; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@MapperScan(basePackages ="com.hydrogen.applet.dao") +@EnableAsync +@SpringBootApplication +public class HydrogenAppletApplication { + public static void main(String[] args) { + SpringApplication.run(HydrogenAppletApplication.class, args); + } +} diff --git a/hydrogen-applet/src/main/java/com/hydrogen/ServletInitializer.java b/hydrogen-applet/src/main/java/com/hydrogen/ServletInitializer.java new file mode 100644 index 0000000..080c221 --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/ServletInitializer.java @@ -0,0 +1,13 @@ +package com.hydrogen; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +public class ServletInitializer extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(HydrogenAppletApplication.class); + } + +} \ No newline at end of file diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignConfiguration.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignConfiguration.java new file mode 100644 index 0000000..5f8034c --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignConfiguration.java @@ -0,0 +1,18 @@ +package com.hydrogen.applet.config; + +import feign.Logger; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Feign 客户端日志配置 + */ +@Configuration +public class FeignConfiguration { + + @Bean + Logger.Level feignLevel() { + return Logger.Level.BASIC; + } + +} \ No newline at end of file diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignOkHttpConfig.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignOkHttpConfig.java new file mode 100644 index 0000000..b9e2f5b --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/FeignOkHttpConfig.java @@ -0,0 +1,39 @@ +package com.hydrogen.applet.config; + +import feign.Feign; +import okhttp3.ConnectionPool; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.TimeUnit; + +/** + * @ClassName OpenFeignInterfaceConfiguration + * @Description OpenFeignConfig 配置管理 + * @Author chaixueteng + * @Date 2020/3/10 9:46 + */ +@Configuration +@ConditionalOnClass(Feign.class) +@AutoConfigureBefore(FeignAutoConfiguration.class) +public class FeignOkHttpConfig { + + + @Bean + public okhttp3.OkHttpClient okHttpClient(){ + return new okhttp3.OkHttpClient.Builder() + //设置连接超时 + .connectTimeout(15, TimeUnit.SECONDS) + //设置读超时 + .readTimeout(15, TimeUnit.SECONDS) + //是否自动重连 + .retryOnConnectionFailure(true) + // 最大连接数、连接存活时间、存活时间单位(分钟) + .connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES)) + //构建OkHttpClient对象 + .build(); + } +} diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/config/MyBatisPlusConfig.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/MyBatisPlusConfig.java new file mode 100644 index 0000000..5e897e3 --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/MyBatisPlusConfig.java @@ -0,0 +1,27 @@ +package com.hydrogen.applet.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@MapperScan("com.hydrogen.examSystem.dao") +public class MyBatisPlusConfig { + /** + * 分页插件 + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加 + // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType + return interceptor; + } +} diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/config/MybatisGenerator.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/MybatisGenerator.java new file mode 100644 index 0000000..ba82295 --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/MybatisGenerator.java @@ -0,0 +1,145 @@ +package com.hydrogen.applet.config; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; +import com.baomidou.mybatisplus.core.toolkit.StringPool; +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 com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +/** + * @ClassName MybatisGenerator + * @Description mybatis生成器 + * @Author chaixueteng + * @Date 2020/3/11 10:34 + */ +public class MybatisGenerator { + + private static final String MYSQL_URL ="jdbc:mysql://120.46.194.248:13306/jhqm_exam?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true"; + private static final String MYSQL_DRIVE ="com.mysql.cj.jdbc.Driver"; + private static final String MYSQL_U ="exam_user"; + private static final String MYSQL_P ="7Js$A2LcTKy="; + + + /** + *

+ * 读取控制台内容 + *

+ */ + @SuppressWarnings("resource") + public static String scanner(String tip) { + Scanner scanner = new Scanner(System.in); + StringBuilder help = new StringBuilder(); + help.append("请输入" + tip + ":"); + System.out.println(help.toString()); + 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(); + final String projectPath = System.getProperty("user.dir"); + gc.setOutputDir(projectPath + "/src/main/java"); + gc.setAuthor("linyx"); + gc.setOpen(false); + gc.setServiceName("%sService");// service 命名方式 + gc.setServiceImplName("%sServiceImpl");// service impl 命名方式 + // 自定义文件命名,注意 %s 会自动填充表实体属性! + gc.setMapperName("%sDao"); + gc.setXmlName("%sDao"); + gc.setFileOverride(true); + gc.setActiveRecord(true); + gc.setEnableCache(false);// XML 二级缓存 + gc.setBaseResultMap(true);// XML ResultMap + gc.setBaseColumnList(true);// XML columList + gc.setIdType(IdType.ASSIGN_ID); + gc.setSwagger2(true); + mpg.setGlobalConfig(gc); + + // 数据源配置 + DataSourceConfig dsc = new DataSourceConfig(); + dsc.setUrl(MYSQL_URL); + // dsc.setSchemaName("public"); + dsc.setDriverName(MYSQL_DRIVE); + dsc.setUsername(MYSQL_U); + dsc.setPassword(MYSQL_P); + mpg.setDataSource(dsc); + + // 包配置 + PackageConfig pc = new PackageConfig(); + //pc.setModuleName(scanner("模块名")); + pc.setParent("com.hydrogen.examSystem"); + pc.setEntity("entity"); + pc.setService("service"); + pc.setServiceImpl("service.impl"); + pc.setController("controller");// 设置控制器包名 + pc.setMapper("dao"); + mpg.setPackageInfo(pc); + + // 自定义配置 + InjectionConfig cfg = new InjectionConfig() { + @Override + public void initMap() {} + }; + + // 如果模板引擎是 freemarker + String templatePath = "/templates/mapper.xml.ftl"; + + // 自定义输出配置 + List focList = new ArrayList(); + // 自定义配置会被优先输出 + focList.add(new FileOutConfig(templatePath) { + @Override + public String outputFile(TableInfo tableInfo) { + // 自定义输出文件名 + return projectPath + "/src/main/resources/mapping/" + + tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML; + } + }); + + cfg.setFileOutConfigList(focList); + mpg.setCfg(cfg); + + // 配置模板 + TemplateConfig templateConfig = new TemplateConfig(); + + templateConfig.setXml(null); + mpg.setTemplate(templateConfig); + + // 策略配置 + StrategyConfig strategy = new StrategyConfig(); + strategy.setNaming(NamingStrategy.underline_to_camel); + //生成时 添加字段注解,解决数据库字段与实体类不一致问题 比如 mysql :f_id pojo:id + strategy.setEntityTableFieldAnnotationEnable(true); + strategy.setColumnNaming(NamingStrategy.underline_to_camel); + strategy.setRestControllerStyle(true); + strategy.setInclude(scanner("表名")); + strategy.setControllerMappingHyphenStyle(true); + strategy.setEntityLombokModel(true); + strategy.setTablePrefix("t_exam_system_"); + strategy.setFieldPrefix("f_"); + mpg.setStrategy(strategy); + mpg.setTemplateEngine(new FreemarkerTemplateEngine()); + mpg.execute(); + } +} + + + diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/config/SwaggerConfig.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/SwaggerConfig.java new file mode 100644 index 0000000..0ff291c --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/config/SwaggerConfig.java @@ -0,0 +1,40 @@ +package com.hydrogen.applet.config; + +import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; +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.oas.annotations.EnableOpenApi; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +@Configuration +@EnableOpenApi +@EnableKnife4j +public class SwaggerConfig { + + @Bean + Docket docket(){ + // 设置 swagger的版本 + return new Docket(DocumentationType.OAS_30) + // 选择生成接口文档 + .select() + // 包所在的路径 + .apis(RequestHandlerSelectors.basePackage("com.hydrogen.applet.controller")) + // 当前包下所有接口都生成 + .paths(PathSelectors.any()) + .build() + // 接口文档初始化,也就是设置接口文档的详细信息, + .apiInfo( + new ApiInfoBuilder() + .description("吸氢机小程序接口文档") + .version("v1.0") + .title("API 测试文档") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") + .build() + ); + } +} diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/AuthenticationInterceptor.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/AuthenticationInterceptor.java new file mode 100644 index 0000000..4f6b9bb --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/AuthenticationInterceptor.java @@ -0,0 +1,85 @@ +package com.hydrogen.applet.filter; + +import com.alibaba.fastjson.JSONObject; +import com.hydrogen.mbg.utils.JwtTokenUtil; +import com.hydrogen.mbg.utils.RedisUtil; +import com.hydrogen.mbg.vo.DrhtResult; +import org.apache.commons.lang3.StringUtils; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * @author fjc + * @date 2023-10-16 17:30 + */ +@Configuration +public class AuthenticationInterceptor implements HandlerInterceptor { + + @Resource + JwtTokenUtil jwtTokenUtil; + @Resource + RedisUtil redisUtil; + + /** + * 请求前置校验 + * + * @param request current HTTP request + * @param response current HTTP response + * @param handler chosen handler to execute, for type and/or instance evaluation + * @return + * @throws Exception + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + if ("OPTIONS".equals(request.getMethod())) {//这里通过判断请求的方法,判断此次是否是预检请求,如果是,标示,允许跨域;预检后,正式请求,这个方法参数就是我们设置的post了 + response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");//当判定为预检请求后,设定允许请求的方法 + response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Token"); //当判定为预检请求后,设定允许请求的头部类型 + response.addHeader("Access-Control-Max-Age", "1"); + return true; + } + + // 从 http 请求头中取出 token + String authorizationToken = request.getHeader("Authorization"); + if (!StringUtils.isEmpty(authorizationToken)) { + //判断token是否有效 + return jwtTokenUtil.validateToken(authorizationToken); + } + + writeResponse(response); + return true; + } + + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { +// String token = request.getHeader("token"); +// userDao.refreshToken(token); + } + + /** + * 写入响应 + * + * @param resp 响应结果 + * @throws IOException + */ + private void writeResponse(HttpServletResponse resp) throws IOException { + DrhtResult fail = DrhtResult.build(1000, "请重新登陆"); + resp.setCharacterEncoding("utf-8"); + resp.setContentType("text/javascript"); + PrintWriter writer = resp.getWriter(); + writer.write(JSONObject.toJSON(fail).toString()); + writer.flush(); + writer.close(); + } +} diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/GlobalParameterValidationHandler.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/GlobalParameterValidationHandler.java new file mode 100644 index 0000000..8adea0f --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/GlobalParameterValidationHandler.java @@ -0,0 +1,38 @@ +package com.hydrogen.applet.filter; + +import com.hydrogen.mbg.vo.DrhtResult; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +/** + * 全局Controller参数校验异常处理 + * + * @author linyx + * @Date 2019/7/16 + */ +@ControllerAdvice +@Slf4j +public class GlobalParameterValidationHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseBody + public DrhtResult exception(MethodArgumentNotValidException e, HttpServletRequest request) { + StringBuilder result = new StringBuilder(); + BindingResult bindingResult = e.getBindingResult(); + log.error("请求[ {} ] {} 的参数校验发生错误", request.getMethod(), request.getRequestURL()); + for (ObjectError objectError : bindingResult.getAllErrors()) { + FieldError fieldError = (FieldError) objectError; + log.error("参数 {} = {} 校验错误:{}", fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage()); + result.append(fieldError.getDefaultMessage()); + result.append(";"); + } + return DrhtResult.build(400, result.toString()); + } +} \ No newline at end of file diff --git a/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/InteceptorChainConfigFilter.java b/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/InteceptorChainConfigFilter.java new file mode 100644 index 0000000..fad5ab5 --- /dev/null +++ b/hydrogen-applet/src/main/java/com/hydrogen/applet/filter/InteceptorChainConfigFilter.java @@ -0,0 +1,59 @@ +package com.hydrogen.applet.filter; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @author fjc + * @date 2023-10-16 17:30 + */ +@Configuration +public class InteceptorChainConfigFilter implements WebMvcConfigurer { + + @Bean + public HandlerInterceptor myIPInterceptor(){ + return new AuthenticationInterceptor(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(myIPInterceptor()) + .addPathPatterns("/**") + .excludePathPatterns("/applet/login") + .excludePathPatterns("/doc.html") + .excludePathPatterns("/swagger-resources") + .excludePathPatterns("/v2/api-docs") + .excludePathPatterns("/v3/api-docs") + .excludePathPatterns("/favicon.ico") + .excludePathPatterns("/webjars/**") + .excludePathPatterns("/upload/**"); + } + + /** + * 配置跨域 + * */ + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("*") + .allowedHeaders("*"); + } + + + /** + * 配置默认资源请求路径 + * */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/**") + .addResourceLocations("classpath:/static/"); + registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } +} diff --git a/hydrogen-applet/src/main/resources/application-dev.yml b/hydrogen-applet/src/main/resources/application-dev.yml new file mode 100644 index 0000000..9c057d3 --- /dev/null +++ b/hydrogen-applet/src/main/resources/application-dev.yml @@ -0,0 +1,45 @@ + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包 + url: jdbc:mysql://120.46.194.248:13306/hydrogen?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true&rewriteBatchedStatements=true # 数据库名称 + username: hydrogen_user + password: 'sFgo)_%h4CD5' + druid: + # 初始化大小,最小,最大 + initial-size: 5 + min-idle: 5 + max-active: 20 + # 配置获取连接等待超时的时间 + max-wait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + time-between-eviction-runs-millis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 + connect-properties: + druid.stat.slowSqlMillis=5000 + druid.stat.mergeSql=true; + # 合并多个DruidDataSource的监控数据 + use-global-data-source-stat: true + filters: stat,wall + + redis: + lettuce: + pool: + max-active: 200 + max-idle: 10 + min-idle: -1 + host: 120.46.171.171 + port: 6379 + password: bcd4@g2wp*PZv#&U + timeout: 1000 + database: 1 \ No newline at end of file diff --git a/hydrogen-applet/src/main/resources/application-prod.yml b/hydrogen-applet/src/main/resources/application-prod.yml new file mode 100644 index 0000000..089cdab --- /dev/null +++ b/hydrogen-applet/src/main/resources/application-prod.yml @@ -0,0 +1,43 @@ +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包 + url: jdbc:mysql://hydrogenprod.internal.cn-north-4.mysql.rds.myhuaweicloud.com:13306/hydrogen?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true&rewriteBatchedStatements=true # 数据库名称 + username: hydrogen_user + password: 'EwkgCTJU$8g7' + druid: + # 初始化大小,最小,最大 + initial-size: 5 + min-idle: 5 + max-active: 20 + # 配置获取连接等待超时的时间 + max-wait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + time-between-eviction-runs-millis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 + connect-properties: + druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 + # 合并多个DruidDataSource的监控数据 + use-global-data-source-stat: true + filters: stat,wall + + redis: + lettuce: + pool: + max-active: 200 + max-idle: 10 + min-idle: -1 + host: redis-6962c01f-a6ab-40c7-9ae1-6dcc29aeb6f3.cn-north-4.dcs.myhuaweicloud.com + port: 6379 + password: juGmpEv*=p6!&*m6 + timeout: 1000 + database: 1 diff --git a/hydrogen-applet/src/main/resources/application.yml b/hydrogen-applet/src/main/resources/application.yml new file mode 100644 index 0000000..4d1372a --- /dev/null +++ b/hydrogen-applet/src/main/resources/application.yml @@ -0,0 +1,71 @@ +# 应用服务 WEB 访问端口 +server: + port: 8007 + servlet: + context-path: /hydrogen-applet + encoding: + charset: UTF-8 + force: true + enabled: true + compression: + enabled: true + min-response-size: 1024 + mime-types: + - image/png + - image/jpeg + - image/jpg + - text/html + - application/javascript + - text/css + - application/octet-stream + - application/json + +spring: + jmx: + enabled: false + # 当前环境名称(注意:不可设置为 test 它是单元测试专用的名称) + profiles: + active: dev + application: + name: hydrogen-applet + mvc: + pathmatch: + matching-strategy: ant_path_matcher + + cloud: + sentinel: + transport: + # 控制台地址 + dashboard: 127.0.0.1:8718 + eager: true +# 声明式服务 +feign: + # 开启okhttp客户端 + okhttp: + enabled: true + # 请求与响应的压缩以提高通信效率 + compression: + request: + enabled: true + min-request-size: 2048 + mime-types: text/xml,application/xml,application/json + response: + enabled: true + + httpclient: + enabled: false + +logging: + config: classpath:logback-spring.xml + +#mybatisPlus +mybatis-plus: + mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径 + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + map-underscore-to-camel-case: true + local-cache-scope: STATEMENT +jwt: + secret: hydrogenUserSecret + expiration: 604800 + tokenHead: hydrogenBearer \ No newline at end of file diff --git a/hydrogen-applet/src/main/resources/logback-spring.xml b/hydrogen-applet/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..6018036 --- /dev/null +++ b/hydrogen-applet/src/main/resources/logback-spring.xml @@ -0,0 +1,54 @@ + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hydrogen-brand-manager/.gitignore b/hydrogen-brand-manager/.gitignore new file mode 100644 index 0000000..1ea203b --- /dev/null +++ b/hydrogen-brand-manager/.gitignore @@ -0,0 +1,44 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/misc.xml +.idea/libraries/ +.idea/misc.xml/ +.idea/vcs.xml/ +.idea/uiDesigner.xml/ +*.iws +*.iml +*.ipr +.idea/dataSources.xml +.idea/mybatisx/templates.xml + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/hydrogen-brand-manager/pom.xml b/hydrogen-brand-manager/pom.xml new file mode 100644 index 0000000..c6d82ff --- /dev/null +++ b/hydrogen-brand-manager/pom.xml @@ -0,0 +1,127 @@ + + + 4.0.0 + + com.hydrogen + hydrogen + 1.0-SNAPSHOT + + com.hydrogen + hydrogen-brand-manager + 0.0.1-SNAPSHOT + hydrogen-brand-manager + 吸氢机品牌商管理后台 + war + + + 8 + 8 + UTF-8 + + + + + mysql + mysql-connector-java + + + + com.alibaba + druid-spring-boot-starter + + + + com.baomidou + mybatis-plus-boot-starter + + + + com.baomidou + mybatis-plus-generator + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + com.hydrogen + hydrogen-mbg + 1.0-SNAPSHOT + + + + + nexus + Nexus Repository + http://nexus.derunht.cn/repository/maven-public/ + + true + + + true + + + + + + + nexus + Nexus Plugin Repository + http://nexus.derunht.cn/repository/maven-public/ + + true + + + true + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 1.4.2.RELEASE + + + com.hydrogen.brandManager.brandManagerApplication + + + + + repackage + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.2.3 + + false + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 8 + 8 + + + + + + \ No newline at end of file diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/HydrogenBrandManagerApplication.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/HydrogenBrandManagerApplication.java new file mode 100644 index 0000000..1e3525f --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/HydrogenBrandManagerApplication.java @@ -0,0 +1,15 @@ +package com.hydrogen; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; + +@MapperScan(basePackages ="com.hydrogen.brandManager.dao") +@EnableAsync +@SpringBootApplication +public class HydrogenBrandManagerApplication { + public static void main(String[] args) { + SpringApplication.run(HydrogenBrandManagerApplication.class, args); + } +} diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/ServletInitializer.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/ServletInitializer.java new file mode 100644 index 0000000..b7ba665 --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/ServletInitializer.java @@ -0,0 +1,13 @@ +package com.hydrogen; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +public class ServletInitializer extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(HydrogenBrandManagerApplication.class); + } + +} \ No newline at end of file diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignConfiguration.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignConfiguration.java new file mode 100644 index 0000000..8d120d3 --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignConfiguration.java @@ -0,0 +1,18 @@ +package com.hydrogen.brandManager.config; + +import feign.Logger; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Feign 客户端日志配置 + */ +@Configuration +public class FeignConfiguration { + + @Bean + Logger.Level feignLevel() { + return Logger.Level.BASIC; + } + +} \ No newline at end of file diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignOkHttpConfig.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignOkHttpConfig.java new file mode 100644 index 0000000..5b40ea5 --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/FeignOkHttpConfig.java @@ -0,0 +1,39 @@ +package com.hydrogen.brandManager.config; + +import feign.Feign; +import okhttp3.ConnectionPool; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.cloud.openfeign.FeignAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.concurrent.TimeUnit; + +/** + * @ClassName OpenFeignInterfaceConfiguration + * @Description OpenFeignConfig 配置管理 + * @Author chaixueteng + * @Date 2020/3/10 9:46 + */ +@Configuration +@ConditionalOnClass(Feign.class) +@AutoConfigureBefore(FeignAutoConfiguration.class) +public class FeignOkHttpConfig { + + + @Bean + public okhttp3.OkHttpClient okHttpClient(){ + return new okhttp3.OkHttpClient.Builder() + //设置连接超时 + .connectTimeout(15, TimeUnit.SECONDS) + //设置读超时 + .readTimeout(15, TimeUnit.SECONDS) + //是否自动重连 + .retryOnConnectionFailure(true) + // 最大连接数、连接存活时间、存活时间单位(分钟) + .connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES)) + //构建OkHttpClient对象 + .build(); + } +} diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MyBatisPlusConfig.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MyBatisPlusConfig.java new file mode 100644 index 0000000..baee160 --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MyBatisPlusConfig.java @@ -0,0 +1,27 @@ +package com.hydrogen.brandManager.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +@MapperScan("com.hydrogen.brandManager.dao") +public class MyBatisPlusConfig { + /** + * 分页插件 + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加 + // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType + return interceptor; + } +} diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MybatisGenerator.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MybatisGenerator.java new file mode 100644 index 0000000..faae2cf --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/MybatisGenerator.java @@ -0,0 +1,145 @@ +package com.hydrogen.brandManager.config; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; +import com.baomidou.mybatisplus.core.toolkit.StringPool; +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 com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; +import org.apache.commons.lang3.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +/** + * @ClassName MybatisGenerator + * @Description mybatis生成器 + * @Author chaixueteng + * @Date 2020/3/11 10:34 + */ +public class MybatisGenerator { + + private static final String MYSQL_URL ="jdbc:mysql://120.46.194.248:13306/jhqm_exam?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true"; + private static final String MYSQL_DRIVE ="com.mysql.cj.jdbc.Driver"; + private static final String MYSQL_U ="exam_user"; + private static final String MYSQL_P ="7Js$A2LcTKy="; + + + /** + *

+ * 读取控制台内容 + *

+ */ + @SuppressWarnings("resource") + public static String scanner(String tip) { + Scanner scanner = new Scanner(System.in); + StringBuilder help = new StringBuilder(); + help.append("请输入" + tip + ":"); + System.out.println(help.toString()); + 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(); + final String projectPath = System.getProperty("user.dir"); + gc.setOutputDir(projectPath + "/src/main/java"); + gc.setAuthor("linyx"); + gc.setOpen(false); + gc.setServiceName("%sService");// service 命名方式 + gc.setServiceImplName("%sServiceImpl");// service impl 命名方式 + // 自定义文件命名,注意 %s 会自动填充表实体属性! + gc.setMapperName("%sDao"); + gc.setXmlName("%sDao"); + gc.setFileOverride(true); + gc.setActiveRecord(true); + gc.setEnableCache(false);// XML 二级缓存 + gc.setBaseResultMap(true);// XML ResultMap + gc.setBaseColumnList(true);// XML columList + gc.setIdType(IdType.ASSIGN_ID); + gc.setSwagger2(true); + mpg.setGlobalConfig(gc); + + // 数据源配置 + DataSourceConfig dsc = new DataSourceConfig(); + dsc.setUrl(MYSQL_URL); + // dsc.setSchemaName("public"); + dsc.setDriverName(MYSQL_DRIVE); + dsc.setUsername(MYSQL_U); + dsc.setPassword(MYSQL_P); + mpg.setDataSource(dsc); + + // 包配置 + PackageConfig pc = new PackageConfig(); + //pc.setModuleName(scanner("模块名")); + pc.setParent("com.hydrogen.brandManager"); + pc.setEntity("entity"); + pc.setService("service"); + pc.setServiceImpl("service.impl"); + pc.setController("controller");// 设置控制器包名 + pc.setMapper("dao"); + mpg.setPackageInfo(pc); + + // 自定义配置 + InjectionConfig cfg = new InjectionConfig() { + @Override + public void initMap() {} + }; + + // 如果模板引擎是 freemarker + String templatePath = "/templates/mapper.xml.ftl"; + + // 自定义输出配置 + List focList = new ArrayList(); + // 自定义配置会被优先输出 + focList.add(new FileOutConfig(templatePath) { + @Override + public String outputFile(TableInfo tableInfo) { + // 自定义输出文件名 + return projectPath + "/src/main/resources/mapping/" + + tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML; + } + }); + + cfg.setFileOutConfigList(focList); + mpg.setCfg(cfg); + + // 配置模板 + TemplateConfig templateConfig = new TemplateConfig(); + + templateConfig.setXml(null); + mpg.setTemplate(templateConfig); + + // 策略配置 + StrategyConfig strategy = new StrategyConfig(); + strategy.setNaming(NamingStrategy.underline_to_camel); + //生成时 添加字段注解,解决数据库字段与实体类不一致问题 比如 mysql :f_id pojo:id + strategy.setEntityTableFieldAnnotationEnable(true); + strategy.setColumnNaming(NamingStrategy.underline_to_camel); + strategy.setRestControllerStyle(true); + strategy.setInclude(scanner("表名")); + strategy.setControllerMappingHyphenStyle(true); + strategy.setEntityLombokModel(true); + strategy.setTablePrefix("t_exam_system_"); + strategy.setFieldPrefix("f_"); + mpg.setStrategy(strategy); + mpg.setTemplateEngine(new FreemarkerTemplateEngine()); + mpg.execute(); + } +} + + + diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/SwaggerConfig.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/SwaggerConfig.java new file mode 100644 index 0000000..6adb9b2 --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/config/SwaggerConfig.java @@ -0,0 +1,40 @@ +package com.hydrogen.brandManager.config; + +import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; +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.oas.annotations.EnableOpenApi; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +@Configuration +@EnableOpenApi +@EnableKnife4j +public class SwaggerConfig { + + @Bean + Docket docket(){ + // 设置 swagger的版本 + return new Docket(DocumentationType.OAS_30) + // 选择生成接口文档 + .select() + // 包所在的路径 + .apis(RequestHandlerSelectors.basePackage("com.hydrogen.brandManager.controller")) + // 当前包下所有接口都生成 + .paths(PathSelectors.any()) + .build() + // 接口文档初始化,也就是设置接口文档的详细信息, + .apiInfo( + new ApiInfoBuilder() + .description("企业企盟考试系统接口文档") + .version("v1.0") + .title("API 测试文档") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0") + .build() + ); + } +} diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/AuthenticationInterceptor.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/AuthenticationInterceptor.java new file mode 100644 index 0000000..dc5853c --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/AuthenticationInterceptor.java @@ -0,0 +1,78 @@ +package com.hydrogen.brandManager.filter; + +import com.alibaba.fastjson.JSONObject; +import com.hydrogen.mbg.utils.JwtTokenUtil; +import com.hydrogen.mbg.utils.RedisUtil; +import com.hydrogen.mbg.vo.DrhtResult; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +/** + * 登陆拦截器 + */ +@Slf4j +public class AuthenticationInterceptor implements HandlerInterceptor { + + @Resource + JwtTokenUtil jwtTokenUtil; + @Resource + RedisUtil redisUtil; + /** + * 请求前置校验 + * @param request current HTTP request + * @param response current HTTP response + * @param handler chosen handler to execute, for type and/or instance evaluation + * @return + * @throws Exception + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + if ("OPTIONS".equals(request.getMethod())) {//这里通过判断请求的方法,判断此次是否是预检请求,如果是,标示,允许跨域;预检后,正式请求,这个方法参数就是我们设置的post了 + response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");//当判定为预检请求后,设定允许请求的方法 + response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Token"); //当判定为预检请求后,设定允许请求的头部类型 + response.addHeader("Access-Control-Max-Age", "1"); + return true; + } + + // 从 http 请求头中取出 token + String authorizationToken = request.getHeader("Authorization"); + if (!StringUtils.isEmpty(authorizationToken)) { + //判断token是否有效 + return jwtTokenUtil.validateToken(authorizationToken); + } + + writeResponse(response); + return true; + } + + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { +// String token = request.getHeader("token"); +// userDao.refreshToken(token); + } + + /** + * 写入响应 + * + * @param resp 响应结果 + * @throws IOException + */ + private void writeResponse(HttpServletResponse resp) throws IOException { + DrhtResult fail = DrhtResult.build(1000, "请重新登陆"); + resp.setCharacterEncoding("utf-8"); + resp.setContentType("text/javascript"); + PrintWriter writer = resp.getWriter(); + writer.write(JSONObject.toJSON(fail).toString()); + writer.flush(); + writer.close(); + } +} diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/GlobalParameterValidationHandler.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/GlobalParameterValidationHandler.java new file mode 100644 index 0000000..5d98f49 --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/GlobalParameterValidationHandler.java @@ -0,0 +1,38 @@ +package com.hydrogen.brandManager.filter; + +import com.hydrogen.mbg.vo.DrhtResult; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.BindingResult; +import org.springframework.validation.FieldError; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; + +/** + * 全局Controller参数校验异常处理 + * + * @author linyx + * @Date 2019/7/16 + */ +@ControllerAdvice +@Slf4j +public class GlobalParameterValidationHandler { + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseBody + public DrhtResult exception(MethodArgumentNotValidException e, HttpServletRequest request) { + StringBuilder result = new StringBuilder(); + BindingResult bindingResult = e.getBindingResult(); + log.error("请求[ {} ] {} 的参数校验发生错误", request.getMethod(), request.getRequestURL()); + for (ObjectError objectError : bindingResult.getAllErrors()) { + FieldError fieldError = (FieldError) objectError; + log.error("参数 {} = {} 校验错误:{}", fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage()); + result.append(fieldError.getDefaultMessage()); + result.append(";"); + } + return DrhtResult.build(400, result.toString()); + } +} \ No newline at end of file diff --git a/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/InteceptorChainConfigFilter.java b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/InteceptorChainConfigFilter.java new file mode 100644 index 0000000..3771ead --- /dev/null +++ b/hydrogen-brand-manager/src/main/java/com/hydrogen/brandManager/filter/InteceptorChainConfigFilter.java @@ -0,0 +1,59 @@ +package com.hydrogen.brandManager.filter; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @author fjc + * @date 2023-10-16 17:30 + */ +@Configuration +public class InteceptorChainConfigFilter implements WebMvcConfigurer { + + @Bean + public HandlerInterceptor myIPInterceptor(){ + return new AuthenticationInterceptor(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(myIPInterceptor()) + .addPathPatterns("/**") + .excludePathPatterns("/applet/login") + .excludePathPatterns("/doc.html") + .excludePathPatterns("/swagger-resources") + .excludePathPatterns("/v2/api-docs") + .excludePathPatterns("/v3/api-docs") + .excludePathPatterns("/favicon.ico") + .excludePathPatterns("/webjars/**") + .excludePathPatterns("/upload/**"); + } + + /** + * 配置跨域 + * */ + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("*") + .allowedHeaders("*"); + } + + + /** + * 配置默认资源请求路径 + * */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/**") + .addResourceLocations("classpath:/static/"); + registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } +} diff --git a/hydrogen-brand-manager/src/main/resources/application-prod.yml b/hydrogen-brand-manager/src/main/resources/application-prod.yml new file mode 100644 index 0000000..38a2254 --- /dev/null +++ b/hydrogen-brand-manager/src/main/resources/application-prod.yml @@ -0,0 +1,109 @@ +# 应用服务 WEB 访问端口 +server: + port: 8007 + servlet: + context-path: /exampleSystem + compression: + enabled: true + min-response-size: 1024 + mime-types: + - image/png + - image/jpeg + - image/jpg + - text/html + - application/javascript + - text/css + - application/octet-stream + - application/json + +spring: + jmx: + enabled: false + application: + name: exampleSystem + http: + encoding: + charset: UTF-8 + force: true + enabled: true + mvc: + pathmatch: + matching-strategy: ant_path_matcher + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包 + url: jdbc:mysql://hydrogenprod.internal.cn-north-4.mysql.rds.myhuaweicloud.com:13306/jhqm_exam?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true&rewriteBatchedStatements=true # 数据库名称 + username: exam_user + password: 'EwkgCTJU$8g7' + druid: + # 初始化大小,最小,最大 + initial-size: 5 + min-idle: 5 + max-active: 20 + # 配置获取连接等待超时的时间 + max-wait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + time-between-eviction-runs-millis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 + connect-properties: + druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 + # 合并多个DruidDataSource的监控数据 + use-global-data-source-stat: true + filters: stat,wall + + redis: + lettuce: + pool: + max-active: 200 + max-idle: 10 + min-idle: -1 + host: redis-6962c01f-a6ab-40c7-9ae1-6dcc29aeb6f3.cn-north-4.dcs.myhuaweicloud.com + port: 6379 + password: juGmpEv*=p6!&*m6 + timeout: 1000 + database: 1 + + cloud: + sentinel: + transport: + # 控制台地址 + dashboard: 127.0.0.1:8718 + eager: true +# 声明式服务 +feign: + # 开启okhttp客户端 + okhttp: + enabled: true + # 请求与响应的压缩以提高通信效率 + compression: + request: + enabled: true + min-request-size: 2048 + mime-types: text/xml,application/xml,application/json + response: + enabled: true + + httpclient: + enabled: false + + +logging: + config: classpath:logback-spring.xml + +#mybatisPlus +mybatis-plus: + mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径 + # type-aliases-package: com/hydrogen/brandManager/entity # 注意:对应实体类的路径 + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + map-underscore-to-camel-case: true + local-cache-scope: STATEMENT diff --git a/hydrogen-brand-manager/src/main/resources/application.yml b/hydrogen-brand-manager/src/main/resources/application.yml new file mode 100644 index 0000000..ec5b247 --- /dev/null +++ b/hydrogen-brand-manager/src/main/resources/application.yml @@ -0,0 +1,111 @@ +# 应用服务 WEB 访问端口 +server: + port: 8007 + servlet: + context-path: /brandManager + encoding: + charset: UTF-8 + force: true + enabled: true + compression: + enabled: true + min-response-size: 1024 + mime-types: + - image/png + - image/jpeg + - image/jpg + - text/html + - application/javascript + - text/css + - application/octet-stream + - application/json + +spring: + jmx: + enabled: false + # 当前环境名称(注意:不可设置为 test 它是单元测试专用的名称) + profiles: + active: local + application: + name: brandManager + mvc: + pathmatch: + matching-strategy: ant_path_matcher + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动包 + url: jdbc:mysql://120.46.194.248:13306/jhqm_exam?useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowMultiQueries=true&rewriteBatchedStatements=true # 数据库名称 + username: exam_user + password: '7Js$A2LcTKy=' + druid: + # 初始化大小,最小,最大 + initial-size: 5 + min-idle: 5 + max-active: 20 + # 配置获取连接等待超时的时间 + max-wait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + time-between-eviction-runs-millis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + min-evictable-idle-time-millis: 300000 + validation-query: SELECT 1 FROM DUAL + test-while-idle: true + test-on-borrow: false + test-on-return: false + # 打开PSCache,并且指定每个连接上PSCache的大小 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 + connect-properties: + druid.stat.slowSqlMillis=5000 + druid.stat.mergeSql=true; + # 合并多个DruidDataSource的监控数据 + use-global-data-source-stat: true + filters: stat,wall + + redis: + lettuce: + pool: + max-active: 200 + max-idle: 10 + min-idle: -1 + host: 120.46.171.171 + port: 6379 + password: bcd4@g2wp*PZv#&U + timeout: 1000 + database: 1 + + cloud: + sentinel: + transport: + # 控制台地址 + dashboard: 127.0.0.1:8718 + eager: true +# 声明式服务 +feign: + # 开启okhttp客户端 + okhttp: + enabled: true + # 请求与响应的压缩以提高通信效率 + compression: + request: + enabled: true + min-request-size: 2048 + mime-types: text/xml,application/xml,application/json + response: + enabled: true + + httpclient: + enabled: false + +logging: + config: classpath:logback-spring.xml + +#mybatisPlus +mybatis-plus: + mapper-locations: classpath:mapper/*.xml #注意:一定要对应mapper映射xml文件的所在路径 +# type-aliases-package: com/hydrogen/brandManager/entity # 注意:对应实体类的路径 + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + map-underscore-to-camel-case: true + local-cache-scope: STATEMENT \ No newline at end of file diff --git a/hydrogen-brand-manager/src/main/resources/logback-spring.xml b/hydrogen-brand-manager/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..6018036 --- /dev/null +++ b/hydrogen-brand-manager/src/main/resources/logback-spring.xml @@ -0,0 +1,54 @@ + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/hydrogen-mbg/.gitignore b/hydrogen-mbg/.gitignore new file mode 100644 index 0000000..1ea203b --- /dev/null +++ b/hydrogen-mbg/.gitignore @@ -0,0 +1,44 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/misc.xml +.idea/libraries/ +.idea/misc.xml/ +.idea/vcs.xml/ +.idea/uiDesigner.xml/ +*.iws +*.iml +*.ipr +.idea/dataSources.xml +.idea/mybatisx/templates.xml + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/hydrogen-mbg/pom.xml b/hydrogen-mbg/pom.xml new file mode 100644 index 0000000..d4dd635 --- /dev/null +++ b/hydrogen-mbg/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + com.hydrogen + hydrogen + 1.0-SNAPSHOT + + + hydrogen-mbg + + + 8 + 8 + UTF-8 + + + \ No newline at end of file diff --git a/hydrogen-mbg/src/main/java/com/hydrogen/mbg/bean/PageBean.java b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/bean/PageBean.java new file mode 100644 index 0000000..712eb58 --- /dev/null +++ b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/bean/PageBean.java @@ -0,0 +1,61 @@ +package com.hydrogen.mbg.bean; + + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.List; + +@ApiModel(description = "分页数据") +public class PageBean implements Serializable { + + @ApiModelProperty("当前页码") + private int pageNum; //当前页码 + //@Expose gson 没有此注解的生成json时会被排除掉 + + @ApiModelProperty("每页显示的页数") + private int pageSize; // 每页显示的页数 + + @ApiModelProperty("当前页的数据集合") + private List list; //当前页的数据集合 + + @ApiModelProperty("总记录数") + private int total; //总记录数 + + + public int getPageNum() { + return pageNum; + } + + public void setPageNum(int pageNum) { + this.pageNum = pageNum; + } + + public int getPageSize() { + return pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + + +} diff --git a/hydrogen-mbg/src/main/java/com/hydrogen/mbg/dto/BaseListDTO.java b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/dto/BaseListDTO.java new file mode 100644 index 0000000..83b066b --- /dev/null +++ b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/dto/BaseListDTO.java @@ -0,0 +1,51 @@ +package com.hydrogen.mbg.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +@ApiModel(value = "列表查询基础dto") +public class BaseListDTO implements Serializable { + + @ApiModelProperty(value = "当前页,从1开始") + private Integer pageNum=1; + @ApiModelProperty(value = "每页条数") + private Integer pageSize=15; + @ApiModelProperty(value = "是否分页") + private Boolean page; + + public BaseListDTO() { + this.page = false; + } + + public Integer getPageNum() { + if(pageNum==null||pageNum==0){ + return 1; + } + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + if(pageSize==null||pageSize==0){ + return 15; + } + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public Boolean getPage() { + return page; + } + + public void setPage(Boolean page) { + this.page = page; + } +} \ No newline at end of file diff --git a/hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/JwtTokenUtil.java b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/JwtTokenUtil.java new file mode 100644 index 0000000..03b541b --- /dev/null +++ b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/JwtTokenUtil.java @@ -0,0 +1,111 @@ +package com.hydrogen.mbg.utils; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.StrUtil; +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.DecodedJWT; +//import io.jsonwebtoken.Claims; +//import io.jsonwebtoken.Jwts; +//import io.jsonwebtoken.SignatureAlgorithm; +//import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * JwtToken生成的工具类 + * JWT token的格式:header.payload.signature + * header的格式(算法、token的类型): + * {"alg": "HS512","typ": "JWT"} + * payload的格式(用户名、创建时间、生成时间): + * {"sub":"wang","created":1489079981393,"exp":1489684781} + * signature的生成算法: + * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret) + */ +@Component +public class JwtTokenUtil { + private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class); + private static final String CLAIM_KEY_USERNAME = "account"; + private static final String CLAIM_KEY_USERID = "account_id"; + private static final String CLAIM_KEY_CREATED = "created"; + private static final String ISSUER = "hydrogen"; + @Value("${jwt.secret}") + private String secret; + @Value("${jwt.expiration}") + private Long expiration; + @Value("${jwt.tokenHead}") + private String tokenHead; + + // 创建Token + public String createToken(String userName,String userId) { + return tokenHead + JWT.create() + .withIssuer(ISSUER) //发行人 + .withClaim(CLAIM_KEY_USERNAME,userName) //存放数据 + .withClaim(CLAIM_KEY_USERID,userId) //存放数据 + .withClaim(CLAIM_KEY_CREATED,new Date()) //存放数据 +// .withExpiresAt(new Date(System.currentTimeMillis() + expiration * 1000)) //过期时间,Redis处理 + .sign(Algorithm.HMAC256(secret)); + } +// + // 从Token中获取用户信息 + public Map getUserInfoFromToken(String token) { + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)) + .withIssuer(ISSUER) + .build(); + token = token.replace(tokenHead,""); + DecodedJWT decodedJWT = jwtVerifier.verify(token); + Map userInfo = new HashMap<>(); + userInfo.put(CLAIM_KEY_USERNAME,decodedJWT.getClaim(CLAIM_KEY_USERNAME).asString()); + userInfo.put(CLAIM_KEY_USERID,decodedJWT.getClaim(CLAIM_KEY_USERID).asString()); + return userInfo; + } + + // 验证Token是否有效 + public boolean validateToken(String token) { + boolean isValid = true; + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)) + .withIssuer(ISSUER) + .build(); + try { + token = token.replace(tokenHead,""); + DecodedJWT decodedJWT = jwtVerifier.verify(token); + }catch(Exception e){ + isValid = false; + LOGGER.info("token异常:"+e);; + } + return isValid; + } + + + + public static void main(String[] args) { + Map claims = new HashMap<>(); +// claims.put(CLAIM_KEY_USERNAME, "fujichuan"); + claims.put(CLAIM_KEY_CREATED, new Date()); + String token = JWT.create() + .withIssuer("auth0") //发行人 + .withClaim("username","fujichuan") //存放数据 + .withClaim("created",new Date()) + .withExpiresAt(new Date(System.currentTimeMillis() + 604800 * 1000)) //过期时间 + .sign(Algorithm.HMAC256("userSecret")); + + + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("userSecret")) + .withIssuer("auth0") + .build(); + DecodedJWT decodedJWT = jwtVerifier.verify(token);/// 如果有问题的话,那么抛出各种异常 + + System.out.println("TOKEN 验证通过"); + System.out.println("username :"+ decodedJWT.getClaim("username").asString()); + System.out.println("过期时间:"+ decodedJWT.getExpiresAt()); + + } +} diff --git a/hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/RedisUtil.java b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/RedisUtil.java new file mode 100644 index 0000000..e994416 --- /dev/null +++ b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/utils/RedisUtil.java @@ -0,0 +1,111 @@ +package com.hydrogen.mbg.utils; + +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * @title redis工具类 + * @author LeGreen + * @date 2021/1/6 + */ +@Component +public class RedisUtil { + + private static final String COMMON_KEY = "hydrogen-"; + + @Resource + private RedisTemplate redisTemplate; + + /** + * 设置缓存过期时间 + * @param key 缓存Key + * @param timeout 过期时间 + * @param unit 单位(默认为秒-TimeUnit.SECONDS) + */ + public void expire(String key, long timeout, TimeUnit unit) { + key = COMMON_KEY+key; + redisTemplate.expire(key, timeout, unit == null ? TimeUnit.SECONDS : unit); + } + + /** + * 设置缓存 + * @param key 缓存Key + * @param value 缓存值 + */ + public void setRedisValue(String key, Object value) { + setRedisValue(key, value, null, null); + } + + /** + * 设置缓存 + * @param key 缓存Key + * @param value 缓存值 + * @param timeout 过期时间 + * @param unit 单位(默认为秒-TimeUnit.SECONDS) + */ + public void setRedisValue(String key, Object value, Long timeout, TimeUnit unit) { + key = COMMON_KEY+key; + if(timeout == null || timeout <= 0) { + redisTemplate.opsForValue().set(key, value); + } else { + redisTemplate.opsForValue().set(key, value, timeout, unit == null ? TimeUnit.SECONDS : unit); + } + } + + /** + * 获取对象缓存(String) + * @param key 缓存Key + * @return + */ + public Object getRedisValue(String key) { + key = COMMON_KEY+key; + return redisTemplate.opsForValue().get(key); + } + + /** + * 删除缓存 + * @param keys 要删除的缓存keys + */ + public void delete(String ... keys) { + if(keys == null || keys.length <= 0) { + return; + } + + List keyList = new ArrayList<>(); + for(String key : keys) { + key = COMMON_KEY+key; + keyList.add(key); + } + redisTemplate.delete(keyList); + } + + /** + * 删除缓存 + * @param keys 要删除的缓存keys + */ + public void deletePattern(String ... keys) { + if(keys == null || keys.length <= 0) { + return; + } + + for(String key : keys) { + key = COMMON_KEY+key; + redisTemplate.delete(redisTemplate.keys(key+"*")); + } + } + + /** + * 获取缓存过期时长 + * @param key 要查询的缓存keys + */ + public Long getExpireTime(String key) { + key = COMMON_KEY+key; + return redisTemplate.opsForValue().getOperations().getExpire(key); + } +} \ No newline at end of file diff --git a/hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/DrhtResult.java b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/DrhtResult.java new file mode 100644 index 0000000..5de0994 --- /dev/null +++ b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/DrhtResult.java @@ -0,0 +1,162 @@ +package com.hydrogen.mbg.vo; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.List; + +/** + * 自定义响应结构 + */ +@ApiModel( "统一结果集") +public class DrhtResult implements Serializable { + + // 定义jackson对象 + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @ApiModelProperty( "响应业务状态") + // 响应业务状态 + private Integer status; + + // 响应消息 + @ApiModelProperty( "响应消息") + private String msg; + + // 响应中的数据 + @ApiModelProperty( "响应中的数据") + private T data; + + + public static ObjectMapper getMAPPER() { + return MAPPER; + } + + public static DrhtResult build(Integer status, String msg, T data) { + return new DrhtResult<>(status, msg, data); + } + + public static DrhtResult ok(T data) { + return new DrhtResult<>(data); + } + + public static DrhtResult ok() { + return new DrhtResult(null); + } + + public DrhtResult() { + + } + + public static DrhtResult build(Integer status, String msg) { + return new DrhtResult(status, msg, null); + } + + public DrhtResult(Integer status, String msg, T data) { + this.status = status; + this.msg = msg; + this.data = data; + } + + public DrhtResult(T data) { + this.status = 200; + this.msg = "OK"; + this.data = data; + } + +// public Boolean isOK() { +// return this.status == 200; +// } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + /** + * 将json结果集转化为TaotaoResult对象 + * + * @param jsonData json数据 + * @param clazz TaotaoResult中的object类型 + * @return + */ + public static DrhtResult formatToPojo(String jsonData, Class clazz) { + try { + if (clazz == null) { + return MAPPER.readValue(jsonData, DrhtResult.class); + } + JsonNode jsonNode = MAPPER.readTree(jsonData); + JsonNode data = jsonNode.get("data"); + Object obj = null; + if (clazz != null) { + if (data.isObject()) { + obj = MAPPER.readValue(data.traverse(), clazz); + } else if (data.isTextual()) { + obj = MAPPER.readValue(data.asText(), clazz); + } + } + return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); + } catch (Exception e) { + return null; + } + } + + /** + * 没有object对象的转化 + * + * @param json + * @return + */ + public static DrhtResult format(String json) { + try { + return MAPPER.readValue(json, DrhtResult.class); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Object是集合转化 + * + * @param jsonData json数据 + * @param clazz 集合中的类型 + * @return + */ + public static DrhtResult formatToList(String jsonData, Class clazz) { + try { + JsonNode jsonNode = MAPPER.readTree(jsonData); + JsonNode data = jsonNode.get("data"); + Object obj = null; + if (data.isArray() && data.size() > 0) { + obj = MAPPER.readValue(data.traverse(), + MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); + } + return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); + } catch (Exception e) { + return null; + } + } + +} diff --git a/hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/ListVO.java b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/ListVO.java new file mode 100644 index 0000000..6d4b9b3 --- /dev/null +++ b/hydrogen-mbg/src/main/java/com/hydrogen/mbg/vo/ListVO.java @@ -0,0 +1,63 @@ +package com.hydrogen.mbg.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.util.List; + +@ApiModel(value = "列表查询基础Vo") +public class ListVO { + + public ListVO() { + } + @ApiModelProperty(value = "当前页") + private Integer pageNum; + + @ApiModelProperty(value = "总记录数") + private Long total; + + @ApiModelProperty(value = "数据集") + private List list; + + public ListVO(List arr) { + this.pageNum = 1; + this.list = arr; + this.total = (long)arr.size(); + } + + public ListVO(List arr, Long total) { + this.pageNum = 1; + this.list = arr; + this.total = total; + } + + public ListVO(List arr, Long total, Integer pageNum){ + this.pageNum = pageNum; + this.list = arr; + this.total = total; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Long getTotal() { + return total; + } + + public void setTotal(Long total) { + this.total = total; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..a09a0e8 --- /dev/null +++ b/pom.xml @@ -0,0 +1,294 @@ + + + 4.0.0 + + com.hydrogen + hydrogen + 1.0-SNAPSHOT + pom + + + hydrogen-applet + hydrogen-brand-manager + hydrogen-mbg + + + + + 1.8 + UTF-8 + UTF-8 + 2.6.13 + 2021.0.5 + 2021.0.5.0 + + 3.4.0 + 3.4.0 + + 5.3.9 + + 3.0.0 + + 2.2.2 + + 11.10 + + 1.2.83 + + 2.2.6.RELEASE + 1.4.1 + true + 8.0.19 + 1.1.22 + 2.6.13 + 4.6.0 + 4.6.0 + + + + + + + + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${openfeign.version} + + + io.github.openfeign + feign-okhttp + ${okhttp.version} + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.freemarker + freemarker + + + + + cn.hutool + hutool-all + ${hutool.version} + + + + io.springfox + springfox-boot-starter + ${swagger.version} + + + + com.github.xiaoymin + knife4j-spring-boot-starter + 3.0.2 + + + + org.apache.commons + commons-pool2 + + + org.apache.commons + commons-lang3 + 3.9 + + + com.google.guava + guava + 27.0.1-android + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + org.apache.httpcomponents + httpcore + 4.4.13 + + + com.alibaba + easyexcel + 2.2.8 + + + com.huaweicloud + esdk-obs-java-bundle + 3.21.11 + + + + + com.alibaba + fastjson + ${fastjson.version} + + + + + + com.example + sms + 1.0.0 + + + com.example + bgmprovider + 1.0.3 + + + com.example + jca + 1.0.3 + + + com.example + jsse + 1.0.3 + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + + + com.belerweb + pinyin4j + 2.5.0 + + + io.github.biezhi + TinyPinyin + 2.0.3.RELEASE + + + com.github.stuxuhai + jpinyin + 1.1.8 + + + + com.auth0 + java-jwt + 3.18.2 + + + com.github.binarywang + weixin-java-miniapp + ${weixin-java-miniapp.version} + + + com.github.binarywang + weixin-java-mp + ${weixin-java-mp.version} + + + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + ${mybatis.version} + + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + + com.baomidou + mybatis-plus-boot-starter + ${mybatis-plus.version} + + + + com.baomidou + mybatis-plus-generator + ${mybatis-generator.version} + + + mysql + mysql-connector-java + ${mysql.version} + + + + com.github.pagehelper + pagehelper-spring-boot-starter + ${pagehelper.version} + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + \ No newline at end of file