Sfoglia il codice sorgente

病历质控框架初始化

gaodm 5 anni fa
commit
85403736b7
54 ha cambiato i file con 3641 aggiunte e 0 eliminazioni
  1. 25 0
      .gitignore
  2. 219 0
      pom.xml
  3. 33 0
      src/main/java/com/diagbot/MrqcSysApplication.java
  4. 41 0
      src/main/java/com/diagbot/aop/SysLoggerAspect.java
  5. 25 0
      src/main/java/com/diagbot/client/UserServiceClient.java
  6. 23 0
      src/main/java/com/diagbot/client/hystrix/UserServiceHystrix.java
  7. 19 0
      src/main/java/com/diagbot/config/CustomAccessTokenConverter.java
  8. 30 0
      src/main/java/com/diagbot/config/CustomTokenEnhancer.java
  9. 15 0
      src/main/java/com/diagbot/config/GlobalMethodSecurityConfigurer.java
  10. 48 0
      src/main/java/com/diagbot/config/JwtConfigurer.java
  11. 33 0
      src/main/java/com/diagbot/config/MybatisPlusConfigurer.java
  12. 91 0
      src/main/java/com/diagbot/config/OAuth2Configurer.java
  13. 112 0
      src/main/java/com/diagbot/config/RedisConfigurer.java
  14. 42 0
      src/main/java/com/diagbot/config/ResourceServerConfigurer.java
  15. 70 0
      src/main/java/com/diagbot/config/SwaggerConfigurer.java
  16. 69 0
      src/main/java/com/diagbot/config/WebSecurityConfigurer.java
  17. 96 0
      src/main/java/com/diagbot/config/security/UrlAccessDecisionManager.java
  18. 29 0
      src/main/java/com/diagbot/config/security/UrlConfigAttribute.java
  19. 79 0
      src/main/java/com/diagbot/config/security/UrlFilterSecurityInterceptor.java
  20. 40 0
      src/main/java/com/diagbot/config/security/UrlMetadataSourceService.java
  21. 16 0
      src/main/java/com/diagbot/entity/JwtStore.java
  22. 172 0
      src/main/java/com/diagbot/entity/Permission.java
  23. 196 0
      src/main/java/com/diagbot/entity/SysLog.java
  24. 21 0
      src/main/java/com/diagbot/entity/Token.java
  25. 182 0
      src/main/java/com/diagbot/entity/User.java
  26. 81 0
      src/main/java/com/diagbot/exception/CommonExceptionHandler.java
  27. 39 0
      src/main/java/com/diagbot/exception/ServiceErrorCode.java
  28. 13 0
      src/main/java/com/diagbot/facade/SysLogFacade.java
  29. 13 0
      src/main/java/com/diagbot/facade/TokenFacade.java
  30. 18 0
      src/main/java/com/diagbot/mapper/PermissionMapper.java
  31. 16 0
      src/main/java/com/diagbot/mapper/SysLogMapper.java
  32. 16 0
      src/main/java/com/diagbot/mapper/UserMapper.java
  33. 15 0
      src/main/java/com/diagbot/service/SysLogService.java
  34. 35 0
      src/main/java/com/diagbot/service/TokenService.java
  35. 40 0
      src/main/java/com/diagbot/service/UrlGrantedAuthority.java
  36. 50 0
      src/main/java/com/diagbot/service/UrlUserService.java
  37. 19 0
      src/main/java/com/diagbot/service/impl/SysLogServiceImpl.java
  38. 146 0
      src/main/java/com/diagbot/service/impl/TokenServiceImpl.java
  39. 21 0
      src/main/java/com/diagbot/vo/SysLogVo.java
  40. 110 0
      src/main/java/com/diagbot/web/SysLogController.java
  41. 153 0
      src/main/resources/application-dev.yml
  42. 153 0
      src/main/resources/application-local.yml
  43. 153 0
      src/main/resources/application-pre.yml
  44. 153 0
      src/main/resources/application-pro.yml
  45. 153 0
      src/main/resources/application-test.yml
  46. 21 0
      src/main/resources/bootstrap.yml
  47. BIN
      src/main/resources/diagbot-jwt.jks
  48. 306 0
      src/main/resources/logback-spring.xml
  49. 26 0
      src/main/resources/mapper/PermissionMapper.xml
  50. 22 0
      src/main/resources/mapper/SysLogMapper.xml
  51. 35 0
      src/main/resources/mapper/UserMapper.xml
  52. 9 0
      src/main/resources/public.cert
  53. 83 0
      src/test/java/com/diagbot/CodeGeneration.java
  54. 16 0
      src/test/java/com/diagbot/MrqcSysApplicationTests.java

+ 25 - 0
.gitignore

@@ -0,0 +1,25 @@
+/target/
+!.mvn/wrapper/maven-wrapper.jar
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/build/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/

+ 219 - 0
pom.xml

@@ -0,0 +1,219 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.diagbot</groupId>
+    <artifactId>mrqc-sys</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <packaging>jar</packaging>
+
+    <name>mrqc-sys</name>
+    <description>病历质控系统</description>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>2.2.1.RELEASE</version>
+        <relativePath/>
+    </parent>
+
+    <properties>
+        <maven.compiler.source>1.8</maven.compiler.source>
+        <maven.compiler.target>1.8</maven.compiler.target>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+        <java.version>1.8</java.version>
+        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
+        <mybatis-plus-boot-starter.version>3.2.0</mybatis-plus-boot-starter.version>
+        <mybatis-spring-boot.version>2.1.1</mybatis-spring-boot.version>
+        <druid.version>1.1.21</druid.version>
+        <swagger.version>2.9.2</swagger.version>
+        <!--<swagger-bootstrap.version>1.9.1</swagger-bootstrap.version>-->
+        <logstash.version>5.2</logstash.version>
+        <poi.version>4.1.1</poi.version>
+        <aggregator.version>1.1.0</aggregator.version>
+        <okhttp.version>4.2.2</okhttp.version>
+        <docker-maven-plugin.version>1.2.1</docker-maven-plugin.version>
+        <docker.image.prefix>192.168.2.236:5000/diagbotcloud</docker.image.prefix>
+        <registryUrl>http://192.168.2.236:5000/repository/diagbotcloud/</registryUrl>
+    </properties>
+
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework.cloud</groupId>
+                <artifactId>spring-cloud-dependencies</artifactId>
+                <version>${spring-cloud.version}</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.diagbot</groupId>
+            <artifactId>common</artifactId>
+            <version>0.0.1-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jolokia</groupId>
+            <artifactId>jolokia-core</artifactId>
+        </dependency>
+
+        <!-- 开启web-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.springframework.boot</groupId>
+                    <artifactId>spring-boot-starter-tomcat</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-undertow</artifactId>
+        </dependency>
+
+        <!-- 开启feign-->
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-openfeign</artifactId>
+        </dependency>
+
+        <!-- dashboard -->
+        <!-- actuator-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-actuator</artifactId>
+        </dependency>
+        <!--hystrix-dashboard-->
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
+        </dependency>
+        <!--hystrix -->
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
+        </dependency>
+
+        <!--swagger-->
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger2</artifactId>
+            <version>${swagger.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>io.springfox</groupId>
+            <artifactId>springfox-swagger-ui</artifactId>
+            <version>${swagger.version}</version>
+        </dependency>
+        <!--database-->
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+        <!--security-->
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-oauth2</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <dependency>
+            <groupId>net.logstash.logback</groupId>
+            <artifactId>logstash-logback-encoder</artifactId>
+            <version>${logstash.version}</version>
+        </dependency>
+
+
+        <!-- mybatis-plus begin -->
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>${mybatis-plus-boot-starter.version}</version>
+        </dependency>
+
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-generator</artifactId>
+            <version>${mybatis-plus-boot-starter.version}</version>
+        </dependency>
+        <!-- mybatis-plus end -->
+
+        <!-- 阿里巴巴druid数据库连接池 -->
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>druid-spring-boot-starter</artifactId>
+            <version>${druid.version}</version>
+        </dependency>
+
+        <!-- springboot整合mybatis(核心就这一个) -->
+        <!-- 注意顺序,这个一定要放在最下面 -->
+        <dependency>
+            <groupId>org.mybatis.spring.boot</groupId>
+            <artifactId>mybatis-spring-boot-starter</artifactId>
+            <version>${mybatis-spring-boot.version}</version>
+        </dependency>
+
+        <!--redis设置-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-pool2</artifactId>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+            <!-- 添加docker-maven插件 -->
+            <plugin>
+                <groupId>com.spotify</groupId>
+                <artifactId>docker-maven-plugin</artifactId>
+                <version>1.1.1</version>
+                <configuration>
+                    <imageName>${docker.image.prefix}/${project.artifactId}:${project.version}</imageName>
+                    <forceTags>true</forceTags>
+                    <!--镜像的FROM,使用压缩的小镜像-->
+                    <baseImage>frolvlad/alpine-oraclejre8:slim</baseImage>
+                    <entryPoint>["java", "-jar", "-Xms256m", "-Xmx1024m", "-Duser.timezone=GMT+8", "/${project.build.finalName}.jar"]</entryPoint>
+                    <resources>
+                        <resource>
+                            <targetPath>/</targetPath>
+                            <directory>${project.build.directory}</directory>
+                            <include>${project.build.finalName}.jar</include>
+                        </resource>
+                    </resources>
+                    <serverId>docker-registry</serverId>
+                    <registryUrl>${registryUrl}</registryUrl>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 33 - 0
src/main/java/com/diagbot/MrqcSysApplication.java

@@ -0,0 +1,33 @@
+package com.diagbot;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
+import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
+import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
+import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration;
+import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
+import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
+import org.springframework.cloud.netflix.hystrix.EnableHystrix;
+import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
+import org.springframework.cloud.openfeign.EnableFeignClients;
+
+
+/**
+ * @Description: 互动反馈启动文件
+ * @author: gaodm
+ * @time: 2018/8/7 9:26
+ */
+@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
+        JmxAutoConfiguration.class, ThymeleafAutoConfiguration.class })
+@EnableFeignClients({ "com.diagbot.client" })
+@EnableHystrixDashboard
+@EnableHystrix
+@EnableCircuitBreaker
+@ConfigurationPropertiesScan
+public class MrqcSysApplication {
+
+    public static void main(String[] args) {
+        SpringApplication.run(MrqcSysApplication.class, args);
+    }
+}

+ 41 - 0
src/main/java/com/diagbot/aop/SysLoggerAspect.java

@@ -0,0 +1,41 @@
+//package com.diagbot.aop;
+//
+//import com.diagbot.biz.log.entity.SysLog;
+//import com.diagbot.enums.SysTypeEnum;
+//import com.diagbot.rabbit.MySender;
+//import com.diagbot.util.AopUtil;
+//import org.aspectj.lang.JoinPoint;
+//import org.aspectj.lang.annotation.Aspect;
+//import org.aspectj.lang.annotation.Before;
+//import org.aspectj.lang.annotation.Pointcut;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+//import org.springframework.stereotype.Component;
+//
+///**
+// * @Description: 日志拦截切面
+// * @author: gaodm
+// * @time: 2018/8/2 13:36
+// */
+//@Aspect
+//@Component
+//@ConditionalOnProperty(prefix = "syslog", value = { "enable" }, havingValue = "true")
+//public class SysLoggerAspect {
+//    @Autowired
+//    private MySender mySender;
+//
+//    @Pointcut("@annotation(com.diagbot.annotation.SysLogger)")
+//    public void loggerPointCut() {
+//
+//    }
+//
+//    @Before("loggerPointCut()")
+//    public void saveSysLog(JoinPoint joinPoint) {
+//        //入参设置
+//        SysLog sysLog = AopUtil.sysLoggerAspect(joinPoint, SysTypeEnum.FEEDBACK_SERVICE.getKey());
+//        //保存系统日志
+//        mySender.outputLogSend(sysLog);
+//    }
+//
+//}
+//

+ 25 - 0
src/main/java/com/diagbot/client/UserServiceClient.java

@@ -0,0 +1,25 @@
+package com.diagbot.client;
+
+import com.diagbot.client.hystrix.UserServiceHystrix;
+import com.diagbot.dto.RespDTO;
+import com.diagbot.entity.User;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestHeader;
+
+
+/**
+ * @Description: 调用用户服务
+ * @author: gaodm
+ * @time: 2018/8/6 9:52
+ */
+@FeignClient(value = "user-service", fallback = UserServiceHystrix.class)
+public interface UserServiceClient {
+
+    @PostMapping(value = "/user/{username}")
+    RespDTO<User> getUser(@RequestHeader(value = "Authorization") String token, @PathVariable("username") String username);
+}
+
+
+

+ 23 - 0
src/main/java/com/diagbot/client/hystrix/UserServiceHystrix.java

@@ -0,0 +1,23 @@
+package com.diagbot.client.hystrix;
+
+import com.diagbot.client.UserServiceClient;
+import com.diagbot.dto.RespDTO;
+import com.diagbot.entity.User;
+import org.springframework.stereotype.Component;
+
+
+/**
+ * @Description: 调用用户服务
+ * @author: gaodm
+ * @time: 2018/8/6 9:52
+ */
+@Component
+public class UserServiceHystrix implements UserServiceClient {
+
+    @Override
+    public RespDTO<User> getUser(String token, String username) {
+        System.out.println(token);
+        System.out.println(username);
+        return null;
+    }
+}

+ 19 - 0
src/main/java/com/diagbot/config/CustomAccessTokenConverter.java

@@ -0,0 +1,19 @@
+package com.diagbot.config;
+
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+@Component
+public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {
+
+    @Override
+    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
+        OAuth2Authentication authentication = super.extractAuthentication(claims);
+        authentication.setDetails(claims);
+        return authentication;
+    }
+
+}

+ 30 - 0
src/main/java/com/diagbot/config/CustomTokenEnhancer.java

@@ -0,0 +1,30 @@
+package com.diagbot.config;
+
+import com.diagbot.entity.User;
+import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.provider.token.TokenEnhancer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Description: token生成携带的信息
+ * @author: gaodm
+ * @time: 2018/9/3 15:16
+ */
+public class CustomTokenEnhancer implements TokenEnhancer {
+
+    @Override
+    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
+        final Map<String, Object> additionalInfo = new HashMap<>();
+        User user = (User) authentication.getUserAuthentication().getPrincipal();
+        additionalInfo.put("user_id", user.getId());
+        //		additionalInfo.put("username", user.getUsername());
+        //		additionalInfo.put("authorities", user.getAuthorities());
+        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
+        return accessToken;
+    }
+
+}

+ 15 - 0
src/main/java/com/diagbot/config/GlobalMethodSecurityConfigurer.java

@@ -0,0 +1,15 @@
+package com.diagbot.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+
+/**
+ * @Description: 安全配置类
+ * @author: gaodm
+ * @time: 2018/8/2 13:38
+ */
+@Configuration
+@EnableGlobalMethodSecurity(prePostEnabled = true)
+public class GlobalMethodSecurityConfigurer {
+
+}

+ 48 - 0
src/main/java/com/diagbot/config/JwtConfigurer.java

@@ -0,0 +1,48 @@
+package com.diagbot.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
+import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
+import org.springframework.util.FileCopyUtils;
+
+import java.io.IOException;
+
+/**
+ * @Description: JWT配置类
+ * @author: gaodm
+ * @time: 2018/8/2 13:38
+ */
+@Configuration
+public class JwtConfigurer {
+    @Autowired
+    private CustomAccessTokenConverter customAccessTokenConverter;
+
+    @Bean
+    @Qualifier("tokenStore")
+    public TokenStore tokenStore() {
+
+        System.out.println("Created JwtTokenStore");
+        return new JwtTokenStore(jwtTokenEnhancer());
+    }
+
+    @Bean
+    protected JwtAccessTokenConverter jwtTokenEnhancer() {
+        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
+        Resource resource = new ClassPathResource("public.cert");
+        String publicKey;
+        try {
+            publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+        converter.setVerifierKey(publicKey);
+        converter.setAccessTokenConverter(customAccessTokenConverter);
+        return converter;
+    }
+}

+ 33 - 0
src/main/java/com/diagbot/config/MybatisPlusConfigurer.java

@@ -0,0 +1,33 @@
+package com.diagbot.config;
+
+import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+
+/**
+ * @Description: MybatisPlus配置类
+ * @author: gaodm
+ * @time: 2018/8/2 13:39
+ */
+@EnableTransactionManagement
+@Configuration
+@MapperScan("com.diagbot.mapper*")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可
+public class MybatisPlusConfigurer {
+
+    /**
+     * mybatis-plus分页插件<br>
+     * 文档:http://mp.baomidou.com<br>
+     */
+    @Bean
+    public PaginationInterceptor paginationInterceptor() {
+        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
+        // 设置请求的页面大于最大页后操作,true调回到首页,false继续请求,默认false
+        //paginationInterceptor.setOverflow(false);
+        // 设置最大单页限制数量,默认500条,-1不受限制
+        paginationInterceptor.setLimit(500L);
+        return paginationInterceptor;
+    }
+
+}

+ 91 - 0
src/main/java/com/diagbot/config/OAuth2Configurer.java

@@ -0,0 +1,91 @@
+package com.diagbot.config;
+
+import com.diagbot.service.UrlUserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
+import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
+import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
+import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
+import org.springframework.security.oauth2.provider.token.TokenEnhancer;
+import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
+import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
+import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
+
+import java.util.Arrays;
+
+/**
+ * @Description: OAuth2授权认证配置类
+ * @author: gaodm
+ * @time: 2018/8/2 14:24
+ */
+@Configuration
+@EnableAuthorizationServer
+public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
+    @Autowired
+    private UrlUserService urlUserService;
+    @Override
+    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
+        clients.inMemory()
+                .withClient("uaa-service")
+                .secret("{noop}123456")
+                .scopes("service")
+                .autoApprove(true)
+                .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code")
+                .accessTokenValiditySeconds(24 * 3600)
+                .refreshTokenValiditySeconds(30 * 24 * 3600);
+    }
+
+    /**
+     * 注入自定义token生成方式
+     *
+     * @return
+     */
+    @Bean
+    public TokenEnhancer customerEnhancer() {
+        return new CustomTokenEnhancer();
+    }
+
+    @Override
+    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
+        //指定认证管理器
+        endpoints.authenticationManager(authenticationManager).userDetailsService(urlUserService);
+        //指定token存储位置
+        endpoints.tokenStore(tokenStore());
+        // 自定义token生成方式
+        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
+        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customerEnhancer(), jwtTokenEnhancer()));
+        endpoints.tokenEnhancer(tokenEnhancerChain);
+    }
+
+    @Override
+    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
+        security.tokenKeyAccess("permitAll()")
+                .checkTokenAccess("isAuthenticated()")
+                .allowFormAuthenticationForClients();
+    }
+
+    @Autowired
+    @Qualifier("authenticationManagerBean")
+    private AuthenticationManager authenticationManager;
+
+    @Bean
+    public TokenStore tokenStore() {
+        return new JwtTokenStore(jwtTokenEnhancer());
+    }
+
+    @Bean
+    protected JwtAccessTokenConverter jwtTokenEnhancer() {
+        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("diagbot-jwt.jks"), "diagbot123456".toCharArray());
+        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
+        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("diagbot-jwt"));
+        return converter;
+    }
+}

+ 112 - 0
src/main/java/com/diagbot/config/RedisConfigurer.java

@@ -0,0 +1,112 @@
+package com.diagbot.config;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cache.annotation.CachingConfigurerSupport;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
+import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
+import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
+import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+import java.time.Duration;
+
+@Configuration
+@Slf4j
+public class RedisConfigurer extends CachingConfigurerSupport {
+
+    @Value("${spring.redis.database.token}")
+    private String databaseMr;
+    @Value("${spring.redis.host}")
+    private String host;
+    @Value("${spring.redis.password}")
+    private String password;
+    @Value("${spring.redis.port}")
+    private int port;
+    @Value("${spring.redis.timeout}")
+    private int timeout;
+    @Value("${spring.redis.lettuce.pool.max-active}")
+    private int maxActive;
+    @Value("${spring.redis.lettuce.pool.max-idle}")
+    private int maxIdle;
+    @Value("${spring.redis.lettuce.pool.max-wait}")
+    private long maxWaitMillis;
+    @Value("${spring.redis.lettuce.pool.min-idle}")
+    private int minIdle;
+
+    @Bean
+    public GenericObjectPoolConfig getRedisConfig() {
+        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
+        poolConfig.setMaxTotal(maxActive);
+        poolConfig.setMaxIdle(maxIdle);
+        poolConfig.setMaxWaitMillis(maxWaitMillis);
+        poolConfig.setMinIdle(minIdle);
+        return poolConfig;
+    }
+
+
+    private Jackson2JsonRedisSerializer getSerializer() {
+        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
+        ObjectMapper om = new ObjectMapper();
+        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(om);
+        return jackson2JsonRedisSerializer;
+    }
+
+    /**
+     * Token使用的redis
+     *
+     * @return
+     */
+    @Bean("factoryForToken")
+    public LettuceConnectionFactory redisConnectionFactoryForToken() {
+        return getRedisConnectionFactory(Integer.valueOf(databaseMr));
+    }
+
+    @Bean(name = "redisTemplateForToken")
+    public RedisTemplate<String, Object> redisTemplateForToken(@Qualifier("factoryForToken") LettuceConnectionFactory factory) {
+        return getRedisTemplate(factory);
+    }
+
+
+    private LettuceConnectionFactory getRedisConnectionFactory(Integer database) {
+        RedisStandaloneConfiguration connection = new RedisStandaloneConfiguration();
+        connection.setHostName(host);
+        connection.setPort(port);
+        connection.setPassword(password);
+        connection.setDatabase(database);
+        GenericObjectPoolConfig poolConfig = getRedisConfig();
+        LettuceClientConfiguration builder = LettucePoolingClientConfiguration.builder()
+                .commandTimeout(Duration.ofMillis(timeout))
+                .poolConfig(poolConfig)
+                .shutdownTimeout(Duration.ZERO)
+                .build();
+        LettuceConnectionFactory factory = new LettuceConnectionFactory(connection, builder);
+        return factory;
+    }
+
+    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
+        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
+        redisTemplate.setConnectionFactory(factory);
+
+        // value值的序列化
+        redisTemplate.setValueSerializer(getSerializer());
+        redisTemplate.setHashValueSerializer(getSerializer());
+        // key的序列化采用StringRedisSerializer
+        redisTemplate.setKeySerializer(new StringRedisSerializer());
+        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
+        redisTemplate.afterPropertiesSet();
+        return redisTemplate;
+    }
+}
+ 

+ 42 - 0
src/main/java/com/diagbot/config/ResourceServerConfigurer.java

@@ -0,0 +1,42 @@
+package com.diagbot.config;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
+import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
+import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+
+/**
+ * @Description: 权限资源配置类
+ * @author: gaodm
+ * @time: 2018/8/2 14:21
+ */
+@Configuration
+@EnableResourceServer
+public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
+    Logger log = LoggerFactory.getLogger(ResourceServerConfigurer.class);
+
+    @Override
+    public void configure(HttpSecurity http) throws Exception {
+        http
+                .csrf().disable()
+                .authorizeRequests()
+                .regexMatchers(".*swagger.*", ".*v2.*", ".*webjars.*", "/druid.*", "/actuator.*", "/hystrix.*").permitAll()
+//                .antMatchers("/**").authenticated();
+                .antMatchers("/**").permitAll();
+    }
+
+
+    @Override
+    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
+        log.info("Configuring ResourceServerSecurityConfigurer ");
+        resources.resourceId("user-service").tokenStore(tokenStore);
+    }
+
+    @Autowired
+    TokenStore tokenStore;
+}

+ 70 - 0
src/main/java/com/diagbot/config/SwaggerConfigurer.java

@@ -0,0 +1,70 @@
+package com.diagbot.config;
+
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import springfox.documentation.builders.ApiInfoBuilder;
+import springfox.documentation.builders.ParameterBuilder;
+import springfox.documentation.builders.PathSelectors;
+import springfox.documentation.builders.RequestHandlerSelectors;
+import springfox.documentation.schema.ModelRef;
+import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
+import springfox.documentation.service.Parameter;
+import springfox.documentation.spi.DocumentationType;
+import springfox.documentation.spring.web.plugins.Docket;
+import springfox.documentation.swagger2.annotations.EnableSwagger2;
+
+import java.util.ArrayList;
+import java.util.List;
+
+
+/**
+ * @Description: Swagger配置类
+ * @author: gaodm
+ * @time: 2018/8/2 14:21
+ */
+@Configuration
+@ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true")
+@EnableSwagger2
+public class SwaggerConfigurer {
+    /**
+     * 全局参数
+     *
+     * @return
+     */
+    private List<Parameter> parameter() {
+        List<Parameter> params = new ArrayList<>();
+        params.add(new ParameterBuilder().name("Authorization")
+                .description("Authorization Bearer token")
+                .modelRef(new ModelRef("string"))
+                .parameterType("header")
+                .required(false).build());
+        return params;
+    }
+
+
+    @Bean
+    public Docket sysApi() {
+        return new Docket(DocumentationType.SWAGGER_2)
+                .apiInfo(apiInfo())
+                .select()
+                .apis(RequestHandlerSelectors.basePackage("com.diagbot.web"))
+                .paths(PathSelectors.any())
+                .build().globalOperationParameters(parameter());
+        //.securitySchemes(newArrayList(oauth()))
+        // .securityContexts(newArrayList(securityContext()));
+    }
+
+    private ApiInfo apiInfo() {
+        return new ApiInfoBuilder()
+                .title(" feedback-service api ")
+                .description("feedback-service 微服务")
+                .termsOfServiceUrl("")
+                .contact(new Contact("diagbot","",""))
+                .version("1.0")
+                .build();
+    }
+
+}

+ 69 - 0
src/main/java/com/diagbot/config/WebSecurityConfigurer.java

@@ -0,0 +1,69 @@
+package com.diagbot.config;
+
+import com.diagbot.service.UrlUserService;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.crypto.factory.PasswordEncoderFactories;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.web.AuthenticationEntryPoint;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * @Description: WebSecurity配置类
+ * @author: gaodm
+ * @time: 2018/8/2 14:24
+ */
+@Configuration
+class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
+
+    @Override
+    @Bean
+    public AuthenticationManager authenticationManagerBean() throws Exception {
+        return super.authenticationManagerBean();
+    }
+
+    @Override
+    protected void configure(HttpSecurity http) throws Exception {
+        //CSRF:因为不再依赖于Cookie,所以你就不需要考虑对CSRF(跨站请求伪造)的防范。
+        http
+                .csrf().disable()
+                .exceptionHandling()
+                // .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
+                .authenticationEntryPoint(new AuthenticationEntryPoint() {
+                    @Override
+                    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
+                        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+                    }
+                })
+                .and()
+                .authorizeRequests()
+                .regexMatchers("/actuator.*").permitAll()
+                .antMatchers("/**").authenticated()
+                .and()
+                .httpBasic();
+    }
+
+    @Bean
+    UrlUserService urlUserService() {
+        return new UrlUserService();
+    }
+
+    @Bean
+    public PasswordEncoder passwordEncoder() {
+        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
+    }
+
+    @Override
+    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+        auth.userDetailsService(urlUserService()).passwordEncoder(passwordEncoder());
+    }
+}

+ 96 - 0
src/main/java/com/diagbot/config/security/UrlAccessDecisionManager.java

@@ -0,0 +1,96 @@
+package com.diagbot.config.security;
+
+import com.diagbot.facade.TokenFacade;
+import com.diagbot.util.HttpUtils;
+import com.diagbot.util.StringUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.AccessDecisionManager;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.access.ConfigAttribute;
+import org.springframework.security.authentication.AccountExpiredException;
+import org.springframework.security.authentication.InsufficientAuthenticationException;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.web.FilterInvocation;
+import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Collection;
+
+/**
+ * @Description: 自定义权限拦截
+ * @author: gaodm
+ * @time: 2018/8/23 13:46
+ */
+@Service
+public class UrlAccessDecisionManager implements AccessDecisionManager {
+    @Autowired
+    private TokenFacade tokenFacade;
+
+    @Override
+    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
+//        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
+//        String url, method;
+//        if (matchPermitAllUrl(request)) {
+//            return;
+//        }
+//        if ("anonymousUser".equals(authentication.getPrincipal())) {
+//            throw new AccessDeniedException("no right");
+//        } else {
+//            String tokenStr = HttpUtils.getHeaders(request).get("Authorization");
+//            if (StringUtil.isNotEmpty(tokenStr)) {
+//                tokenStr = tokenStr.replaceFirst("Bearer ", "");
+//                Boolean res = tokenFacade.verifyToken(tokenStr, 1);
+//                if (!res) {
+//                    throw new AccountExpiredException("token expire");
+//                }
+//            }
+//            for (GrantedAuthority ga : authentication.getAuthorities()) {
+//                String[] authority = ga.getAuthority().split(";");
+//                url = authority[0];
+//                method = authority[1];
+//                if (matchers(url, request)) {
+//                    if (method.equals(request.getMethod()) || "ALL".equals(method)) {
+//                        return;
+//                    }
+//                }
+//            }
+//        }
+//        throw new AccessDeniedException("no right");
+    }
+
+
+    @Override
+    public boolean supports(ConfigAttribute attribute) {
+        return true;
+    }
+
+    @Override
+    public boolean supports(Class<?> clazz) {
+        return true;
+    }
+
+    private Boolean matchPermitAllUrl(HttpServletRequest request) {
+        if (matchers("/swagger/**", request)
+                || matchers("/v2/**", request)
+                || matchers("/swagger-ui.html/**", request)
+                || matchers("/swagger-resources/**", request)
+                || matchers("/webjars/**", request)
+                || matchers("/druid/**", request)
+                || matchers("/actuator/**", request)
+                || matchers("/hystrix/**", request)
+                || matchers("/", request)) {
+            return true;
+        }
+        return false;
+    }
+
+    private boolean matchers(String url, HttpServletRequest request) {
+        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
+        if (matcher.matches(request)) {
+            return true;
+        }
+        return false;
+    }
+}

+ 29 - 0
src/main/java/com/diagbot/config/security/UrlConfigAttribute.java

@@ -0,0 +1,29 @@
+package com.diagbot.config.security;
+
+import org.springframework.security.access.ConfigAttribute;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * @Description: 自定义权限拦截
+ * @author: gaodm
+ * @time: 2018/8/23 13:47
+ */
+public class UrlConfigAttribute implements ConfigAttribute {
+
+    private final HttpServletRequest httpServletRequest;
+
+    public UrlConfigAttribute(HttpServletRequest httpServletRequest) {
+        this.httpServletRequest = httpServletRequest;
+    }
+
+
+    @Override
+    public String getAttribute() {
+        return null;
+    }
+
+    public HttpServletRequest getHttpServletRequest() {
+        return httpServletRequest;
+    }
+}

+ 79 - 0
src/main/java/com/diagbot/config/security/UrlFilterSecurityInterceptor.java

@@ -0,0 +1,79 @@
+package com.diagbot.config.security;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.access.SecurityMetadataSource;
+import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
+import org.springframework.security.access.intercept.InterceptorStatusToken;
+import org.springframework.security.web.FilterInvocation;
+import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+
+/**
+ * @Description: 自定义权限拦截
+ * @author: gaodm
+ * @time: 2018/8/23 13:47
+ */
+@Service
+public class UrlFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
+
+
+    @Autowired
+    private FilterInvocationSecurityMetadataSource securityMetadataSource;
+
+    @Autowired
+    public void setUrlAccessDecisionManager(UrlAccessDecisionManager urlAccessDecisionManager) {
+        super.setAccessDecisionManager(urlAccessDecisionManager);
+    }
+
+
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+
+    }
+
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+
+        FilterInvocation fi = new FilterInvocation(request, response, chain);
+        invoke(fi);
+    }
+
+
+    public void invoke(FilterInvocation fi) throws IOException, ServletException {
+        //fi里面有一个被拦截的url
+        //里面调用UrlMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
+        //再调用UrlAccessDecisionManager的decide方法来校验用户的权限是否足够
+        InterceptorStatusToken token = super.beforeInvocation(fi);
+        try {
+            //执行下一个拦截器
+            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
+        } finally {
+            super.afterInvocation(token, null);
+        }
+    }
+
+
+    @Override
+    public void destroy() {
+
+    }
+
+    @Override
+    public Class<?> getSecureObjectClass() {
+        return FilterInvocation.class;
+
+    }
+
+    @Override
+    public SecurityMetadataSource obtainSecurityMetadataSource() {
+        return this.securityMetadataSource;
+    }
+}

+ 40 - 0
src/main/java/com/diagbot/config/security/UrlMetadataSourceService.java

@@ -0,0 +1,40 @@
+package com.diagbot.config.security;
+
+import org.springframework.security.access.ConfigAttribute;
+import org.springframework.security.web.FilterInvocation;
+import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @Description: 自定义权限拦截
+ * @author: gaodm
+ * @time: 2018/8/23 13:47
+ */
+@Service
+public class UrlMetadataSourceService implements
+        FilterInvocationSecurityMetadataSource {
+
+    @Override
+    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
+        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
+        Set<ConfigAttribute> allAttributes = new HashSet<>();
+        ConfigAttribute configAttribute = new UrlConfigAttribute(request);
+        allAttributes.add(configAttribute);
+        return allAttributes;
+    }
+
+    @Override
+    public Collection<ConfigAttribute> getAllConfigAttributes() {
+        return null;
+    }
+
+    @Override
+    public boolean supports(Class<?> clazz) {
+        return true;
+    }
+}

+ 16 - 0
src/main/java/com/diagbot/entity/JwtStore.java

@@ -0,0 +1,16 @@
+package com.diagbot.entity;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @Description:
+ * @author: gaodm
+ * @time: 2018/10/29 14:38
+ */
+@Getter
+@Setter
+public class JwtStore {
+    private String accessToken;
+    private String refreshToken;
+}

+ 172 - 0
src/main/java/com/diagbot/entity/Permission.java

@@ -0,0 +1,172 @@
+package com.diagbot.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * <p>
+ * 系统资源表
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-30
+ */
+@TableName("sys_permission")
+public class Permission implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 资源ID
+     */
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    /**
+     * 是否删除,N:未删除,Y:删除
+     */
+    private String isDeleted;
+
+    /**
+     * 记录创建时间
+     */
+    private Date gmtCreate;
+
+    /**
+     * 记录修改时间,如果时间是1970年则表示纪录未修改
+     */
+    private Date gmtModified;
+
+    /**
+     * 创建人,0表示无创建人值
+     */
+    private String creator;
+
+    /**
+     * 修改人,如果为0则表示纪录未修改
+     */
+    private String modifier;
+
+    /**
+     * 资源名称
+     */
+    private String name;
+
+    /**
+     * 资源Url
+     */
+    @TableField("permissionUrl")
+    private String permissionUrl;
+
+    /**
+     * 资源允许的请求方式
+     */
+    private String method;
+
+    /**
+     * 资源描述
+     */
+    private String descritpion;
+
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getIsDeleted() {
+        return isDeleted;
+    }
+
+    public void setIsDeleted(String isDeleted) {
+        this.isDeleted = isDeleted;
+    }
+
+    public Date getGmtCreate() {
+        return gmtCreate;
+    }
+
+    public void setGmtCreate(Date gmtCreate) {
+        this.gmtCreate = gmtCreate;
+    }
+
+    public Date getGmtModified() {
+        return gmtModified;
+    }
+
+    public void setGmtModified(Date gmtModified) {
+        this.gmtModified = gmtModified;
+    }
+
+    public String getCreator() {
+        return creator;
+    }
+
+    public void setCreator(String creator) {
+        this.creator = creator;
+    }
+
+    public String getModifier() {
+        return modifier;
+    }
+
+    public void setModifier(String modifier) {
+        this.modifier = modifier;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getPermissionUrl() {
+        return permissionUrl;
+    }
+
+    public void setPermissionUrl(String permissionUrl) {
+        this.permissionUrl = permissionUrl;
+    }
+
+    public String getMethod() {
+        return method;
+    }
+
+    public void setMethod(String method) {
+        this.method = method;
+    }
+
+    public String getDescritpion() {
+        return descritpion;
+    }
+
+    public void setDescritpion(String descritpion) {
+        this.descritpion = descritpion;
+    }
+
+    @Override
+    public String toString() {
+        return "Permission{" +
+                "id=" + id +
+                ", isDeleted=" + isDeleted +
+                ", gmtCreate=" + gmtCreate +
+                ", gmtModified=" + gmtModified +
+                ", creator=" + creator +
+                ", modifier=" + modifier +
+                ", name=" + name +
+                ", permissionUrl=" + permissionUrl +
+                ", method=" + method +
+                ", descritpion=" + descritpion +
+                "}";
+    }
+}

+ 196 - 0
src/main/java/com/diagbot/entity/SysLog.java

@@ -0,0 +1,196 @@
+package com.diagbot.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * <p>
+ * 系统操作日志表
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-09-14
+ */
+public class SysLog implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 日志ID
+     */
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    /**
+     * 是否删除,N:未删除,Y:删除
+     */
+    private String isDeleted;
+
+    /**
+     * 记录创建时间
+     */
+    private Date gmtCreate;
+
+    /**
+     * 记录修改时间,如果时间是1970年则表示纪录未修改
+     */
+    private Date gmtModified;
+
+    /**
+     * 创建人,0表示无创建人值
+     */
+    private String creator;
+
+    /**
+     * 修改人,如果为0则表示纪录未修改
+     */
+    private String modifier;
+
+    /**
+     * 访问者的IP
+     */
+    private String ip;
+
+    /**
+     * 访问的系统类型 1:user-service,2:diagbotman-service,3:uaa-service,4:log-service,5:bi-service,6:knowledge-service,7:feedback-service,8:icss-web
+     */
+    private Integer sysType;
+
+    /**
+     * 方法
+     */
+    private String method;
+
+    /**
+     * 操作名
+     */
+    private String operation;
+
+    /**
+     * 参数
+     */
+    private String params;
+
+    /**
+     * 用户名
+     */
+    private String username;
+
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getIsDeleted() {
+        return isDeleted;
+    }
+
+    public void setIsDeleted(String isDeleted) {
+        this.isDeleted = isDeleted;
+    }
+
+    public Date getGmtCreate() {
+        return gmtCreate;
+    }
+
+    public void setGmtCreate(Date gmtCreate) {
+        this.gmtCreate = gmtCreate;
+    }
+
+    public Date getGmtModified() {
+        return gmtModified;
+    }
+
+    public void setGmtModified(Date gmtModified) {
+        this.gmtModified = gmtModified;
+    }
+
+    public String getCreator() {
+        return creator;
+    }
+
+    public void setCreator(String creator) {
+        this.creator = creator;
+    }
+
+    public String getModifier() {
+        return modifier;
+    }
+
+    public void setModifier(String modifier) {
+        this.modifier = modifier;
+    }
+
+    public String getIp() {
+        return ip;
+    }
+
+    public void setIp(String ip) {
+        this.ip = ip;
+    }
+
+    public Integer getSysType() {
+        return sysType;
+    }
+
+    public void setSysType(Integer sysType) {
+        this.sysType = sysType;
+    }
+
+    public String getMethod() {
+        return method;
+    }
+
+    public void setMethod(String method) {
+        this.method = method;
+    }
+
+    public String getOperation() {
+        return operation;
+    }
+
+    public void setOperation(String operation) {
+        this.operation = operation;
+    }
+
+    public String getParams() {
+        return params;
+    }
+
+    public void setParams(String params) {
+        this.params = params;
+    }
+
+    public String getUsername() {
+        return username;
+    }
+
+    public void setUsername(String username) {
+        this.username = username;
+    }
+
+    @Override
+    public String toString() {
+        return "SysLog{" +
+                "id=" + id +
+                ", isDeleted=" + isDeleted +
+                ", gmtCreate=" + gmtCreate +
+                ", gmtModified=" + gmtModified +
+                ", creator=" + creator +
+                ", modifier=" + modifier +
+                ", ip=" + ip +
+                ", sysType=" + sysType +
+                ", method=" + method +
+                ", operation=" + operation +
+                ", params=" + params +
+                ", username=" + username +
+                "}";
+    }
+}

+ 21 - 0
src/main/java/com/diagbot/entity/Token.java

@@ -0,0 +1,21 @@
+package com.diagbot.entity;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import java.io.Serializable;
+
+/**
+ * @Description: token
+ * @Author: ztg
+ * @Date: 2018/9/19 13:14
+ */
+@Getter
+@Setter
+public class Token implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    private String token;
+
+}

+ 182 - 0
src/main/java/com/diagbot/entity/User.java

@@ -0,0 +1,182 @@
+package com.diagbot.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * <p>
+ * 系统用户表
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-30
+ */
+@TableName("sys_user")
+public class User implements UserDetails, Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 用户ID
+     */
+    @TableId(value = "id", type = IdType.AUTO)
+    private Long id;
+
+    /**
+     * 是否删除,N:未删除,Y:删除
+     */
+    private String isDeleted;
+
+    /**
+     * 记录创建时间
+     */
+    private Date gmtCreate;
+
+    /**
+     * 记录修改时间,如果时间是1970年则表示纪录未修改
+     */
+    private Date gmtModified;
+
+    /**
+     * 创建人,0表示无创建人值
+     */
+    private String creator;
+
+    /**
+     * 修改人,如果为0则表示纪录未修改
+     */
+    private String modifier;
+
+    /**
+     * 用户密码
+     */
+    private String password;
+
+    /**
+     * 用户名
+     */
+    private String username;
+
+    private List<? extends GrantedAuthority> authorities;
+
+    @Override
+    @JsonIgnore
+    public boolean isAccountNonExpired() {
+        return true;
+    }
+
+    @Override
+    @JsonIgnore
+    public boolean isAccountNonLocked() {
+        return true;
+    }
+
+    @Override
+    @JsonIgnore
+    public boolean isCredentialsNonExpired() {
+        return true;
+    }
+
+    @Override
+    @JsonIgnore
+    public boolean isEnabled() {
+        return true;
+    }
+
+    @JsonIgnore
+    public Collection<? extends GrantedAuthority> getAuthorities() {
+        return authorities;
+    }
+
+    public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) {
+        this.authorities = authorities;
+    }
+
+
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getIsDeleted() {
+        return isDeleted;
+    }
+
+    public void setIsDeleted(String isDeleted) {
+        this.isDeleted = isDeleted;
+    }
+
+    public Date getGmtCreate() {
+        return gmtCreate;
+    }
+
+    public void setGmtCreate(Date gmtCreate) {
+        this.gmtCreate = gmtCreate;
+    }
+
+    public Date getGmtModified() {
+        return gmtModified;
+    }
+
+    public void setGmtModified(Date gmtModified) {
+        this.gmtModified = gmtModified;
+    }
+
+    public String getCreator() {
+        return creator;
+    }
+
+    public void setCreator(String creator) {
+        this.creator = creator;
+    }
+
+    public String getModifier() {
+        return modifier;
+    }
+
+    public void setModifier(String modifier) {
+        this.modifier = modifier;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public String getUsername() {
+        return username;
+    }
+
+    public void setUsername(String username) {
+        this.username = username;
+    }
+
+    @Override
+    public String toString() {
+        return "User{" +
+                "id=" + id +
+                ", isDeleted=" + isDeleted +
+                ", gmtCreate=" + gmtCreate +
+                ", gmtModified=" + gmtModified +
+                ", creator=" + creator +
+                ", modifier=" + modifier +
+                ", password=" + password +
+                ", username=" + username +
+                "}";
+    }
+}

+ 81 - 0
src/main/java/com/diagbot/exception/CommonExceptionHandler.java

@@ -0,0 +1,81 @@
+package com.diagbot.exception;
+
+import com.diagbot.dto.RespDTO;
+import com.diagbot.util.GsonUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.BindException;
+import org.springframework.validation.FieldError;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.MissingServletRequestParameterException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+/**
+ * @Description: 错误通用处理
+ * @author: gaodm
+ * @time: 2018/8/2 14:22
+ */
+@ControllerAdvice
+@ResponseBody
+@Slf4j
+public class CommonExceptionHandler {
+
+    @ExceptionHandler(Exception.class)
+    public ResponseEntity<RespDTO> handleException(Exception e) {
+        RespDTO resp = new RespDTO();
+        if (e instanceof BindException) {
+            BindException ex = (BindException) e;
+            Map<String, String> stringMap = new HashMap<>();
+            for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
+                stringMap.put(fieldError.getField(), fieldError.getDefaultMessage());
+            }
+            String msg = GsonUtil.toJson(stringMap);
+            log.warn("【参数异常】:{}", msg);
+            resp.code = CommonErrorCode.PARAM_ERROR.getCode();
+            resp.msg = msg;
+            return new ResponseEntity(resp, HttpStatus.OK);
+        }
+        if (e instanceof MethodArgumentNotValidException) {
+            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
+            Map<String, String> stringMap = new HashMap<>();
+            for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
+                stringMap.put(fieldError.getField(), fieldError.getDefaultMessage());
+            }
+            String msg = GsonUtil.toJson(stringMap);
+            log.warn("【参数异常】:{}", msg);
+            resp.code = CommonErrorCode.PARAM_ERROR.getCode();
+            resp.msg = msg;
+            return new ResponseEntity(resp, HttpStatus.OK);
+        }
+        if (e instanceof MissingServletRequestParameterException) {
+            MissingServletRequestParameterException ex = (MissingServletRequestParameterException) e;
+            Map<String, String> stringMap = new HashMap<>();
+            stringMap.put(ex.getParameterName(), "不能为null");
+            String msg = GsonUtil.toJson(stringMap);
+            log.warn("【参数异常】:{}", msg);
+            resp.code = CommonErrorCode.PARAM_ERROR.getCode();
+            resp.msg = msg;
+            return new ResponseEntity(resp, HttpStatus.OK);
+        }
+        if (e instanceof CommonException) {
+            CommonException taiChiException = (CommonException) e;
+            resp.code = taiChiException.getCode();
+            resp.msg = e.getMessage();
+            log.error("【业务异常】:{}", e.getMessage());
+            return new ResponseEntity(resp, HttpStatus.OK);
+        }
+        resp.code = CommonErrorCode.FAIL.getCode();
+        resp.msg = e.getMessage();
+        log.error("【系统异常】:{}", e.getMessage());
+        e.printStackTrace();
+        return new ResponseEntity(resp, HttpStatus.OK);
+    }
+
+}

+ 39 - 0
src/main/java/com/diagbot/exception/ServiceErrorCode.java

@@ -0,0 +1,39 @@
+package com.diagbot.exception;
+
+/**
+ * @Description: 本服务错误码
+ * 系统码(3位) + 等级码(1位) + 4位顺序号
+ * 系统码 通用码 000;用户中心 100; 管理中心 200;
+ * @author: gaodm
+ * @time: 2018/9/10 11:11
+ */
+public enum ServiceErrorCode implements ErrorCode {
+    LOG_IS_NOT_EXIST("90020001", "该日志不存在");
+
+    private String code;
+    private String msg;
+
+
+    ServiceErrorCode(String code, String msg) {
+        this.code = code;
+        this.msg = msg;
+    }
+
+
+    public String getCode() {
+        return code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public static ServiceErrorCode codeOf(String code) {
+        for (ServiceErrorCode state : values()) {
+            if (state.getCode() == code) {
+                return state;
+            }
+        }
+        return null;
+    }
+}

+ 13 - 0
src/main/java/com/diagbot/facade/SysLogFacade.java

@@ -0,0 +1,13 @@
+package com.diagbot.facade;
+
+import com.diagbot.service.impl.SysLogServiceImpl;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Description: 用户日志业务层
+ * @author: gaodm
+ * @time: 2018/8/6 9:11
+ */
+@Component
+public class SysLogFacade extends SysLogServiceImpl {
+}

+ 13 - 0
src/main/java/com/diagbot/facade/TokenFacade.java

@@ -0,0 +1,13 @@
+package com.diagbot.facade;
+
+import com.diagbot.service.impl.TokenServiceImpl;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Description: token实现
+ * @author: gaodm
+ * @time: 2018/10/29 14:24
+ */
+@Component
+public class TokenFacade extends TokenServiceImpl {
+}

+ 18 - 0
src/main/java/com/diagbot/mapper/PermissionMapper.java

@@ -0,0 +1,18 @@
+package com.diagbot.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.diagbot.entity.Permission;
+
+import java.util.List;
+
+/**
+ * <p>
+ * Mapper 接口
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-22
+ */
+public interface PermissionMapper extends BaseMapper<Permission> {
+    List<Permission> getByUserId(Long userId);
+}

+ 16 - 0
src/main/java/com/diagbot/mapper/SysLogMapper.java

@@ -0,0 +1,16 @@
+package com.diagbot.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.diagbot.entity.SysLog;
+
+/**
+ * <p>
+ * Mapper 接口
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-02
+ */
+public interface SysLogMapper extends BaseMapper<SysLog> {
+
+}

+ 16 - 0
src/main/java/com/diagbot/mapper/UserMapper.java

@@ -0,0 +1,16 @@
+package com.diagbot.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.diagbot.entity.User;
+
+/**
+ * <p>
+ * Mapper 接口
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-02
+ */
+public interface UserMapper extends BaseMapper<User> {
+    User getByUserName(String username);
+}

+ 15 - 0
src/main/java/com/diagbot/service/SysLogService.java

@@ -0,0 +1,15 @@
+package com.diagbot.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.diagbot.entity.SysLog;
+
+/**
+ * <p>
+ * 服务类
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-02
+ */
+public interface SysLogService extends IService<SysLog> {
+}

+ 35 - 0
src/main/java/com/diagbot/service/TokenService.java

@@ -0,0 +1,35 @@
+package com.diagbot.service;
+
+import com.diagbot.entity.JwtStore;
+
+/**
+ * @Description: Token验证类
+ * @author: gaodm
+ * @time: 2018/10/29 13:35
+ */
+public interface TokenService {
+
+    /**
+     * 创建token
+     *
+     * @param token 用户token
+     * @return
+     */
+    Boolean createToken(JwtStore token);
+
+    /**
+     * 验证token是否有效
+     *
+     * @param token 待验证的token
+     * @param type  1:accessToken,2:refreshToken
+     * @return
+     */
+    Boolean verifyToken(String token, Integer type);
+
+    /**
+     *  删除用户token
+     * @param userId 用户ID
+     * @return 删除是否成功
+     */
+    Boolean deleteToken(String userId);
+}

+ 40 - 0
src/main/java/com/diagbot/service/UrlGrantedAuthority.java

@@ -0,0 +1,40 @@
+package com.diagbot.service;
+
+import org.springframework.security.core.GrantedAuthority;
+
+/**
+ * @Description: 自定义权限信息
+ * @author: gaodm
+ * @time: 2018/8/23 14:09
+ */
+public class UrlGrantedAuthority implements GrantedAuthority {
+
+    private String permissionUrl;
+    private String method;
+
+    public String getPermissionUrl() {
+        return permissionUrl;
+    }
+
+    public void setPermissionUrl(String permissionUrl) {
+        this.permissionUrl = permissionUrl;
+    }
+
+    public String getMethod() {
+        return method;
+    }
+
+    public void setMethod(String method) {
+        this.method = method;
+    }
+
+    public UrlGrantedAuthority(String permissionUrl, String method) {
+        this.permissionUrl = permissionUrl;
+        this.method = method;
+    }
+
+    @Override
+    public String getAuthority() {
+        return this.permissionUrl + ";" + this.method;
+    }
+}

+ 50 - 0
src/main/java/com/diagbot/service/UrlUserService.java

@@ -0,0 +1,50 @@
+package com.diagbot.service;
+
+import com.diagbot.entity.Permission;
+import com.diagbot.entity.User;
+import com.diagbot.mapper.PermissionMapper;
+import com.diagbot.mapper.UserMapper;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @Description: 用户权限信息获取
+ * @author: gaodm
+ * @time: 2018/8/23 11:39
+ */
+@Service
+public class UrlUserService implements UserDetailsService {
+    @Autowired
+    UserMapper userMapper;
+    @Autowired
+    PermissionMapper permissionMapper;
+
+    @Override
+    public UserDetails loadUserByUsername(String userName) { //重写loadUserByUsername 方法获得 userdetails 类型用户
+
+        User user = userMapper.getByUserName(userName);
+        if (user != null) {
+            List<Permission> permissions = permissionMapper.getByUserId(user.getId());
+            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
+            for (Permission permission : permissions) {
+                if (null != permission && StringUtils.isNotBlank(permission.getPermissionUrl())) {
+                    GrantedAuthority grantedAuthority
+                            = new UrlGrantedAuthority(permission.getPermissionUrl(), permission.getMethod());
+                    grantedAuthorities.add(grantedAuthority);
+                }
+            }
+            user.setGrantedAuthorities(grantedAuthorities);
+            return user;
+        } else {
+            throw new UsernameNotFoundException("admin: " + userName + " do not exist");
+        }
+    }
+}

+ 19 - 0
src/main/java/com/diagbot/service/impl/SysLogServiceImpl.java

@@ -0,0 +1,19 @@
+package com.diagbot.service.impl;
+
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.diagbot.entity.SysLog;
+import com.diagbot.mapper.SysLogMapper;
+import com.diagbot.service.SysLogService;
+import org.springframework.stereotype.Service;
+
+/**
+ * <p>
+ * 服务实现类
+ * </p>
+ *
+ * @author gaodm
+ * @since 2018-08-02
+ */
+@Service
+public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {
+}

+ 146 - 0
src/main/java/com/diagbot/service/impl/TokenServiceImpl.java

@@ -0,0 +1,146 @@
+package com.diagbot.service.impl;
+
+import com.auth0.jwt.interfaces.Claim;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import com.diagbot.entity.JwtStore;
+import com.diagbot.service.TokenService;
+import com.diagbot.util.DateUtil;
+import com.diagbot.util.JwtUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.dao.DataAccessException;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.core.RedisCallback;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * @Description: Token验证类 实现
+ * @author: gaodm
+ * @time: 2018/10/29 13:34
+ */
+@Slf4j
+@Service
+public class TokenServiceImpl implements TokenService {
+
+    @Autowired
+    @Qualifier("redisTemplateForToken")
+    RedisTemplate redisForToken;
+
+    private byte[] serializeKey(Object o) {
+        return redisForToken.getKeySerializer().serialize(o);
+    }
+
+    private byte[] serializeValue(Object o) {
+        return redisForToken.getValueSerializer().serialize(o);
+    }
+
+    private Object deserializeValue(byte[] b) {
+        return redisForToken.getValueSerializer().deserialize(b);
+    }
+
+    private byte[] getUserTokenKey(String userId) {
+        String userTokensFormat = "user_tokens_%s";
+        return serializeKey(String.format(userTokensFormat, userId));
+    }
+
+    /**
+     * 创建token
+     *
+     * @param token 用户token
+     * @return
+     */
+    @Override
+    public Boolean createToken(JwtStore token) {
+        DecodedJWT jwt = JwtUtil.decodedJWT(token.getRefreshToken());
+        Map<String, Claim> claims = jwt.getClaims();
+        String userId = claims.get("user_id").asInt().toString();
+        Date expDate = claims.get("exp").asDate();
+        final byte[] redis_key = getUserTokenKey(userId);
+        redisForToken.execute(new RedisCallback<Object>() {
+            @Override
+            public Object doInRedis(RedisConnection connection) throws DataAccessException {
+                //获取旧的
+                byte[] bytes = connection.get(redis_key);
+                //删除旧的
+                if (bytes != null) {
+                    connection.del(bytes);
+                }
+                //设置新的
+                connection.setEx(
+                        redis_key,
+                        (expDate.getTime() - DateUtil.now().getTime()) / 1000,
+                        serializeValue(token)
+                );
+                return true;
+            }
+        });
+        return true;
+    }
+
+    /**
+     * 验证token是否有效
+     *
+     * @param token 待验证的token
+     * @param type  1:accessToken,2:refreshToken
+     * @return
+     */
+    @Override
+    public Boolean verifyToken(String token, Integer type) {
+        Boolean res = false;
+        if (null == token) {
+            return false;
+        }
+        String userId = JwtUtil.getUserId(token);
+        //从redis中取出
+        final byte[] redis_key = getUserTokenKey(userId);
+        JwtStore tokenStore = (JwtStore) redisForToken.execute(new RedisCallback<JwtStore>() {
+            @Override
+            public JwtStore doInRedis(RedisConnection connection) throws DataAccessException {
+                byte[] bytes = connection.get(redis_key);
+                if (bytes == null) {
+                    return null;
+                }
+                return (JwtStore) deserializeValue(bytes);
+            }
+        });
+
+        if (null != tokenStore) {
+            if (type == 1) {
+                if (null != tokenStore.getAccessToken() && tokenStore.getAccessToken().equals(token)) {
+                    res = true;
+                }
+            }
+
+            if (type == 2) {
+                if (null != tokenStore.getRefreshToken() && tokenStore.getRefreshToken().equals(token)) {
+                    res = true;
+                }
+            }
+        }
+
+        return res;
+    }
+
+    /**
+     * 删除用户token
+     *
+     * @param userId 用户ID
+     * @return 删除是否成功
+     */
+    @Override
+    public Boolean deleteToken(String userId) {
+        final byte[] redis_key = getUserTokenKey(userId);
+        Long l = (Long) redisForToken.execute(new RedisCallback<Long>() {
+            @Override
+            public Long doInRedis(RedisConnection connection) throws DataAccessException {
+                return connection.del(redis_key);
+            }
+        });
+        return l > 0;
+    }
+}

+ 21 - 0
src/main/java/com/diagbot/vo/SysLogVo.java

@@ -0,0 +1,21 @@
+package com.diagbot.vo;
+
+import lombok.Getter;
+import lombok.Setter;
+
+import java.util.Date;
+
+/**
+ * @Description:
+ * @author: gaodm
+ * @time: 2018/8/6 10:16
+ */
+@Getter
+@Setter
+public class SysLogVo {
+    private Date createDate;
+    private String ip;
+    private String method;
+    private String operation;
+    private String params;
+}

+ 110 - 0
src/main/java/com/diagbot/web/SysLogController.java

@@ -0,0 +1,110 @@
+package com.diagbot.web;
+
+
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
+import com.diagbot.annotation.SysLogger;
+import com.diagbot.dto.RespDTO;
+import com.diagbot.entity.SysLog;
+import com.diagbot.facade.SysLogFacade;
+import com.diagbot.vo.SysLogVo;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.Date;
+
+/**
+ * @Description: 日志操作控制层
+ * @author: gaodm
+ * @time: 2018/8/30 10:12
+ */
+@RestController
+@RequestMapping("/log")
+public class SysLogController {
+
+    @Autowired
+    private SysLogFacade sysLogFacade;
+
+    /**
+     * 新增日志信息
+     *
+     * @param sysLogVo 新增日志输入参数
+     * @return 新增日志是否成功
+     */
+    @ApiOperation(value = "添加日志", notes = "添加日志")
+    @PostMapping("/add")
+    @SysLogger("postLog")
+    public RespDTO add(@RequestBody SysLogVo sysLogVo) {
+        //初始化新增日志信息
+        SysLog sysLog = new SysLog();
+        sysLog.setGmtCreate(new Date());
+        sysLog.setIp(sysLogVo.getIp());
+        sysLog.setMethod(sysLogVo.getMethod());
+        sysLog.setOperation(sysLogVo.getOperation());
+        sysLog.setParams(sysLogVo.getParams());
+        return RespDTO.onSuc(sysLogFacade.save(sysLog) ? "添加成功" : "添加失败");
+    }
+
+    /**
+     * 删除日志
+     *
+     * @param id 日志信息ID
+     * @return 删除是否成功
+     */
+    @ApiOperation(value = "删除日志", notes = "删除日志")
+    @DeleteMapping("/delete/{id}")
+    @SysLogger("deleteLog")
+    public RespDTO delete(@PathVariable(value = "id") Integer id) {
+        return RespDTO.onSuc(sysLogFacade.removeById(id) ? "删除成功" : "删除失败");
+    }
+
+    /**
+     * 修改日志
+     *
+     * @param sysLog 修改日志输入参数
+     * @return 修改是否成功
+     */
+    @ApiOperation(value = "修改日志", notes = "修改日志")
+    @PostMapping("/update")
+    @SysLogger("updateLog")
+    public RespDTO update(@RequestBody SysLog sysLog) {
+        return RespDTO.onSuc(sysLogFacade.updateById(sysLog) ? "修改成功" : "修改失败");
+    }
+
+    /**
+     * 获取日志列表
+     *
+     * @return 日志列信息
+     */
+    @ApiOperation(value = "获取日志列表", notes = "获取日志列表")
+    @GetMapping("/list")
+    @SysLogger("listLog")
+    public RespDTO list() {
+        Wrapper<SysLog> wrapper = new QueryWrapper<>();
+        return RespDTO.onSuc(sysLogFacade.list(wrapper));
+    }
+
+    /**
+     * 获取日志翻页信息
+     *
+     * @return 日志翻页信息
+     */
+    @ApiOperation(value = "获取日志翻页信息", notes = "获取日志翻页信息")
+    @GetMapping("/page")
+    @SysLogger("pageLog")
+    public RespDTO page() {
+        //初始化日志翻页参数
+        IPage<SysLog> wrapper = new Page<>();
+        return RespDTO.onSuc(sysLogFacade.page(wrapper, null));
+    }
+}
+

+ 153 - 0
src/main/resources/application-dev.yml

@@ -0,0 +1,153 @@
+server:
+  port: 5858
+  max-http-header-size: 10MB
+
+hystrix:
+  threadpool:
+    default:
+      coreSize: 200 #并发执行的最大线程数,默认10
+      maxQueueSize: 200 #BlockingQueue的最大队列数
+      queueSizeRejectionThreshold: 50 #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝
+  command:
+    default:
+      execution:
+        timeout:
+          enabled: true
+        isolation:
+          strategy: SEMAPHORE
+          semaphore:
+            maxConcurrentRequests: 2000
+          thread:
+            timeoutInMilliseconds: 20000
+
+ribbon:
+  ReadTimeout: 20000
+  ConnectTimeout: 20000
+  MaxAutoRetries: 0
+  MaxAutoRetriesNextServer: 1
+
+feign:
+  hystrix:
+    enabled: true
+  #开启Feign请求压缩
+  compression:
+    response:
+      enabled: true
+  httpclient:
+    enabled: false
+  okhttp:
+    enabled: true
+    max-connections: 1000 # 默认值
+    max-connections-per-route: 250 # 默认值
+
+management:
+  endpoints:
+    web:
+      exposure:
+        include: bus-refresh,health,info,hystrix.stream
+      cors:
+        allowed-origins: "*"
+        allowed-methods: "*"
+  endpoint:
+    health:
+      show-details: always
+
+# 驱动配置信息
+spring:
+  datasource:
+    druid:
+      driver-class-name: com.mysql.cj.jdbc.Driver
+      platform: mysql
+      url: jdbc:mysql://192.168.2.236:3306/sys-mrqcneo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
+      username: root
+      password: lantone
+      # 连接池的配置信息
+      # 初始化大小,最小,最大
+      initialSize: 5
+      minIdle: 5
+      maxActive: 20
+      # 配置获取连接等待超时的时间
+      maxWait: 60000
+      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
+      timeBetweenEvictionRunsMillis: 60000
+      # 配置一个连接在池中最小生存的时间,单位是毫秒
+      minEvictableIdleTimeMillis: 300000
+      validationQuery: SELECT 1 FROM DUAL
+      testWhileIdle: true
+      testOnBorrow: false
+      testOnReturn: false
+      # 打开PSCache,并且指定每个连接上PSCache的大小
+      poolPreparedStatements: true
+      maxPoolPreparedStatementPerConnectionSize: 20
+      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
+      filters.commons-log.connection-logger-name: wall,log4j
+      filter:
+        stat:
+          enabled: true
+          mergeSql: true
+          log-slow-sql: true
+          slow-sql-millis: 2000
+      #监控配置
+      web-stat-filter:
+        enabled: true
+        url-pattern: /*
+        exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
+
+      # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
+      stat-view-servlet:
+        enabled: true
+        url-pattern: /druid/*
+        reset-enable: false
+        login-username: root
+        login-password: root
+
+  jackson:
+    date-format: yyyy-MM-dd HH:mm:ss
+    time-zone: GMT+8
+
+  #redis
+  redis:
+    database:
+      token: 8 # Token索引
+    host: 192.168.2.236  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
+#mybatis
+mybatis-plus:
+  mapper-locations: classpath:/mapper/*Mapper.xml
+  #实体扫描,多个package用逗号或者分号分隔
+  typeAliasesPackage: com.diagbot.entity
+  global-config:
+    #刷新mapper 调试神器
+    db-config:
+      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
+      id-type: id_worker
+      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
+      field-strategy: not_empty
+      #驼峰下划线转换
+      column-underline: true
+      #数据库大写下划线转换
+      #capital-mode: true
+      #刷新mapper 调试神器
+      refresh-mapper: true
+      #逻辑删除配置
+      logic-delete-value: 0
+      logic-not-delete-value: 1
+      #自定义填充策略接口实现
+      #meta-object-handler: com.baomidou.springboot.xxx
+      #自定义SQL注入器
+      #sql-injector: com.baomidou.springboot.xxx
+  configuration:
+    map-underscore-to-camel-case: true
+    cache-enabled: false
+
+swagger:
+  enable: true

+ 153 - 0
src/main/resources/application-local.yml

@@ -0,0 +1,153 @@
+server:
+  port: 5858
+  max-http-header-size: 10MB
+
+hystrix:
+  threadpool:
+    default:
+      coreSize: 200 #并发执行的最大线程数,默认10
+      maxQueueSize: 200 #BlockingQueue的最大队列数
+      queueSizeRejectionThreshold: 50 #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝
+  command:
+    default:
+      execution:
+        timeout:
+          enabled: true
+        isolation:
+          strategy: SEMAPHORE
+          semaphore:
+            maxConcurrentRequests: 2000
+          thread:
+            timeoutInMilliseconds: 20000
+
+ribbon:
+  ReadTimeout: 20000
+  ConnectTimeout: 20000
+  MaxAutoRetries: 0
+  MaxAutoRetriesNextServer: 1
+
+feign:
+  hystrix:
+    enabled: true
+  #开启Feign请求压缩
+  compression:
+    response:
+      enabled: true
+  httpclient:
+    enabled: false
+  okhttp:
+    enabled: true
+    max-connections: 1000 # 默认值
+    max-connections-per-route: 250 # 默认值
+
+management:
+  endpoints:
+    web:
+      exposure:
+        include: bus-refresh,health,info,hystrix.stream
+      cors:
+        allowed-origins: "*"
+        allowed-methods: "*"
+  endpoint:
+    health:
+      show-details: always
+
+# 驱动配置信息
+spring:
+  datasource:
+    druid:
+      driver-class-name: com.mysql.cj.jdbc.Driver
+      platform: mysql
+      url: jdbc:mysql://192.168.2.236:3306/sys-mrqcneo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
+      username: root
+      password: lantone
+      # 连接池的配置信息
+      # 初始化大小,最小,最大
+      initialSize: 5
+      minIdle: 5
+      maxActive: 20
+      # 配置获取连接等待超时的时间
+      maxWait: 60000
+      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
+      timeBetweenEvictionRunsMillis: 60000
+      # 配置一个连接在池中最小生存的时间,单位是毫秒
+      minEvictableIdleTimeMillis: 300000
+      validationQuery: SELECT 1 FROM DUAL
+      testWhileIdle: true
+      testOnBorrow: false
+      testOnReturn: false
+      # 打开PSCache,并且指定每个连接上PSCache的大小
+      poolPreparedStatements: true
+      maxPoolPreparedStatementPerConnectionSize: 20
+      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
+      filters.commons-log.connection-logger-name: wall,log4j
+      filter:
+        stat:
+          enabled: true
+          mergeSql: true
+          log-slow-sql: true
+          slow-sql-millis: 2000
+      #监控配置
+      web-stat-filter:
+        enabled: true
+        url-pattern: /*
+        exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
+
+      # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
+      stat-view-servlet:
+        enabled: true
+        url-pattern: /druid/*
+        reset-enable: false
+        login-username: root
+        login-password: root
+
+  jackson:
+    date-format: yyyy-MM-dd HH:mm:ss
+    time-zone: GMT+8
+
+  #redis
+  redis:
+    database:
+      token: 8 # Token索引
+    host: 192.168.2.236  #Redis服务器地址
+    port: 6378 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
+#mybatis
+mybatis-plus:
+  mapper-locations: classpath:/mapper/*Mapper.xml
+  #实体扫描,多个package用逗号或者分号分隔
+  typeAliasesPackage: com.diagbot.entity
+  global-config:
+    #刷新mapper 调试神器
+    db-config:
+      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
+      id-type: id_worker
+      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
+      field-strategy: not_empty
+      #驼峰下划线转换
+      column-underline: true
+      #数据库大写下划线转换
+      #capital-mode: true
+      #刷新mapper 调试神器
+      refresh-mapper: true
+      #逻辑删除配置
+      logic-delete-value: 0
+      logic-not-delete-value: 1
+      #自定义填充策略接口实现
+      #meta-object-handler: com.baomidou.springboot.xxx
+      #自定义SQL注入器
+      #sql-injector: com.baomidou.springboot.xxx
+  configuration:
+    map-underscore-to-camel-case: true
+    cache-enabled: false
+
+swagger:
+  enable: true

+ 153 - 0
src/main/resources/application-pre.yml

@@ -0,0 +1,153 @@
+server:
+  port: 5858
+  max-http-header-size: 10MB
+
+hystrix:
+  threadpool:
+    default:
+      coreSize: 200 #并发执行的最大线程数,默认10
+      maxQueueSize: 200 #BlockingQueue的最大队列数
+      queueSizeRejectionThreshold: 50 #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝
+  command:
+    default:
+      execution:
+        timeout:
+          enabled: true
+        isolation:
+          strategy: SEMAPHORE
+          semaphore:
+            maxConcurrentRequests: 2000
+          thread:
+            timeoutInMilliseconds: 20000
+
+ribbon:
+  ReadTimeout: 20000
+  ConnectTimeout: 20000
+  MaxAutoRetries: 0
+  MaxAutoRetriesNextServer: 1
+
+feign:
+  hystrix:
+    enabled: true
+  #开启Feign请求压缩
+  compression:
+    response:
+      enabled: true
+  httpclient:
+    enabled: false
+  okhttp:
+    enabled: true
+    max-connections: 1000 # 默认值
+    max-connections-per-route: 250 # 默认值
+
+management:
+  endpoints:
+    web:
+      exposure:
+        include: bus-refresh,health,info,hystrix.stream
+      cors:
+        allowed-origins: "*"
+        allowed-methods: "*"
+  endpoint:
+    health:
+      show-details: always
+
+# 驱动配置信息
+spring:
+  datasource:
+    druid:
+      driver-class-name: com.mysql.cj.jdbc.Driver
+      platform: mysql
+      url: jdbc:mysql://192.168.2.121:3306/sys-mrqcneo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
+      username: teamback
+      password: goTulmLeon
+      # 连接池的配置信息
+      # 初始化大小,最小,最大
+      initialSize: 5
+      minIdle: 5
+      maxActive: 20
+      # 配置获取连接等待超时的时间
+      maxWait: 60000
+      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
+      timeBetweenEvictionRunsMillis: 60000
+      # 配置一个连接在池中最小生存的时间,单位是毫秒
+      minEvictableIdleTimeMillis: 300000
+      validationQuery: SELECT 1 FROM DUAL
+      testWhileIdle: true
+      testOnBorrow: false
+      testOnReturn: false
+      # 打开PSCache,并且指定每个连接上PSCache的大小
+      poolPreparedStatements: true
+      maxPoolPreparedStatementPerConnectionSize: 20
+      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
+      filters.commons-log.connection-logger-name: wall,log4j
+      filter:
+        stat:
+          enabled: true
+          mergeSql: true
+          log-slow-sql: true
+          slow-sql-millis: 2000
+      #监控配置
+      web-stat-filter:
+        enabled: true
+        url-pattern: /*
+        exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
+
+      # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
+      stat-view-servlet:
+        enabled: true
+        url-pattern: /druid/*
+        reset-enable: false
+        login-username: root
+        login-password: root
+
+  jackson:
+    date-format: yyyy-MM-dd HH:mm:ss
+    time-zone: GMT+8
+
+  #redis
+  redis:
+    database:
+      token: 8 # Token索引
+    host: 192.168.2.121  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
+#mybatis
+mybatis-plus:
+  mapper-locations: classpath:/mapper/*Mapper.xml
+  #实体扫描,多个package用逗号或者分号分隔
+  typeAliasesPackage: com.diagbot.entity
+  global-config:
+    #刷新mapper 调试神器
+    db-config:
+      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
+      id-type: id_worker
+      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
+      field-strategy: not_empty
+      #驼峰下划线转换
+      column-underline: true
+      #数据库大写下划线转换
+      #capital-mode: true
+      #刷新mapper 调试神器
+      refresh-mapper: true
+      #逻辑删除配置
+      logic-delete-value: 0
+      logic-not-delete-value: 1
+      #自定义填充策略接口实现
+      #meta-object-handler: com.baomidou.springboot.xxx
+      #自定义SQL注入器
+      #sql-injector: com.baomidou.springboot.xxx
+  configuration:
+    map-underscore-to-camel-case: true
+    cache-enabled: false
+
+swagger:
+  enable: true

+ 153 - 0
src/main/resources/application-pro.yml

@@ -0,0 +1,153 @@
+server:
+  port: 5858
+  max-http-header-size: 10MB
+
+hystrix:
+  threadpool:
+    default:
+      coreSize: 200 #并发执行的最大线程数,默认10
+      maxQueueSize: 200 #BlockingQueue的最大队列数
+      queueSizeRejectionThreshold: 50 #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝
+  command:
+    default:
+      execution:
+        timeout:
+          enabled: true
+        isolation:
+          strategy: SEMAPHORE
+          semaphore:
+            maxConcurrentRequests: 2000
+          thread:
+            timeoutInMilliseconds: 20000
+
+ribbon:
+  ReadTimeout: 20000
+  ConnectTimeout: 20000
+  MaxAutoRetries: 0
+  MaxAutoRetriesNextServer: 1
+
+feign:
+  hystrix:
+    enabled: true
+  #开启Feign请求压缩
+  compression:
+    response:
+      enabled: true
+  httpclient:
+    enabled: false
+  okhttp:
+    enabled: true
+    max-connections: 1000 # 默认值
+    max-connections-per-route: 250 # 默认值
+
+management:
+  endpoints:
+    web:
+      exposure:
+        include: bus-refresh,health,info,hystrix.stream
+      cors:
+        allowed-origins: "*"
+        allowed-methods: "*"
+  endpoint:
+    health:
+      show-details: always
+
+# 驱动配置信息
+spring:
+  datasource:
+    druid:
+      driver-class-name: com.mysql.cj.jdbc.Driver
+      platform: mysql
+      url: jdbc:mysql://192.168.2.122:3306/sys-mrqcneo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
+      username: root
+      password: lantone
+      # 连接池的配置信息
+      # 初始化大小,最小,最大
+      initialSize: 5
+      minIdle: 5
+      maxActive: 20
+      # 配置获取连接等待超时的时间
+      maxWait: 60000
+      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
+      timeBetweenEvictionRunsMillis: 60000
+      # 配置一个连接在池中最小生存的时间,单位是毫秒
+      minEvictableIdleTimeMillis: 300000
+      validationQuery: SELECT 1 FROM DUAL
+      testWhileIdle: true
+      testOnBorrow: false
+      testOnReturn: false
+      # 打开PSCache,并且指定每个连接上PSCache的大小
+      poolPreparedStatements: true
+      maxPoolPreparedStatementPerConnectionSize: 20
+      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
+      filters.commons-log.connection-logger-name: wall,log4j
+      filter:
+        stat:
+          enabled: true
+          mergeSql: true
+          log-slow-sql: true
+          slow-sql-millis: 2000
+      #监控配置
+      web-stat-filter:
+        enabled: true
+        url-pattern: /*
+        exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
+
+      # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
+      stat-view-servlet:
+        enabled: true
+        url-pattern: /druid/*
+        reset-enable: false
+        login-username: root
+        login-password: root
+
+  jackson:
+    date-format: yyyy-MM-dd HH:mm:ss
+    time-zone: GMT+8
+
+  #redis
+  redis:
+    database:
+      token: 8 # Token索引
+    host: 192.168.2.122  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
+#mybatis
+mybatis-plus:
+  mapper-locations: classpath:/mapper/*Mapper.xml
+  #实体扫描,多个package用逗号或者分号分隔
+  typeAliasesPackage: com.diagbot.entity
+  global-config:
+    #刷新mapper 调试神器
+    db-config:
+      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
+      id-type: id_worker
+      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
+      field-strategy: not_empty
+      #驼峰下划线转换
+      column-underline: true
+      #数据库大写下划线转换
+      #capital-mode: true
+      #刷新mapper 调试神器
+      refresh-mapper: true
+      #逻辑删除配置
+      logic-delete-value: 0
+      logic-not-delete-value: 1
+      #自定义填充策略接口实现
+      #meta-object-handler: com.baomidou.springboot.xxx
+      #自定义SQL注入器
+      #sql-injector: com.baomidou.springboot.xxx
+  configuration:
+    map-underscore-to-camel-case: true
+    cache-enabled: false
+
+swagger:
+  enable: true

+ 153 - 0
src/main/resources/application-test.yml

@@ -0,0 +1,153 @@
+server:
+  port: 5858
+  max-http-header-size: 10MB
+
+hystrix:
+  threadpool:
+    default:
+      coreSize: 200 #并发执行的最大线程数,默认10
+      maxQueueSize: 200 #BlockingQueue的最大队列数
+      queueSizeRejectionThreshold: 50 #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝
+  command:
+    default:
+      execution:
+        timeout:
+          enabled: true
+        isolation:
+          strategy: SEMAPHORE
+          semaphore:
+            maxConcurrentRequests: 2000
+          thread:
+            timeoutInMilliseconds: 20000
+
+ribbon:
+  ReadTimeout: 20000
+  ConnectTimeout: 20000
+  MaxAutoRetries: 0
+  MaxAutoRetriesNextServer: 1
+
+feign:
+  hystrix:
+    enabled: true
+  #开启Feign请求压缩
+  compression:
+    response:
+      enabled: true
+  httpclient:
+    enabled: false
+  okhttp:
+    enabled: true
+    max-connections: 1000 # 默认值
+    max-connections-per-route: 250 # 默认值
+
+management:
+  endpoints:
+    web:
+      exposure:
+        include: bus-refresh,health,info,hystrix.stream
+      cors:
+        allowed-origins: "*"
+        allowed-methods: "*"
+  endpoint:
+    health:
+      show-details: always
+
+# 驱动配置信息
+spring:
+  datasource:
+    druid:
+      driver-class-name: com.mysql.cj.jdbc.Driver
+      platform: mysql
+      url: jdbc:mysql://192.168.2.241:3306/sys-mrqcneo?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false
+      username: root
+      password: lantone
+      # 连接池的配置信息
+      # 初始化大小,最小,最大
+      initialSize: 5
+      minIdle: 5
+      maxActive: 20
+      # 配置获取连接等待超时的时间
+      maxWait: 60000
+      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
+      timeBetweenEvictionRunsMillis: 60000
+      # 配置一个连接在池中最小生存的时间,单位是毫秒
+      minEvictableIdleTimeMillis: 300000
+      validationQuery: SELECT 1 FROM DUAL
+      testWhileIdle: true
+      testOnBorrow: false
+      testOnReturn: false
+      # 打开PSCache,并且指定每个连接上PSCache的大小
+      poolPreparedStatements: true
+      maxPoolPreparedStatementPerConnectionSize: 20
+      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
+      filters.commons-log.connection-logger-name: wall,log4j
+      filter:
+        stat:
+          enabled: true
+          mergeSql: true
+          log-slow-sql: true
+          slow-sql-millis: 2000
+      #监控配置
+      web-stat-filter:
+        enabled: true
+        url-pattern: /*
+        exclusions: '*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*'
+
+      # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
+      stat-view-servlet:
+        enabled: true
+        url-pattern: /druid/*
+        reset-enable: false
+        login-username: root
+        login-password: root
+
+  jackson:
+    date-format: yyyy-MM-dd HH:mm:ss
+    time-zone: GMT+8
+
+  #redis
+  redis:
+    database:
+      token: 8 # Token索引
+    host: 192.168.2.241  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
+#mybatis
+mybatis-plus:
+  mapper-locations: classpath:/mapper/*Mapper.xml
+  #实体扫描,多个package用逗号或者分号分隔
+  typeAliasesPackage: com.diagbot.entity
+  global-config:
+    #刷新mapper 调试神器
+    db-config:
+      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
+      id-type: id_worker
+      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
+      field-strategy: not_empty
+      #驼峰下划线转换
+      column-underline: true
+      #数据库大写下划线转换
+      #capital-mode: true
+      #刷新mapper 调试神器
+      refresh-mapper: true
+      #逻辑删除配置
+      logic-delete-value: 0
+      logic-not-delete-value: 1
+      #自定义填充策略接口实现
+      #meta-object-handler: com.baomidou.springboot.xxx
+      #自定义SQL注入器
+      #sql-injector: com.baomidou.springboot.xxx
+  configuration:
+    map-underscore-to-camel-case: true
+    cache-enabled: false
+
+swagger:
+  enable: true

+ 21 - 0
src/main/resources/bootstrap.yml

@@ -0,0 +1,21 @@
+spring:
+  application:
+    name: mrqc-sys
+#  cloud:
+#    config:
+#      #uri: http://${myuri}:8769
+#      fail-fast: true
+#      discovery:
+#        enabled: true
+#        serviceId: config-server
+  profiles:
+    active: local
+  main:
+    allow-bean-definition-overriding: true
+
+#eureka:
+#  client:
+#    serviceUrl:
+#      defaultZone: http://${myuri}:8761/eureka/
+#
+#myuri: localhost

BIN
src/main/resources/diagbot-jwt.jks


+ 306 - 0
src/main/resources/logback-spring.xml

@@ -0,0 +1,306 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+    <!-- 项目名称 -->
+    <property name="APPDIR" value="mrqc-sys"/>
+    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
+    <property name="LOG_PATH" value="../logs"/>
+
+    <!-- 彩色日志 -->
+    <!-- 彩色日志依赖的渲染类 -->
+    <conversionRule conversionWord="clr"
+                    converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
+    <conversionRule conversionWord="wex"
+                    converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
+    <conversionRule conversionWord="wEx"
+                    converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
+    <!-- 彩色日志格式 -->
+    <!--<property name="CONSOLE_LOG_PATTERN"-->
+    <!--value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(-&#45;&#45;){faint} %clr([%15.15t]){faint} %clr(%logger){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>-->
+    <!--包名输出缩进对齐-->
+    <property name="CONSOLE_LOG_PATTERN"
+              value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
+
+    <!--  日志记录器,日期滚动记录
+            ERROR 级别
+     -->
+    <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/${APPDIR}/${APPDIR}_error.log</file>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!-- 归档的日志文件的路径,例如今天是1992-11-06日志,当前写的日志文件路径为file节点指定,
+            可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+            而1992-11-06的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
+            <fileNamePattern>${LOG_PATH}/${APPDIR}/error/${APPDIR}-error-%d{yyyy-MM-dd}.%i.log
+            </fileNamePattern>
+            <!--  保留日志天数 -->
+            <maxHistory>30</maxHistory>
+            <!-- 除按日志记录之外,还配置了日志文件不能超过10MB,若超过10MB,日志文件会以索引0开始,
+            命名日志文件,例如log-error-1992-11-06.0.log -->
+            <timeBasedFileNamingAndTriggeringPolicy
+                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>10MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+        </rollingPolicy>
+        <!-- 追加方式记录日志 -->
+        <append>true</append>
+        <!-- 日志文件的格式 -->
+        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%thread] %logger Line:%-3L - %msg%n
+            </pattern>
+            <charset>utf-8</charset>
+        </encoder>
+        <!-- 此日志文件记录error级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>error</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+
+    <!-- 日志记录器,日期滚动记录
+            WARN  级别
+     -->
+    <appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/${APPDIR}/${APPDIR}_warn.log</file>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!-- 归档的日志文件的路径,例如今天1992-11-06日志,当前写的日志文件路径为file节点指定,
+            可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+            而1992-11-06的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
+            <fileNamePattern>${LOG_PATH}/${APPDIR}/warn/${APPDIR}-warn-%d{yyyy-MM-dd}.%i.log
+            </fileNamePattern>
+            <!--  保留日志天数 -->
+            <maxHistory>15</maxHistory>
+            <!-- 除按日志记录之外,还配置了日志文件不能超过10MB,若超过10MB,日志文件会以索引0开始,
+            命名日志文件,例如log-warn-1992-11-06.0.log -->
+            <timeBasedFileNamingAndTriggeringPolicy
+                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>10MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+        </rollingPolicy>
+        <!-- 追加方式记录日志 -->
+        <append>true</append>
+        <!-- 日志文件的格式 -->
+        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%thread] %logger Line:%-3L - %msg%n
+            </pattern>
+            <charset>utf-8</charset>
+        </encoder>
+        <!-- 此日志文件只记录warn级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>warn</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+
+    <!-- 日志记录器,日期滚动记录
+            INFO  级别
+    -->
+    <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/${APPDIR}/${APPDIR}_info.log</file>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!-- 归档的日志文件的路径,例如今天是1992-11-06日志,当前写的日志文件路径为file节点指定,
+            可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+            而1992-11-06的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
+            <fileNamePattern>${LOG_PATH}/${APPDIR}/info/${APPDIR}-info-%d{yyyy-MM-dd}.%i.log
+            </fileNamePattern>
+            <!--  保留日志天数 -->
+            <maxHistory>15</maxHistory>
+            <!-- 除按日志记录之外,还配置了日志文件不能超过10MB,若超过10MB,日志文件会以索引0开始,
+            命名日志文件,例如log-info-1992-11-06.0.log -->
+            <timeBasedFileNamingAndTriggeringPolicy
+                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>10MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+        </rollingPolicy>
+        <!-- 追加方式记录日志 -->
+        <append>true</append>
+        <!-- 日志文件的格式 -->
+        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%thread] %logger Line:%-3L - %msg%n
+            </pattern>
+            <charset>utf-8</charset>
+        </encoder>
+        <!-- 此日志文件只记录info级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>info</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+
+    <!-- 日志记录器,日期滚动记录
+            DEBUG  级别
+    -->
+    <appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
+        <!-- 正在记录的日志文件的路径及文件名 -->
+        <file>${LOG_PATH}/${APPDIR}/${APPDIR}_debug.log</file>
+        <!-- 日志记录器的滚动策略,按日期,按大小记录 -->
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <!-- 归档的日志文件的路径,例如今天是1992-11-06日志,当前写的日志文件路径为file节点指定,
+            可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。
+            而1992-11-06的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 -->
+            <fileNamePattern>${LOG_PATH}/${APPDIR}/debug/${APPDIR}-debug-%d{yyyy-MM-dd}.%i.log
+            </fileNamePattern>
+            <!--  保留日志天数 -->
+            <maxHistory>15</maxHistory>
+            <!-- 除按日志记录之外,还配置了日志文件不能超过10MB,若超过10MB,日志文件会以索引0开始,
+            命名日志文件,例如log-debug-1992-11-06.0.log -->
+            <timeBasedFileNamingAndTriggeringPolicy
+                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
+                <maxFileSize>10MB</maxFileSize>
+            </timeBasedFileNamingAndTriggeringPolicy>
+        </rollingPolicy>
+        <!-- 追加方式记录日志 -->
+        <append>true</append>
+        <!-- 日志文件的格式 -->
+        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
+            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level --- [%thread] %logger Line:%-3L - %msg%n
+            </pattern>
+            <charset>utf-8</charset>
+        </encoder>
+        <!-- 此日志文件只记录debug级别的 -->
+        <filter class="ch.qos.logback.classic.filter.LevelFilter">
+            <level>debug</level>
+            <onMatch>ACCEPT</onMatch>
+            <onMismatch>DENY</onMismatch>
+        </filter>
+    </appender>
+
+    <!-- ConsoleAppender 控制台输出日志 -->
+    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+        <!--encoder 默认配置为PatternLayoutEncoder-->
+        <encoder>
+            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
+            <!--<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level -&#45;&#45; [%thread] %logger Line:%-3L - %msg%n</pattern>-->
+            <charset>utf-8</charset>
+        </encoder>
+        <!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
+        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+            <level>debug</level>
+        </filter>
+    </appender>
+
+
+    <!--&lt;!&ndash;输出到mysql数据库的appender配置     &ndash;&gt;-->
+    <!--<appender name="db" class="ch.qos.logback.classic.db.DBAppender">-->
+    <!--<connectionSource-->
+    <!--class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
+    <!--<driverClass>com.mysql.cj.jdbc.Driver</driverClass>-->
+    <!--<url>jdbc:mysql://120.77.222.42:3306/logback_member?characterEncoding=utf8</url>-->
+    <!--<user>root</user>-->
+    <!--<password>a123456789</password>-->
+    <!--</connectionSource>-->
+    <!--</appender>-->
+
+    <!-- FrameworkServlet日志-->
+    <logger name="org.springframework" level="WARN"/>
+
+    <!-- mybatis日志打印-->
+    <logger name="org.apache.ibatis" level="DEBUG"/>
+    <logger name="java.sql" level="DEBUG"/>
+
+    <!--  项目 mapper 路径
+            console控制台显示sql语句:STDOUT.filter.level -> debug级别
+    -->
+    <logger name="com.diagbot.mapper" level="DEBUG"/>
+
+    <appender name="LOGSTASHDEV" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
+        <destination>192.168.2.236:5044</destination>
+        <!-- encoder必须配置,有多种可选 -->
+        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
+            <customFields>{"appname":"mrqc-sys"}</customFields>
+        </encoder>
+    </appender>
+
+    <appender name="LOGSTASHTEST" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
+        <destination>192.168.2.241:5044</destination>
+        <!-- encoder必须配置,有多种可选 -->
+        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
+            <customFields>{"appname":"mrqc-sys"}</customFields>
+        </encoder>
+    </appender>
+
+    <appender name="LOGSTASHPRE" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
+        <destination>192.168.2.121:5044</destination>
+        <!-- encoder必须配置,有多种可选 -->
+        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
+            <customFields>{"appname":"mrqc-sys"}</customFields>
+        </encoder>
+    </appender>
+
+    <appender name="LOGSTASHPRO" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
+        <destination>192.168.2.122:5044</destination>
+        <!-- encoder必须配置,有多种可选 -->
+        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
+            <customFields>{"appname":"mrqc-sys"}</customFields>
+        </encoder>
+    </appender>
+
+    <!-- 本地环境下的日志配置 -->
+    <springProfile name="local">
+        <root level="INFO">
+            <appender-ref ref="ERROR"/>
+            <appender-ref ref="WARN"/>
+            <appender-ref ref="INFO"/>
+            <appender-ref ref="DEBUG"/>
+            <appender-ref ref="STDOUT"/>
+        </root>
+    </springProfile>
+
+    <!-- 开发环境下的日志配置 -->
+    <springProfile name="dev">
+        <root level="INFO">
+            <appender-ref ref="ERROR"/>
+            <appender-ref ref="WARN"/>
+            <appender-ref ref="INFO"/>
+            <appender-ref ref="DEBUG"/>
+            <appender-ref ref="STDOUT"/>
+            <appender-ref ref="LOGSTASHDEV"/>
+        </root>
+    </springProfile>
+
+    <!-- 测试环境下的日志配置 -->
+    <springProfile name="test">
+        <root level="INFO">
+            <appender-ref ref="ERROR"/>
+            <appender-ref ref="WARN"/>
+            <appender-ref ref="INFO"/>
+            <appender-ref ref="DEBUG"/>
+            <appender-ref ref="STDOUT"/>
+            <appender-ref ref="LOGSTASHTEST"/>
+        </root>
+    </springProfile>
+
+    <!-- 预发布环境下的日志配置 -->
+    <springProfile name="pre">
+        <root level="INFO">
+            <appender-ref ref="ERROR"/>
+            <appender-ref ref="WARN"/>
+            <appender-ref ref="INFO"/>
+            <appender-ref ref="DEBUG"/>
+            <appender-ref ref="STDOUT"/>
+            <appender-ref ref="LOGSTASHPRE"/>
+        </root>
+    </springProfile>
+
+    <!-- 生产环境下的日志配置 -->
+    <springProfile name="pro">
+        <root level="INFO">
+            <appender-ref ref="ERROR"/>
+            <appender-ref ref="WARN"/>
+            <appender-ref ref="INFO"/>
+            <appender-ref ref="DEBUG"/>
+            <appender-ref ref="STDOUT"/>
+            <appender-ref ref="LOGSTASHPRO"/>
+        </root>
+    </springProfile>
+</configuration>

+ 26 - 0
src/main/resources/mapper/PermissionMapper.xml

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.diagbot.mapper.PermissionMapper">
+
+    <!-- 通用查询映射结果 -->
+    <resultMap id="BaseResultMap" type="com.diagbot.entity.Permission">
+        <id column="id" property="id"/>
+        <result column="is_deleted" property="isDeleted"/>
+        <result column="gmt_create" property="gmtCreate"/>
+        <result column="gmt_modified" property="gmtModified"/>
+        <result column="creator" property="creator"/>
+        <result column="modifier" property="modifier"/>
+        <result column="name" property="name"/>
+        <result column="permissionUrl" property="permissionUrl"/>
+        <result column="method" property="method"/>
+        <result column="descritpion" property="descritpion"/>
+    </resultMap>
+
+    <select id="getByUserId" parameterType="java.lang.Long" resultType="com.diagbot.entity.Permission">
+      select DISTINCT p.permissionUrl, p.method from sys_user u, sys_user_role sru, sys_role_permission rp, sys_permission p
+      where u.is_deleted = 'N' and sru.is_deleted = 'N' and rp.is_deleted = 'N' and p.is_deleted = 'N'
+      and u.id = sru.user_id and sru.role_id = rp.role_id and rp.permission_id = p.id
+      and u.id= #{userId}
+     </select>
+</mapper>

+ 22 - 0
src/main/resources/mapper/SysLogMapper.xml

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.diagbot.mapper.SysLogMapper">
+
+    <!-- 通用查询映射结果 -->
+    <resultMap id="BaseResultMap" type="com.diagbot.entity.SysLog">
+        <id column="id" property="id"/>
+        <result column="is_deleted" property="isDeleted"/>
+        <result column="gmt_create" property="gmtCreate"/>
+        <result column="gmt_modified" property="gmtModified"/>
+        <result column="creator" property="creator"/>
+        <result column="modifier" property="modifier"/>
+        <result column="ip" property="ip"/>
+        <result column="sys_type" property="sysType"/>
+        <result column="method" property="method"/>
+        <result column="operation" property="operation"/>
+        <result column="params" property="params"/>
+        <result column="username" property="username"/>
+    </resultMap>
+
+</mapper>

+ 35 - 0
src/main/resources/mapper/UserMapper.xml

@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.diagbot.mapper.UserMapper">
+
+    <!-- 通用查询映射结果 -->
+    <resultMap id="BaseResultMap" type="com.diagbot.entity.User">
+        <id column="id" property="id"/>
+        <result column="is_deleted" property="isDeleted"/>
+        <result column="gmt_create" property="gmtCreate"/>
+        <result column="gmt_modified" property="gmtModified"/>
+        <result column="creator" property="creator"/>
+        <result column="modifier" property="modifier"/>
+        <result column="password" property="password"/>
+        <result column="username" property="username"/>
+    </resultMap>
+
+
+    <resultMap id="userMap" type="com.diagbot.entity.User">
+        <id column="id" property="id"/>
+        <result column="is_deleted" property="isDeleted"/>
+        <result column="gmt_create" property="gmtCreate"/>
+        <result column="gmt_modified" property="gmtModified"/>
+        <result column="creator" property="creator"/>
+        <result column="modifier" property="modifier"/>
+        <result column="password" property="password"/>
+        <result column="username" property="username"/>
+    </resultMap>
+
+    <select id="getByUserName" parameterType="java.lang.String" resultMap="userMap">
+		select u.*
+		from sys_user u
+        where is_deleted = 'N' and u.username= #{username}
+	</select>
+</mapper>

+ 9 - 0
src/main/resources/public.cert

@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxXZWH/WgxW9eTT6AmPRo
+GFY3T5V1+F1458dcQFw0EZejjHuGwEeHvxcgl4059Me2B1xXTs3FDXTWQ5z19EtP
+3ITYtnFTo2cxhwxiwqN8ZqFdpq5Uac0mzjlYKcyGp8x6t+Nc2cv3D3Ul2VIbGvbP
+sQOeKvt3WxWwdpQ+q3RXjRUFQGiygSD7yuXHIUpcOsm4ZWDlUkjfwX1q4pjiwFfA
+Mq5xgkzPwolUKnI0NFnom3Th3i4oFXzUg2s6cEj7jL7YU35c2/9kE7WQPbeYhoSi
+XH2OwWgBk/2Ki6+Q0Yq/eAsXSBjp1jqh337vvKBk5ocPG1Imi8uTLIgYQCMwzvg+
+VQIDAQAB
+-----END PUBLIC KEY-----

+ 83 - 0
src/test/java/com/diagbot/CodeGeneration.java

@@ -0,0 +1,83 @@
+package com.diagbot;
+
+import com.baomidou.mybatisplus.annotation.DbType;
+import com.baomidou.mybatisplus.generator.AutoGenerator;
+import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
+import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.PackageConfig;
+import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
+
+/**
+ * @Description: 代码生成器
+ * @author: gaodm
+ * @time: 2018/8/2 10:15
+ */
+public class CodeGeneration {
+
+    /**
+     *
+     * @Title: main
+     * @Description: 生成
+     * @param args
+     */
+    public static void main(String[] args) {
+        AutoGenerator mpg = new AutoGenerator();
+
+        // 全局配置
+        GlobalConfig gc = new GlobalConfig();
+        gc.setOutputDir("E://code//feedbackservice");
+        gc.setFileOverride(true);
+        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
+        gc.setEnableCache(false);// XML 二级缓存
+        gc.setBaseResultMap(true);// XML ResultMap
+        gc.setBaseColumnList(false);// XML columList
+        gc.setAuthor("gaodm");// 作者
+
+        // 自定义文件命名,注意 %s 会自动填充表实体属性!
+        gc.setControllerName("%sController");
+        gc.setServiceName("%sService");
+        gc.setServiceImplName("%sServiceImpl");
+        gc.setMapperName("%sMapper");
+        gc.setXmlName("%sMapper");
+        mpg.setGlobalConfig(gc);
+
+        // 数据源配置
+        DataSourceConfig dsc = new DataSourceConfig();
+        dsc.setDbType(DbType.MYSQL);
+        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
+        dsc.setUsername("root");
+        dsc.setPassword("root");
+        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/sys-log?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8");
+        mpg.setDataSource(dsc);
+
+        // 策略配置
+        StrategyConfig strategy = new StrategyConfig();
+//        strategy.setTablePrefix(new String[] { "sys_" });// 此处可以修改为您的表前缀
+        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
+        strategy.setInclude(new String[] { "sys_log" }); // 需要生成的表
+
+        strategy.setSuperServiceClass(null);
+        strategy.setSuperServiceImplClass(null);
+        strategy.setSuperMapperClass(null);
+
+        mpg.setStrategy(strategy);
+
+        // 包配置
+        PackageConfig pc = new PackageConfig();
+        pc.setParent("com.diagbot");
+        pc.setController("web");
+        pc.setService("service");
+        pc.setServiceImpl("service.impl");
+        pc.setMapper("mapper");
+        pc.setEntity("entity");
+        pc.setXml("resources.mapper");
+        mpg.setPackageInfo(pc);
+
+        // 执行生成
+        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
+        mpg.execute();
+
+    }
+}

+ 16 - 0
src/test/java/com/diagbot/MrqcSysApplicationTests.java

@@ -0,0 +1,16 @@
+package com.diagbot;
+
+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 MrqcSysApplicationTests {
+
+    @Test
+    public void contextLoads() {
+    }
+
+}