Parcourir la source

Merge branch 'dev' of yeshijie/patient-co-management into dev

yeshijie il y a 7 ans
Parent
commit
eac99f86cf
100 fichiers modifiés avec 10258 ajouts et 0 suppressions
  1. 270 0
      patient-co-manage/redis-cache/pom.xml
  2. 30 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/Application.java
  3. 14 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/ApiVersion.java
  4. 60 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/BizObject.java
  5. 189 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/ErrorCode.java
  6. 14 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/PageArg.java
  7. 161 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/ServiceApi.java
  8. 196 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/controller/BaseRestEndPoint.java
  9. 75 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/controller/EnvelopRestEndPoint.java
  10. 120 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/exception/ApiException.java
  11. 42 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/exception/ResourceError.java
  12. 198 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/FieldCondition.java
  13. 218 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/PageModel.java
  14. 28 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/ReturnIdPstCreator.java
  15. 303 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/URLHqlQueryParser.java
  16. 63 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/UpdatePstCallback.java
  17. 526 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/ObjectId.java
  18. 44 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/StringBuilderEx.java
  19. 129 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/URLQueryBuilder.java
  20. 15 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/UuidUtil.java
  21. 52 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/DefaultJSchUserInfo.java
  22. 107 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisCacheAuthorization.java
  23. 91 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisCacheCategory.java
  24. 127 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisCacheKeyRule.java
  25. 136 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisMqChannel.java
  26. 107 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisMqPublisher.java
  27. 107 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisMqSubscriber.java
  28. 25 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/DataSourceConfig.java
  29. 51 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/RedisConfig.java
  30. 66 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/RepositoryWlyyConfig.java
  31. 121 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/SpringSecurityConfig.java
  32. 48 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/SwaggerConfig.java
  33. 59 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/WebMvcConfig.java
  34. 621 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/BaseController.java
  35. 85 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/common/account/LoginController.java
  36. 22 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/common/account/LogoutController.java
  37. 146 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/common/account/RegisterController.java
  38. 32 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/AdminController.java
  39. 17 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/MainController.java
  40. 127 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/account/ShiroDbRealm.java
  41. 220 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/user/UserController.java
  42. 169 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheAuthorizationEndPoint.java
  43. 215 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheCategoryEndPoint.java
  44. 189 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheKeyRuleEndPoint.java
  45. 151 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheOperationEndPoint.java
  46. 132 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheStatisticsEndPoint.java
  47. 35 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisIndexController.java
  48. 241 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisMqChannelEndPoint.java
  49. 169 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisMqPublisherEndPoint.java
  50. 199 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisMqSubscriberEndPoint.java
  51. 198 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisScheduledController.java
  52. 67 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisSubscribeMessageEndPoint.java
  53. 54 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/DictEntryKey.java
  54. 44 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/IdEntity.java
  55. 133 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/SocialSecurityInfo.java
  56. 106 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/SystemDict.java
  57. 152 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/SystemDictList.java
  58. 456 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/User.java
  59. 56 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/BaseAssignedEntity.java
  60. 130 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheAuthorization.java
  61. 120 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheCategory.java
  62. 137 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheKeyMemory.java
  63. 163 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheKeyRule.java
  64. 99 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheResponseTimeLog.java
  65. 174 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqChannel.java
  66. 130 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqMessageLog.java
  67. 131 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqPublisher.java
  68. 131 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqSubscriber.java
  69. 65 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/AccessToken.java
  70. 71 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/JsApiTicket.java
  71. 29 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/RSA.java
  72. 81 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/Token.java
  73. 116 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/AccessDecisionManagerImpl.java
  74. 61 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/AccessDeniedHandlerImpl.java
  75. 33 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/RoleCache.java
  76. 41 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/SessionOutTimeFilter.java
  77. 36 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/interceptors/UserSessionInterceptor.java
  78. 86 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/listener/ApplicationReadyEventListener.java
  79. 19 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/listener/ApplicationStart.java
  80. 19 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/SocialSecurityInfoDao.java
  81. 22 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/SystemDictDao.java
  82. 12 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/SystemDictListDao.java
  83. 41 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/UserDao.java
  84. 21 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheAuthorizationDao.java
  85. 22 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheCategoryDao.java
  86. 21 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheKeyMemoryDao.java
  87. 24 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheKeyRuleDao.java
  88. 19 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheResponseTimeLogDao.java
  89. 24 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqChannelDao.java
  90. 19 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqMessageLogDao.java
  91. 25 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqPublisherDao.java
  92. 26 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqSubscriberDao.java
  93. 17 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/AccessTokenDao.java
  94. 17 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/JsapiTicketDao.java
  95. 14 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/RSADao.java
  96. 46 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/TokenDao.java
  97. 99 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/BaseService.java
  98. 34 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/ServiceException.java
  99. 55 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/manager/account/AdminService.java
  100. 0 0
      patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/manager/dict/SystemDictService.java

+ 270 - 0
patient-co-manage/redis-cache/pom.xml

@ -0,0 +1,270 @@
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yihu</groupId>
    <artifactId>redis-cache</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>redis-cache</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <springside.version>4.2.3-GA</springside.version>
        <shiro.version>1.2.3</shiro.version>
        <commons-lang3.version>3.3.2</commons-lang3.version>
        <guava.version>17.0</guava.version>
        <jackson.version>2.4.0</jackson.version>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <version.spring-boot>1.3.5.RELEASE</version.spring-boot>
        <version.spring-data-redis>1.7.1.RELEASE</version.spring-data-redis>
        <version.jedis>2.9.0</version.jedis>
        <version.jsch>0.1.54</version.jsch>
    </properties>
    <dependencies>
        <!-- 能启动,访问 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!--<exclusion>-->
                <!--<groupId>org.springframework.boot</groupId>-->
                <!--<artifactId>spring-boot-starter-logging</artifactId>-->
                <!--</exclusion>-->
                <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-tomcat</artifactId>-->
        <!--<scope>provided</scope>-->
        <!--</dependency>-->
        <!-- 数据库 +application。properties文件 或yml文件-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- servlet 依赖. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>compile</scope>
        </dependency>
        <!-- 使用intellij作为集成开发环境 本地测试时打开,要布署到正式线时要注释-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>compile</scope>
        </dependency>
        <!-- 以上 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 正常启动,数据库访问。页面显示后其他依赖-->
        <!-- GENERAL UTILS begin -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jaxb-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160212</version>
        </dependency>
        <!-- JSON end -->
        <!-- redis start  -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>${version.spring-data-redis}</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${version.jedis}</version>
        </dependency>
        <!-- redis end  -->
        <!-- SPRINGSIDE -->
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
            <version>${springside.version}</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>
        <!-- SECURITY begin -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>
        <!-- SECURITY end -->
        <dependency>
            <groupId>sehrCrypto</groupId>
            <artifactId>sehrCrypto</artifactId>
            <version>1.0.0</version>
        </dependency>
        <!-- Apache Commons fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- Apache Commons fileupload end -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <!-- swagger ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
            <exclusions>
                <exclusion>
                    <artifactId>classmate</artifactId>
                    <groupId>com.fasterxml</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>org.springframework.security</groupId>-->
        <!--<artifactId>spring-security-core</artifactId>-->
        <!--<version>4.0.0.RELEASE</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <!--https://mvnrepository.com/artifact/org.springframework.security/spring-security-taglibs-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>${version.jsch}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
            <version>${version.spring-boot}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-extras</artifactId>
            <version>3.0.5</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <finalName>redis-cache</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin </artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

+ 30 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/Application.java

@ -0,0 +1,30 @@
package com.yihu.wlyy;
import com.yihu.wlyy.listener.ApplicationReadyEventListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
 * Created by Administrator on 2016/6/18.
 */
@SpringBootApplication
@EnableScheduling
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication();
        app.addListeners(new ApplicationReadyEventListener());
        app.run(Application.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

+ 14 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/ApiVersion.java

@ -0,0 +1,14 @@
package com.yihu.wlyy.common.constants;
/**
 * API版本前缀。用于适配Rest控制器的版本。定义好适用的版本之后,可以方便API版本编写。
 *
 * API版本格式为:v大版本.小版本。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.11.05 11:29
 */
public class ApiVersion {
    public static final String Version1_0 = "";      // v1.0 版本
}

+ 60 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/BizObject.java

@ -0,0 +1,60 @@
package com.yihu.wlyy.common.constants;
/**
 * 业务对象划分, 全局唯一ID会使用此划分. 因为 ObjectId 中仅使用一个short作为
 * ID的一部分, 因为枚举值会在 0 ~ 2^16 - 1之间.
 *
 * @author Sand
 * @version 1.0
 * @created 2015.06.19 14:38
 */
public enum BizObject {
    Geography((short) 0x0001),
    Organization((short) 0x0002),
    User((short) 0x0003),
    Card((short) 0x0004),
    JsonPackage((short) 0x0005),
    StdProfile((short) 0x0006),
    HealthEvent((short) 0x0007),
    ADAPTER((short) 0x0008),
    STANDARD((short) 0x0009),
    App((short) 0x00010),
    Dict((short) 0x0011),
    CdaType((short) 0x0012),
    Families((short) 0x0013),
    Members((short) 0x0014),
    Resources((short) 0x0015),
    Dimensions((short) 0x0016),
    DimensionsCategories((short) 0x0017),
    ResourceMetadata((short) 0x0018),
    AppResource((short) 0x0019),
    AppResourceMetadata((short) 0x0020),
    ResourceCategory((short) 0x0021),
    FileResource((short) 0x0022),
    RsMetadata((short) 0x0023),
    RsAdapterSchema((short) 0x0024),
    RsAdapterMetadata((short) 0x0025),
    RsDictionary((short) 0x0026),
    RsDictionaryEntry((short) 0x0027),
    RsSystemDictionary((short) 0x0028),
    RsSystemDictionaryEntry((short) 0x0029),
    RsInterface((short) 0x0030),
    RsAdapterDictionary((short) 0x0031),
    RsParam((short) 0x0032),
    RolesResource((short) 0x0033),
    RolesResourceMetadata((short) 0x0034),
    OrgResource((short) 0x0035),
    OrgResourceMetadata((short) 0x0036),
    ResourcesDefaultQuery((short) 0x0037);
    public short getBizObject() {
        return bizObject;
    }
    private short bizObject;
    private BizObject(short bizObject) {
        this.bizObject = bizObject;
    }
}

+ 189 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/ErrorCode.java

@ -0,0 +1,189 @@
package com.yihu.wlyy.common.constants;
/**
 *
 * @author Sand
 * @version 1.0
 * @created 2015.08.10 17:49
 */
public enum ErrorCode {
    MissingUserAgent("missing.user_agent"),
    RateLimitExceeding("rate_limit.exceeding"),
    MissMethod("ehr.common.miss.method"),
    MissTimestamp("ehr.common.miss.timestamp"),
    MissAppKey("ehr.common.miss.appid"),
    MissVersion("ehr.common.miss.version"),
    MissSign("ehr.common.miss.sign"),
    MissSignMethod("ehr.common.miss.signMethod"),
    InvalidMethod("ehr.common.invalid.method"),
    InvalidTimestamp("ehr.common.invalid.timestamp"),
    InvalidAppId("ehr.common.invalid.appid"),
    InvalidApiVersion("ehr.common.invalid.version"),
    InvalidSign("ehr.common.invalid.sign"),
    InvalidSignMethod("ehr.common.invalid.signMethod"),
    MissRequiredArgument("ehr.common.miss.required.argument"),
    MissParameter("ehr.common.miss.parameter"),
    InvalidParameter("ehr.common.invalid.parameter"),
    AppTokenExpired("ehr.common.appToken.expired"),
    QueryNoData("ehr.common.query.null"),
    QueryTotalCount("ehr.common.query.count"),
    NotFoundObj("ehr.common.query.not.found"),
    RepeatCode("ehr.commons.repeat.code"),
    RepeatName("ehr.commons.repeat.name"),  // add by cws 20160223
    RepeatRelation("ehr.commons.repeat.relation"),  // add by cws 20160225
    SuccessSave("ehr.common.success.update"),
    InvalidUpdate("ehr.common.invalid.update"),
    SuccessAdd("ehr.common.success.create"),
    SuccessDelete("ehr.common.success.delete"),
    InvalidDelete("ehr.common.invalid.delete"),
    InputRequestSingle("ehr.common.input.request.single"),
    InputRequestMultiple("ehr.common.input.request.multiple"),
    NotFoundEntity("ehr.common.notfound.entity"),//add by lincl 2016.3.3
    InvalidUser("ehr.invalid.user"),
    GetUserSecurityFailed("ehr.get.user.security.failed"),
    InvalidUserNameOrPwd("ehr.invalid.username.or.pwd"),
    InvalidValidateCode("ehr.login.validatecode.invalid"),
    ExpireValidateCode("ehr.login.validatecode.expire"),
    MailHasValidate("ehr.login.mail.hasinvaild"),
    InvalidMail("ehr.login.mail.invaild"),
    ExistUserForCreate("ehr.user.exist.create"),
    SuccessPublicKeyCreate("ehr.publicKey.success.create"),
    ExistOrgForCreate("ehr.org.exist.create"),
    InvalidAppRegister("ehr.app.register.invalid"),
    MissIdentityNo("ehr.patient.miss.identity.no"),
    RepeatedIdentityNo("ehr.patient.repeat.identity.no"),
    InvalidIdentityNo("ehr.patient.invalid.identity.no"),
    PatientRegisterFailed("ehr.patient.register.failed"),
    InvalidFormatPatientRegister("ehr.patient.invalid.register.info"),
    PatientRegisterFailedForExist("ehr.patient.exist.create"),
    CardIsToVoid("ehr.commons.repeat.code"),
    MissArchiveFile("ehr.archive.miss.file"),
    MissArchiveCrypto("ehr.archive.miss.cryptograph"),
    ParseArchiveCryptoFailed("ehr.archive.parse.cryptograph.failed"),
    SaveArchiveFailed("ehr.archive.save.failed"),
    RepeatSysDictName("ehr.sysDict.name.repeat"),
    RepeatOrgDict("ehr.orgDict.repeat"),
    RepeatOrgDictItem("ehr.orgDictItem.repeat"),
    RepeatOrgDataSet("ehr.orgDataSet.repeat"),
    RepeatOrgMetaData("ehr.orgMetaData.repeat"),
    InvalidCreateSysDict("ehr.sysDict.create.invalid"),
    NotExistSysDict("ehr.sysDict.exist.invalid"),
    InvalidDelSysDict("ehr.sysDict.del.invalid "),
    InvalidUpdateSysDict("ehr.sysDict.update.invalid"),
    RepeatSysDictEntryName("ehr.sysDictEntry.name.repeat"),
    InvalidCreateSysDictEntry("ehr.sysDictEntry.create.invalid"),
    InvalidSysDictEntry("ehr.sysDictEntry.name.invalid"),
    InvalidDelSysDictEntry("ehr.sysDictEntry.del.invalid"),
    InvalidUpdateSysDictEntry("ehr.sysDictEntry.update.invalid"),
    GetGeographyFailed("ehr.geography.ger.invalid"),
    ParamError("ehr.std.param.error"),
    InvalidStdVersion("ehr.std.invalid.version"),
    GenerateArchiveFailed("ehr.std.generate.schema.file.failed"),
    GenerateArchiveFileStreamFailed("ehr.std.file.stream.generate.failed"),
    DownArchiveFileFailed("ehr.std.file.down.failed"),
    GenerateFileCryptographStreamFailed("ehr.std.file.cryptograph.generate.failed"),
    GenerateFileCryptographFailed("ehr.std.file.cryptograph.generate.failed"),
    GetStdVersionFailed("ehr.std.get.version.fail"),
    UnknownStdVersion("ehr.std.version.unknown"),
    GetCDAVersionListFailed("ehr.cda.version.list.get.failed"),
    GetCDAVersionFailed("ehr.cda.version.get.failed"),
    SaveCDAVersionFailed("ehr.cda.version.save.failed"),
    GetCDAInfoFailed("ehr.std.get.CDA.list.failed"),
    InValidCDAVersionStage("ehr.std.version.invalid.stage"),//add by lincl 2016.3.3
    NotFoundDataSetView("ehr.dataset.view.notfound"),
    GetCDATypeFailed("ehr.cda.type.get.failed"),
    GetDataSetListFailed("ehr.datasetlist.Get.failed"),
    GetDataSetFailed("ehr.dataset.Get.failed"),
    SavedatasetFailed("ehr.dataset.Save.failed"),
    DeleteDataSetFailed("ehr.dataset.delete.failed"),
    RapeatDataSetCode("ehr.dataset.repeat.code"),
    NotFoundMetaDataView("ehr.metadata.view.notfound"),
    GetMetaDataListFaield("ehr.metadatalist.Get.failed"),
    GetMetaDataFailed("ehr.metadata.Get.failed"),
    SaveMetaDataFailed("ehr.metadata.save.failed"),
    DeleteMetaDataFailed("ehr.metadata.delete.failed"),
    NotFoundStdDictView("ehr.std.dict.view.notfound"),
    GetDictListFaild("ehr.dictlist.Get.failed"),
    GetDictFaild("ehr.dict.Get.failed"),
    SaveDictFailed("ehr.dict.Save.failed"),
    DeleteDictFailed("ehr.dict.delete.failed"),
    NotFoundDictEntryView("ehr.dict.entry.view.notfound"),
    GetDictEntryListFailed("ehr.dict.entries.get.failed"),
    GetDictEntryFailed("ehr.dict.entry.get.failed"),
    saveDictEntryFailed("ehr.dict.entry.save.failed"),
    DeleteDictEntryFailed("ehr.dict.entry.delete.failed"),
    GetStandardSourceFailed("ehr.std.get.source.list.failed"),
    GenerateUserKeyFailed("ehr.security.generate.user.key.failed"),
    GetUserKeyFailed("ehr.security.get.user.key.failed"),
    UserAccessTokenExpired("ehr.security.token.expired"),
    UserRefreshTokenError("ehr.security.token.refreshError"),
    UserRevokeTokenFailed("ehr.security.token.revoke"),
    CodeIsNull("ehr.system.code.null"),
    NameIsNull("ehr.system.name.null"),
    VersionCodeIsNull("ehr.system.versioncode.null"),
    GetEhrArchiveFailed("ehr.ehr.get.archive"),
    GetEhrDataSetFailed("ehr.ehr.get.data.set"),
    CreateEhrDataSetTableFailed("ehr.ehr.create.data.set.table.failed"),
    TruncateTableFailed("ehr.hbase.truncate.table.failed"),
    GetTableFailed("ehr.hbase.get.table.failed"),
    ClearSolrDataFailed("ehr.clear.solr.data.failed"),
    //
    UnknownJsonPackageId("ehr.json.package.unknown"),
    // Quartz Scheduler
    SchedulerStartFailed("ehr.scheduler.start.failed"),
    SchedulerShutdownFailed("ehr.scheduler.shutdown.failed"),
    SchedulerAddJobFailed("ehr.scheduler.add.job"),
    SchedulerRemoveJobFailed("ehr.scheduler.remove.job"),
    GetJobDetailFailed("ehr.scheduler.get.job.failed"),
    GetTriggerFailed("ehr.scheduler.get.trigger.failed"),
    //adaption
    RepeatAdapterOrg("ehr.adpter.org.repeat"),
    //Other
    SystemError("ehr.system.error");
    private final String errorCode;
    private ErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }
    public String getErrorCode() {
        return errorCode;
    }
}

+ 14 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/PageArg.java

@ -0,0 +1,14 @@
package com.yihu.wlyy.common.constants;
/**
 * @author Sand
 * @version 1.0
 * @created 2016.02.14 17:47
 */
public class PageArg {
    public static final Integer DefaultPage = 1;
    public static final Integer DefaultSize = 30;
    public static final String DefaultPageS = "1";
    public static final String DefaultSizeS = "30";
}

+ 161 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/constants/ServiceApi.java

@ -0,0 +1,161 @@
package com.yihu.wlyy.common.constants;
/**
 * 微服务REST API. 此处定义的URL可用于服务对外提供的地址及HTTP客户端请求地址.
 * URL定义遵循健康档案平台REST规范.
 *
 * @author Sand
 * @version 1.0
 * @created 2015.09.09 15:04
 */
public class ServiceApi {
    public static class GateWay {
        public static final String admin = "/admin";
    }
    /**
     * Redis服务
     */
    public static class Redis {
        //初始化缓存
        public static final String InitAddress = "/redis/init/address";
        public static final String InitHealthProblem = "/redis/init/healthProblem";
        public static final String InitIcd10HpR = "/redis/init/icd10HpR";
        public static final String InitIcd10 = "/redis/init/icd10";
        public static final String InitIndicatorsDict = "/redis/init/indicatorsDict";
        public static final String InitOrgName = "/redis/init/orgName";
        public static final String InitOrgArea = "/redis/init/orgArea";
        public static final String InitOrgSaasArea = "/redis/init/orgSaasArea";
        public static final String InitOrgSaasOrg = "/redis/init/orgSaasOrg";
        public static final String InitVersions = "/redis/init/versions";
        public static final String InitRsAdapterDict = "/redis/init/rsAdapterDict/{id}";
        public static final String InitRsAdapterMeta = "/redis/init/rsAdapterMeta/{id}";
        public static final String InitRsMetadata = "/redis/init/rsMetadata";
        //清除缓存
        public static final String Delete = "/redis/delete";
        //更新缓存
        public static final String UpdateOrgName = "/redis/update/orgName";
        public static final String UpdateOrgArea = "/redis/update/orgArea";
        public static final String UpdateOrgSaasArea = "/redis/update/orgSaasArea";
        public static final String UpdateOrgSaasOrg = "/redis/update/orgSaasOrg";
        //获取缓存数据
        public static final String Address = "/redis/address";
        public static final String HealthProblem = "/redis/healthProblem";
        public static final String Icd10HpR = "/redis/icd10HpRelation";
        public static final String Icd10Name = "/redis/icd10Name";
        public static final String Icd10HpCode = "/redis/icd10HpCode";
        public static final String IndicatorsDict = "/redis/indicatorsDict";
        public static final String OrgName = "/redis/orgName";
        public static final String OrgArea = "/redis/orgArea";
        public static final String OrgSaasArea = "/redis/orgSaasArea";
        public static final String OrgSaasOrg = "/redis/orgSaasOrg";
        //App前端Redis
        public static final String AppGetRedisValue = "/redis/getAppClientValue";
        public static final String AppSetRedisValue = "/redis/setAppClientValue";
        public static final String AppSetRedisJsonValue = "/redis/setAppClientJsonValue";
        public static final String AppDeleteRedisValue = "/redis/deleteAppClientValue";
        //资源化相关Redis
        public static final String RsAdapterDict = "/redis/rsAdapterDict";
        public static final String RsAdapterMetadata = "/redis/rsAdapterMetaData";
        public static final String RsMetadata = "/redis/rsMetadata";
        //标准相关Redis
        public static final String StdVersion = "/redis/stdVersion";
        public static final String StdDataSetCode = "/redis/stdDataSetCode";
        public static final String StdDataSetName = "/redis/stdDataSetName";
        public static final String StdDataSetNameByCode = "/redis/stdDataSetNameByCode";
        public static final String StdDataSetMultiRecord = "/redis/stdDataSetMultiRecord";
        public static final String StdMetadataType = "/redis/stdMetaDataType";
        public static final String StdMetadataDict = "/redis/stdMetaDataDict";
        public static final String StdDictEntryValue = "/redis/stdDictEntryValue";
        // Redis消息队列
        public static class MqChannel {
            public static final String Prefix = "/redis/mq/channel/";
            public static final String GetById = "/redis/mq/channel/{id}";
            public static final String Search = "/redis/mq/channel/search";
            public static final String Save = "/redis/mq/channel/save";
            public static final String Delete = "/redis/mq/channel/delete";
            public static final String IsUniqueChannel = "/redis/mq/channel/isUniqueChannel";
            public static final String IsUniqueChannelName = "/redis/mq/channel/isUniqueChannelName";
            public static final String SendMessage = "/redis/mq/channel/sendMessage";
        }
        // Redis消息订阅者
        public static class MqSubscriber {
            public static final String Prefix = "/redis/mq/subscriber/";
            public static final String GetById = "/redis/mq/subscriber/{id}";
            public static final String Search = "/redis/mq/subscriber/search";
            public static final String Save = "/redis/mq/subscriber/save";
            public static final String Delete = "/redis/mq/subscriber/delete";
            public static final String IsUniqueAppId = "/redis/mq/subscriber/isUniqueAppId";
            public static final String IsUniqueSubscribedUrl = "/redis/mq/subscriber/isUniqueSubscribedUrl";
        }
        // Redis消息发布者
        public static class MqPublisher {
            public static final String Prefix = "/redis/mq/publisher/";
            public static final String GetById = "/redis/mq/publisher/{id}";
            public static final String Search = "/redis/mq/publisher/search";
            public static final String Save = "/redis/mq/publisher/save";
            public static final String Delete = "/redis/mq/publisher/delete";
            public static final String IsUniqueAppId = "/redis/mq/publisher/isUniqueAppId";
        }
        // 缓存分类
        public static class CacheCategory {
            public static final String Prefix = "/redis/cache/category/";
            public static final String GetById = "/redis/cache/category/{id}";
            public static final String Search = "/redis/cache/category/search";
            public static final String SearchNoPage = "/redis/cache/category/searchNoPage";
            public static final String Save = "/redis/cache/category/save";
            public static final String Delete = "/redis/cache/category/delete";
            public static final String IsUniqueName = "/redis/cache/category/isUniqueName";
            public static final String IsUniqueCode = "/redis/cache/category/isUniqueCode";
        }
        // 缓存授权
        public static class CacheAuthorization {
            public static final String Prefix = "/redis/cache/authorization/";
            public static final String GetById = "/redis/cache/authorization/{id}";
            public static final String Search = "/redis/cache/authorization/search";
            public static final String Save = "/redis/cache/authorization/save";
            public static final String Delete = "/redis/cache/authorization/delete";
            public static final String IsUniqueAppId = "/redis/cache/authorization/isUniqueAppId";
        }
        // 缓存Key规则
        public static class CacheKeyRule {
            public static final String Prefix = "/redis/cache/keyRule/";
            public static final String GetById = "/redis/cache/keyRule/{id}";
            public static final String Search = "/redis/cache/keyRule/search";
            public static final String Save = "/redis/cache/keyRule/save";
            public static final String Delete = "/redis/cache/keyRule/delete";
            public static final String IsUniqueName = "/redis/cache/keyRule/isUniqueName";
            public static final String IsUniqueCode = "/redis/cache/keyRule/isUniqueCode";
        }
        // 缓存操作
        public static class CacheOperation {
            public static final String Get = "/redis/cache/operation/get";
            public static final String Set = "/redis/cache/operation/set";
            public static final String Remove = "/redis/cache/operation/remove";
        }
        // 缓存操作
        public static class CacheStatistics {
            public static final String GetCategoryKeys = "/redis/cache/statistics/getCategoryKeys";
            public static final String GetCategoryMemory = "/redis/cache/statistics/getCategoryMemory";
        }
        // 接收订阅消息
        public static class SubscribeMessage {
            public static final String ReceiveResponseTime = "/redis/subscribeMessage/receiveResponseTime";
        }
    }
    public static class SystemDict {
        public static final String getDictEntryByDictId = "/systemDict/getDictEntryByDictId/{dictId}";
    }
}

+ 196 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/controller/BaseRestEndPoint.java

@ -0,0 +1,196 @@
package com.yihu.wlyy.common.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.common.constants.ErrorCode;
import com.yihu.wlyy.common.constants.PageArg;
import com.yihu.wlyy.common.exception.ApiException;
import com.yihu.wlyy.util.DateTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 控制器基类。提供模型转换,分页规范实现。
 *
 * @author Sand
 * @version 1.0
 * @created 2016.04.07 17:01
 */
public class BaseRestEndPoint extends AbstractController {
    protected final static String ResourceCount = "X-Total-Count";
    protected final static String ResourceLink = "Link";
    @Autowired
    protected ObjectMapper objectMapper;
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        return null;
    }
    /**
     * 将实体转换为模型。
     *
     * @param source
     * @param targetCls
     * @param properties
     * @param <T>
     * @return
     */
    public <T> T convertToModel(Object source, Class<T> targetCls, String... properties) {
        if (source == null) {
            return null;
        }
        T target = BeanUtils.instantiate(targetCls);
        BeanUtils.copyProperties(source, target, propertyDiffer(properties, targetCls));
        return target;
    }
    public <T> T toEntity(String json, Class<T> entityCls) {
        try {
            objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.ISO8601Pattern));
            T entity = objectMapper.readValue(json, entityCls);
            return entity;
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new ApiException(ErrorCode.SystemError, "Unable to parse json, " + ex.getMessage());
        }
    }
    public String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 将实体集合转换为模型集合。
     *
     * @param sources
     * @param targets
     * @param properties
     * @param <T>
     * @return
     */
    public <T> Collection<T> convertToModels(Collection sources, Collection<T> targets, Class<T> targetCls, String properties) {
        if (sources == null) {
            return null;
        }
        Iterator iterator = sources.iterator();
        while (iterator.hasNext()) {
            Object source = iterator.next();
            T target = (T) BeanUtils.instantiate(targetCls);
            BeanUtils.copyProperties(source, target, propertyDiffer(StringUtils.isEmpty(properties) ? null : properties.split(","), targetCls));
            targets.add(target);
        }
        return targets;
    }
    /**
     * 计算不在类中的属性。
     *
     * @return
     */
    protected String[] propertyDiffer(String[] properties, Class targetCls) {
        if (properties == null || properties.length == 0) return null;
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(targetCls);
        List<String> propertiesList = Arrays.asList(properties);
        List<String> arrayList = new ArrayList<>();
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && !propertiesList.contains(targetPd.getName())) {
                arrayList.add(targetPd.getName());
            }
        }
        return arrayList.toArray(new String[arrayList.size()]);
    }
    /**
     * 客户端调用REST接口时,若返回的是分页结果,则需要在响应头中添加资源的总数量及其他资源的分页导航。
     * EHR平台使用响应头中的 X-Total-Count 字段记录资源的总数量,link header作为其他资源的分页导航。
     *
     * @return
     */
    public void pagedResponse(
            HttpServletRequest request,
            HttpServletResponse response,
            Long resourceCount, Integer currentPage, Integer pageSize) {
        if (request == null || response == null) return;
        response.setHeader(ResourceCount, Long.toString(resourceCount));
        if (resourceCount == 0) return;
        if (currentPage == null) currentPage = new Integer(PageArg.DefaultPage);
        if (pageSize == null) pageSize = new Integer(PageArg.DefaultSize);
        String baseUri = "<" + request.getRequestURL().append("?").toString() + request.getQueryString() + ">";
        long firstPage = currentPage == 1 ? -1 : 1;
        long prevPage = currentPage == 1 ? -1 : currentPage - 1;
        long lastPage = resourceCount % pageSize == 0 ? resourceCount / pageSize : resourceCount / pageSize + 1;
        long nextPage = currentPage == lastPage ? -1 : currentPage + 1;
        lastPage = currentPage == lastPage ? -1 : lastPage;
        Map<String, String> map = new HashMap<>();
        if (firstPage != -1)
            map.put("rel='first',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(firstPage)));
        if (prevPage != -1) map.put("rel='prev',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(prevPage)));
        if (nextPage != -1) map.put("rel='next',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(nextPage)));
        if (lastPage != -1) map.put("rel='last',", baseUri.replaceAll("page=\\d+", "page=" + Long.toString(lastPage)));
        response.setHeader(ResourceLink, linkMap(map));
    }
    private String linkMap(Map<String, String> map) {
        StringBuffer links = new StringBuffer("");
        for (String key : map.keySet()) {
            links.append(map.get(key)).append("; ").append(key);
        }
        return links.toString();
    }
    protected Integer reducePage(Integer page) {
        if (page != null || page > 0) {
            page = page - 1;
            return page;
        }
        return 1;
    }
    protected String getClientId(HttpServletRequest request){
        String userAgent = "";
        Enumeration<String> headers = request.getHeaders("User-Agent");
        while (headers.hasMoreElements()){
            String s = headers.nextElement();
            if (!s.contains("jetty")){
                userAgent = s;
            }
        }
        return StringUtils.isEmpty(userAgent) ? "" : userAgent.split(" ").length>1?userAgent.split(" ")[1]:userAgent.split(" ")[0];
    }
}

+ 75 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/controller/EnvelopRestEndPoint.java

@ -0,0 +1,75 @@
package com.yihu.wlyy.common.controller;
import com.yihu.wlyy.common.constants.BizObject;
import com.yihu.wlyy.common.util.ObjectId;
import com.yihu.wlyy.util.Envelop;
import org.springframework.beans.factory.annotation.Value;
import java.util.List;
/**
 * REST风格控控制器基类。此控制器用于对API进行校验,并处理平台根层级的业务,如API参数校验,错误及返回码设定等。
 * <p>
 * 根层级的校验,如果是正确的,直接返回HTTP代码200,若出错,则会将HTTP返回代码设置为1X或2X,并在HTTP响应体中包含响应的信息。
 * HTTP响应体格式为JSON。
 * + 成功:会根据各业务逻辑自行决定要返回的数据,各业务模块的返回结构不同。
 * + 失败:{"code":"错误代码", "message":"错误原因"}
 *
 * @author zhiyong
 * @author Sand
 */
public class EnvelopRestEndPoint extends BaseRestEndPoint {
    @Value("${deploy.region}")
    Short deployRegion = 3502;
    /**
     * 返回一个信封对象。信封对象的返回场景参见 Envelop.
     *
     * @param modelList
     * @param totalCount
     * @return
     */
    protected Envelop getResult(List modelList, int totalCount) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        envelop.setDetailModelList(modelList);
        envelop.setTotalCount(totalCount);
        return envelop;
    }
    public Envelop getPageResult(List detailModelList, int totalCount, int currPage, int rows) {
        Envelop result = new Envelop();
        result.setSuccessFlg(true);
        result.setDetailModelList(detailModelList);
        result.setTotalCount(totalCount);
        result.setCurrPage(currPage);
        result.setPageSize(rows);
        if (result.getTotalCount() % result.getPageSize() > 0) {
            result.setTotalPage((result.getTotalCount() / result.getPageSize()) + 1);
        } else {
            result.setTotalPage(result.getTotalCount() / result.getPageSize());
        }
        return result;
    }
    public Envelop failed(String errMsg){
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        envelop.setErrorMsg(errMsg);
        return envelop;
    }
    public Envelop success(Object object){
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(true);
        envelop.setObj(object);
        return envelop;
    }
    protected String getObjectId(BizObject bizObject){
        return new ObjectId(deployRegion, bizObject).toString();
    }
}

+ 120 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/exception/ApiException.java

@ -0,0 +1,120 @@
package com.yihu.wlyy.common.exception;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.wlyy.common.constants.ErrorCode;
import com.yihu.wlyy.common.util.StringBuilderEx;
import com.yihu.wlyy.util.query.SpringContext;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import java.util.List;
/**
 * API 异常。使用错误代码初始化,并可接收用于补充错误消息的参数。
 * 用于描述错误代码的信息配置在各服务配置文件中,并由服务配置中心统一管理。
 *
 * 错误描述结构,结构(字段errors对资源而言,REST规范错误不包含此结构):
 * {
 *    "message": "Validation Failed",
 *    "document_url": "https://ehr.yihu.com/docs/api/somewhere"
 *    "errors": [
 *        {
 *            "resource": "User",
 *            "field": "title",
 *            "code": "missing_field"
 *        }
 *    ]
 * }
 *
 * @author Sand
 * @version 1.0
 * @created 2015.12.20 16:05
 */
public class ApiException extends RuntimeException {
    public HttpStatus getHttpStatus() {
        return httpStatus;
    }
    HttpStatus httpStatus;
    ErrorCode errorCode;        // 用于从配置环境中提取错误信息
    String[] errorArgs;         // 格式化配置环境中的错误信息
    String documentURL;
    String message;             // 错误消息
    List<ResourceError> resourceErrors;         // 资源具体错误描述
    private ApiException(HttpStatus httpStatus, ErrorCode errorCode, String documentURL, List<ResourceError> resourceErrors, String... errorArgs){
        this.httpStatus = httpStatus;
        this.errorCode = errorCode;
        this.errorArgs = errorArgs;
        this.documentURL = documentURL;
        this.resourceErrors = resourceErrors;
    }
    public ApiException(HttpStatus httpStatus, ErrorCode errorCode, String documentURL, String... errorArgs){
        this(httpStatus, errorCode, documentURL, null, errorArgs);
    }
    public ApiException(HttpStatus httpStatus, ErrorCode errorCode){
        this(httpStatus, errorCode, null, null, null);
    }
    public ApiException(HttpStatus httpStatus, String message){
        this(httpStatus, null, null, null, null);
        this.message = message;
    }
    public ApiException(ErrorCode errorCode, String... errorArgs) {
        this(HttpStatus.FORBIDDEN, errorCode, null, null, errorArgs);
    }
    // legacy support
    public ApiException(ErrorCode errorCode) {
        this(HttpStatus.FORBIDDEN, errorCode, null, null, null);
    }
    @Override
    public String toString(){
        try {
            return toJson();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }
    private String toJson() throws JsonProcessingException {
        Environment environment = SpringContext.getService(Environment.class);
        message = errorCode == null ? message : environment.getProperty(errorCode.getErrorCode());
        if (null != message && null != errorArgs && errorArgs.length > 0){
            StringBuilderEx util = new StringBuilderEx(message);
            for (int i = 0; i < errorArgs.length; ++i){
                util.replace("{" + i + "}", errorArgs[i]);
            }
            message = util.toString();
        }
        ObjectMapper objectMapper = SpringContext.getService(ObjectMapper.class);
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("message", message != null ? message : "");
        objectNode.put("document_url", documentURL != null ? documentURL : "");
        if (resourceErrors != null) objectNode.put("errors", objectMapper.writeValueAsString(resourceErrors));
        return objectNode.toString();
    }
    @Override
    public String getMessage() {
        return message;
    }
}

+ 42 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/exception/ResourceError.java

@ -0,0 +1,42 @@
package com.yihu.wlyy.common.exception;
/**
 * @author Sand
 * @version 1.0
 * @created 2016.02.27 15:14
 */
public class ResourceError {
    String resource;
    String field;
    String code;
    public ResourceError(String resource, String field, String code) {
        this.resource = resource;
        this.field = field;
        this.code = code;
    }
    public String getResource() {
        return resource;
    }
    public void setResource(String resource) {
        this.resource = resource;
    }
    public String getField() {
        return field;
    }
    public void setField(String field) {
        this.field = field;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
}

+ 198 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/FieldCondition.java

@ -0,0 +1,198 @@
package com.yihu.wlyy.common.query;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.1
 */
public class FieldCondition {
    private String col;       //过滤字段 ,不可为空
    private String logic;    //过滤方式,默认为=;   =, sw, ew, like, >, <, between, >=, <=
    private List<Object> val;//过滤值, 值为空则不过滤
    private String group;   //分组,  多个过滤器中的group相同时  用or连接
    private String tableCol;//数据库字段, 初始化根据实体自动设置, user设置无效
    public FieldCondition() {
    }
    public FieldCondition(String col, Object val) {
        this.col = col;
        this.addVal(val);
    }
    public FieldCondition(String col, String logic, Object ... vals) {
        this.col = col;
        this.logic = logic;
        this.addVal(vals);
    }
    public FieldCondition(String col, String logic, List<Object> val, String group) {
        this.col = col;
        this.logic = logic;
        this.val = val;
        this.group = group;
    }
    /**
     * 格式化过滤条件
     * @param modelName 视图名
     * @param isSql true:返回sql形式, false:返回jpa形式
     * @return
     */
    public String format(String modelName, boolean isSql){
        if(getCol()==null || getCol().equals("") || getVal()==null || getVal().size()==0)
            return "";
        String val = getValMapping();
        if(val==null)
            return "";
        String rs = (isSql ? getTableCol() : getCol()) + " " + getLogic() + " " + val;
        if(modelName.trim().equals(""))
            return " " + rs;
        return " " +modelName + "." + rs;
    }
    /**
     * 格式化过滤条件
     * @return 返回jpa形式
     */
    public String format(){
        return format("", false);
    }
    /**
     * 格式化过滤条件
     * @return 返回sql形式
     */
    public String formatSql(){
        return format("", true);
    }
    /**
     * 判断是否存在分组信息
     * @return
     */
    public boolean isGroup(){
        return !(getGroup()==null || "".equals(getGroup()));
    }
    /**
     * 添加值
     * @param vals
     */
    public void addVal(Object ... vals){
        if(this.val==null)
            this.val = new ArrayList<>();
        for(Object val:vals){
            this.val.add(val);
        }
    }
    /**
     * 判断数据表是否包含有该过滤字段
     * @return
     */
    public boolean isValid() {
        return !StringUtils.isEmpty(getTableCol()) && !(getVal()==null || getVal().size()==0)
                 && !(getCol()==null || getCol().equals("")) && isLogicValid();
    }
    /**
     * 判断查询方式是否符合规范
     * @return
     */
    public boolean isLogicValid(){
        String logic = getLogic();
        if(logic.equals("=") || logic.equals("like") || logic.equals("sw") || logic.equals("ew") ||
                logic.equals("<") || logic.equals(">") || logic.equals(">=") || logic.equals("<=") ||
                    logic.equals("in") || logic.equals("not in") || logic.equals("between"))
            return true;
        return false;
    }
    /**
     * 获取占位符
     * @return
     */
    private String getValMapping(){
        String logic = getLogic();
        String val = ":" + getCol();
        if(logic.equals("in") || logic.equals("not in"))
            return  "("+val+") ";
        if(logic.equals("between"))
            return val + "1 and " +val+"2 ";
        if(logic.equals("=") || logic.equals("like") || logic.equals("sw") || logic.equals("ew") ||
                logic.equals("<") || logic.equals(">") || logic.equals(">=") || logic.equals("<=")){
            return val;
        }
        return null;
    }
    /**
     * 格式化 值, 不支持between
     * between形式: 调用getVal(), 获取值,  占位符为 between col + "1" and  col + "2"
     * @return
     */
    public Object formatVal(){
        if(getLogic().equals("sw"))
            return "%"+getVal().get(0);
        if (getLogic().equals("ew"))
            return getVal().get(0)+"%";
        if (getLogic().equals("like"))
            return "%"+getVal().get(0)+"%";
        if(getLogic().equals("in") || getLogic().equals("not in"))
            return getVal();
        return getVal().get(0);
    }
    /************************************************************************************/
    /***************            getter  &  setter                            ************/
    /***************                                                         ************/
    /************************************************************************************/
    public String getCol() {
        return col;
    }
    public void setCol(String col) {
        this.col = col;
    }
    public String getLogic() {
        if(logic==null || "".equals(logic))
            return "=";
        return logic;
    }
    public void setLogic(String logic) {
        this.logic = logic;
    }
    public List<Object> getVal() {
        return val;
    }
    public void setVal(List<Object> val) {
        this.val = val;
    }
    public String getGroup() {
        return group;
    }
    public void setGroup(String group) {
        this.group = group;
    }
    public String getTableCol() {
        return tableCol;
    }
    public void setTableCol(String tableCol) {
        this.tableCol = tableCol;
    }
}

+ 218 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/PageModel.java

@ -0,0 +1,218 @@
package com.yihu.wlyy.common.query;
import org.springframework.util.StringUtils;
import javax.persistence.Column;
import java.lang.reflect.Method;
import java.util.*;
/**
 * 实体查询模型。将前端的查询转换为实体查询。
 *
 * @author lincl
 * @version 1.0
 * @created 2016.2.1
 */
public class PageModel {
    private int page;                               // 页码
    private int rows;                               // 页大小
    private String[] order;                         // 排序,格式为 +f1,-f2
    private Map<String, FieldCondition> filters;    // 记录过滤器
    private String[] result;                        // 实际返回的字段
    private Class modelClass;                       // JPA实体类
    public PageModel() {
    }
    public PageModel(int page, int rows) {
        this.page = page;
        this.rows = rows;
    }
    public String format(String modelName, boolean isSql) {
        if (modelClass == null) {
            System.err.print("NullPoint: modelClass");
            return "";
        }
        Map<String, FieldCondition> filters = getFilters();
        if (filters.size() == 0)
            return "";
        Map<String, String> whMap = new HashMap<>();
        FieldCondition fieldCondition;
        String wh = "";
        for (String k : filters.keySet()) {
            fieldCondition = filters.get(k);
            if (!fieldCondition.isValid())
                continue;
            if (fieldCondition.isGroup()) {
                String str = whMap.get(fieldCondition.getGroup());
                if (str == null)
                    str = "(" + fieldCondition.format(modelName, isSql);
                else
                    str += " or " + fieldCondition.format(modelName, isSql);
                whMap.put(fieldCondition.getGroup(), str);
            } else {
                if (wh.equals(""))
                    wh = fieldCondition.format(modelName, isSql);
                else
                    wh += " and " + fieldCondition.format(modelName, isSql);
            }
        }
        for (String k : whMap.keySet()) {
            wh += " and " + whMap.get(k) + ") ";
        }
        return wh;
    }
    private String getTableCol(String field) {
        try {
            Method method = modelClass.getMethod("get" + firstLetterToUpper(field));
            Column column = method.getDeclaredAnnotation(Column.class);
            if (column != null) {
                return column.name();
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
    public String formatSqlOrder(String modelName) {
        return formatOrder(modelName, true);
    }
    public String formatSqlOrder() {
        return formatSqlOrder("");
    }
    public String formatOrder() {
        return formatOrder("", false);
    }
    public String formatOrder(String modelName, boolean isSql) {
        if (modelClass == null) {
            System.err.print("NullPoint: modelClass");
            return "";
        }
        if (order == null || order.length == 0)
            return "";
        List<String> ls = new ArrayList<>();
        String tmp = "";
        if (isSql) {
            for (String item : order) {
                tmp = getTableCol(item);
                if (!StringUtils.isEmpty(tmp))
                    ls.add(tmp);
            }
        } else
            for (String item : order) {
                tmp = getTableCol(item);
                if (!StringUtils.isEmpty(tmp))
                    ls.add(item);
            }
        return arrayJoin(ls, StringUtils.isEmpty(modelName) ? "," : "," + modelName + ".", 1);
    }
    public String arrayJoin(Collection<String> ls, String joinStr, int offer) {
        if (ls == null || ls.size() == 0)
            return "";
        String tmp = "";
        for (String str : ls) {
            tmp += joinStr + str;
        }
        return tmp.substring(offer);
    }
    public String formatWithOrder(String modelName) {
        return format(modelName, false) + " order by " + formatOrder(modelName, false);
    }
    public String formatSqlWithOrder(String modelName) {
        return formatSql(modelName) + " order by " + formatSqlOrder(modelName);
    }
    public String format() {
        return format("", false);
    }
    public String formatSql(String modelName) {
        return format(modelName, true);
    }
    public String formatSql() {
        return formatSql("");
    }
    public Object getFieldVal(String field) {
        return filters.get(field).getVal();
    }
    public void setFieldVal(String field, List val) {
        filters.get(field).setVal(val);
    }
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public int getRows() {
        return rows;
    }
    public void setRows(int rows) {
        this.rows = rows;
    }
    public Map<String, FieldCondition> getFilters() {
        return filters == null ? new HashMap<>() : filters;
    }
    public void setFilters(Map<String, FieldCondition> filters) {
        this.filters = filters;
    }
    public void addFieldCondition(FieldCondition fieldCondition) {
        if (filters == null)
            filters = new HashMap<>();
        filters.put(fieldCondition.getCol(), fieldCondition);
    }
    public String[] getOrder() {
        return order;
    }
    public void setOrder(String[] order) {
        this.order = order;
    }
    public String[] getResult() {
        return result;
    }
    public void setResult(String[] result) {
        this.result = result;
    }
    public Class getModelClass() {
        return modelClass;
    }
    public void setModelClass(Class modelClass) {
        this.modelClass = modelClass;
        Map<String, FieldCondition> map = getFilters();
        for (String key : map.keySet()) {
            map.get(key).setTableCol(getTableCol(key));
        }
    }
    public static String firstLetterToUpper(String str) {
        if (str == null || "".equals(str.trim())) {
            return "";
        }
        return str.replaceFirst(("" + str.charAt(0)), ("" + str.charAt(0)).toUpperCase());
    }
}

+ 28 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/ReturnIdPstCreator.java

@ -0,0 +1,28 @@
package com.yihu.wlyy.common.query;
import org.springframework.jdbc.core.PreparedStatementCreator;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/5/6
 */
public class ReturnIdPstCreator implements PreparedStatementCreator {
    String sql;
    public ReturnIdPstCreator(String sql){
        this.sql = sql;
    }
    @Override
    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
        return connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    }
}

+ 303 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/URLHqlQueryParser.java

@ -0,0 +1,303 @@
package com.yihu.wlyy.common.query;
import javafx.util.Pair;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.*;
import org.hibernate.metadata.ClassMetadata;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * URL 查询串解析器。
 *
 * @author lincl
 * @author Sand
 * @version 1.0
 * @created 2016.02.05 10:17
 */
public class URLHqlQueryParser<T> {
    private String fields;
    private String filters;
    private String orders;
    Session session;
    Class<T> entityCls;
    public URLHqlQueryParser(String fields, String filters, String orders) {
        this.fields = fields;
        this.filters = filters;
        this.orders = orders;
    }
    public URLHqlQueryParser(String filters){
        this.filters = filters;
    }
    public URLHqlQueryParser setSession(Session session) {
        this.session = session;
        return this;
    }
    public URLHqlQueryParser setEntityClass(Class<T> cls) {
        this.entityCls = cls;
        return this;
    }
    /**
     * 生成搜索语句.
     *
     * @return
     */
    public Criteria makeCriteriaQuery() {
        Criteria criteria = session.createCriteria(entityCls);
        ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entityCls);
//        makeSelection(criteria, classMetadata);
        makeOrderBy(criteria, classMetadata);
        makeWhere(criteria, classMetadata);
        return criteria;
    }
    /**
     * 生成count语句。
     *
     * @return
     */
    public Criteria makeCriteriaCountQuery() {
        Criteria criteria = session.createCriteria(entityCls);
        ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entityCls);
        criteria.setProjection(Projections.rowCount());
        makeWhere(criteria, classMetadata);
        return criteria;
    }
    /**
     * 生成返回值字段。
     *
     * @param criteria
     * @param classMetadata
     */
    private void makeSelection(Criteria criteria, ClassMetadata classMetadata) {
    }
    /**
     * +code 以code字段进行升序排序
     * -code 以code字段进行降序排序
     * 生成排序字段。
     *
     * @param criteria
     * @param classMetadata
     */
    private void makeOrderBy(Criteria criteria, ClassMetadata classMetadata) {
        if (StringUtils.isNotEmpty(orders)) {
            String[] orderArray = orders.split(",");
            for(String elem : orderArray){
//                try {
//                    classMetadata.getPropertyType(elem);
//                }catch (Exception e){
//                    throw new IllegalArgumentException("the property not found!");
//                }
                criteria = elem.startsWith("+") ?
                        criteria.addOrder(Order.asc(elem.substring(1)))
                        : criteria.addOrder(Order.desc(elem.substring(1)));
            }
        }
    }
    /**
     * like:使用"?"来表示,如:name?'%医'
     * not in:使用"<>"来表示并用","逗号对值进行分隔,如:status=2,3,4,5
     * in:使用"="来表示并用","逗号对值进行分隔,如:status=2,3,4,5
     * =:使用"="来表示,如:status=2
     * >=:使用大于号和大于等于语法,如:createDate>2012
     * <=:使用小于号和小于等于语法,如:createDate<=2015
     * 分组:在条件后面加上空格,并设置分组号,如:createDate>2012 g1,具有相同组名的条件将使用or连接
     * 多条件组合:使用";"来分隔
     * <p>
     * 生成 where 条件。
     *
     * @param criteria
     * @param classMetadata
     */
    private void makeWhere(Criteria criteria, ClassMetadata classMetadata) {
        if (StringUtils.isEmpty(filters)) return;
        Map<String, List<Criterion>> criterionMap = new HashMap<>();
        String[] filterArray = filters.split(";");
        List<Criterion> groupCriterion = new ArrayList<>();
        for (int i = 0; i < filterArray.length; ++i) {
            String[] tokens = filterArray[i].split(" ");
            if (tokens.length > 2){
                for(int j=1; j<tokens.length; j++){
                    if(j==tokens.length-1)
                        tokens[1] = tokens[j];
                    else
                        tokens[0] += " " + tokens[j] ;
                }
            }
//            if (tokens.length > 2) throw new IllegalArgumentException("无效过滤参数");
            String group = null;
            if (tokens.length >= 2) group = tokens[1];
            Criterion criterion = splitFilter(tokens[0], classMetadata);
            if (group == null)
                group = Integer.toString(i);
            criterionMap.put(group,
                    makeGroupCriterion(criterionMap.get(group), criterion));
        }
        addWhere(criteria, criterionMap);
    }
    private void addWhere(Criteria criteria, Map<String, List<Criterion>> criterionMap) {
        List<Criterion> ls;
        for (String group : criterionMap.keySet()){
            ls = criterionMap.get(group);
            if(ls.size()>1)
                criteria.add(
                        Restrictions.or(ls.toArray(new Criterion[ls.size()]))
                );
            else
                criteria.add(
                        Restrictions.and(ls.toArray(new Criterion[ls.size()]))
                );
        }
    }
    protected List<Criterion> makeGroupCriterion(List<Criterion> ls, Criterion criterion){
        (ls = ls == null ? new ArrayList<>() : ls)
                .add(criterion);
        return ls;
    }
    protected Criterion splitFilter(String filter, ClassMetadata classMetadata) {
        Criterion criterion = null;
        if (filter.contains("?")) {
            Pair<Property, Object> pair = getPair(filter, "[?]", classMetadata);
            criterion = pair.getKey().like("%"+pair.getValue()+"%");
        } else if (filter.contains("<>")) {
            Pair<Property, Object> pair = getPair(filter, "<>", classMetadata);
            if (pair.getValue().getClass().isArray()) {
                criterion = pair.getKey().in((Object[])pair.getValue());
            } else {
                criterion = pair.getKey().eq(pair.getValue());
            }
            criterion = Restrictions.not(criterion);
        }  else if (filter.contains(">=")) {
            Pair<Property, Object> pair = getPair(filter, ">=", classMetadata);
            criterion = pair.getKey().ge(pair.getValue());
        } else if (filter.contains(">")) {
            Pair<Property, Object> pair = getPair(filter, ">", classMetadata);
            //todo:  转成对应类型
            criterion = pair.getKey().gt(pair.getValue());
        } else if (filter.contains("<=")) {
            Pair<Property, Object> pair = getPair(filter, "<=", classMetadata);
            criterion = pair.getKey().le(pair.getValue());
        } else if (filter.contains("<")) {
            Pair<Property, Object> pair = getPair(filter, "<", classMetadata);
            criterion = pair.getKey().lt(pair.getValue());
        } else if (filter.contains("=")) {
            Pair<Property, Object> pair = getPair(filter, "=", classMetadata);
            if (pair.getValue().getClass().isArray()) {
                criterion = pair.getKey().in((Object[])pair.getValue());
            } else {
                criterion = pair.getKey().eq(pair.getValue());
            }
        }
        return criterion;
    }
    protected Pair<Property, Object> getPair(String filter, String splitter, ClassMetadata classMetadata) throws IllegalArgumentException {
        String[] tokens = filter.split(splitter);
        String valStr = tokens[1];
        Object val = tokens[1];
        try {
            if((splitter.equals("=") || splitter.equals("<>")) && valStr.contains(",")){
                val = formatVal(tokens[0], valStr, true);
            }
            else if(!splitter.equals("[?]")){
                val = formatVal(tokens[0], valStr, false);
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return new Pair(Property.forName(tokens[0]), val);
    }
    private Object formatVal(String fileName, String valStr, boolean isArr) throws NoSuchFieldException {
        Object val = "";
        if(isLong(fileName)){
            if(isArr){
                val = strToLongArr(valStr);
            }else
                val = Long.parseLong(valStr);
        }else if(isInteger(fileName)){
            if(isArr){
                val = strToIntArr(valStr);
            }else
                val = Integer.parseInt(valStr);
        }else {
            if(isArr)
                val = valStr.split(",");
            else
                val = valStr;
        }
        return val;
    }
    private Long[] strToLongArr(String valStr){
        String[] strArr = valStr.split(",");
        Long[] longArr = new Long[strArr.length];
        for(int i=0; i<strArr.length; i++){
            longArr[i] = Long.parseLong(strArr[i]);
        }
        return longArr;
    }
    private Integer[] strToIntArr(String valStr){
        String[] strArr = valStr.split(",");
        Integer[] intArr = new Integer[strArr.length];
        for(int i=0; i<strArr.length; i++){
            intArr[i] = Integer.parseInt(strArr[i]);
        }
        return intArr;
    }
    private boolean isInteger(String fieldName) throws NoSuchFieldException {
        Field field = getField(fieldName);
        return field.getType().equals(Integer.class) || field.getType().equals(Integer.TYPE);
    }
    private boolean isLong(String fieldName) throws NoSuchFieldException {
        Field field = getField(fieldName);
        return field.getType().equals(Long.class) || field.getType().equals(Long.TYPE);
    }
    private Field getField(String fieldName) throws NoSuchFieldException {
        Field f;
        try {
            f = entityCls.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            f = entityCls.getSuperclass().getDeclaredField(fieldName);
        }
        return f;
    }
}

+ 63 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/query/UpdatePstCallback.java

@ -0,0 +1,63 @@
package com.yihu.wlyy.common.query;
import javafx.util.Pair;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/5/6
 */
public class UpdatePstCallback implements PreparedStatementCallback<Integer> {
    List<Pair<Type, Object>> values;
    public UpdatePstCallback(List<Pair<Type, Object>> values){
        this.values = values;
    }
    @Override
    public Integer doInPreparedStatement(PreparedStatement preparedStatement) throws SQLException, DataAccessException {
        //设参
        setParams(preparedStatement);
        //执行语句
        preparedStatement.executeUpdate();
        //获取id
        int key = getKey(preparedStatement);
        //关闭
        preparedStatement.close();
        return key;
    }
    private int getKey(PreparedStatement preparedStatement) throws SQLException {
        int autoIncKeyFromApi = -1;
        ResultSet rs = preparedStatement.getGeneratedKeys();
        if (rs.next()) {
            autoIncKeyFromApi = rs.getInt(1);
        }
        rs.close();
        rs = null;
        return autoIncKeyFromApi;
    }
    public PreparedStatement setParams(PreparedStatement pst) throws SQLException {
        int i=1;
        for(Pair<Type, Object> pair : values){
            pst.setObject(i, pair.getValue());
            i++;
        }
        return pst;
    }
}

+ 526 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/ObjectId.java

@ -0,0 +1,526 @@
package com.yihu.wlyy.common.util;
import com.yihu.wlyy.common.constants.BizObject;
import java.io.Serializable;
import java.net.NetworkInterface;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * <p>对象全局唯一ID.</p>
 * <p>
 * 本类修改自 MongoDB 的org.bson.ObjectId. ID生成原则:
 * <lo>
 * <li>地区: 区分数据地理来源, 到市/自治区一级, 即四位数字, 如: 3502 表示厦门</li>
 * <li>模块: 区分业务对象, 如: 0001表示卡对象</li>
 * <li>时间: 数据产生时间</li>
 * <li>机器: 数据产生时, 位于哪台机器上</li>
 * <li>进程: 产生数据的进程ID</li>
 * <li>增量: 在上述所有因素均相同时, 并发序数</li>
 * </lo>
 * <p>
 * <p>由16个字节构成, 分为以下段:</p>
 * <table border="1">
 * <caption>ObjectID layout</caption>
 * <tr>
 * <td>0</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td><td>12</td><td>13</td><td>14</td><td>15</td>
 * </tr>
 * <tr>
 * <td colspan="2">地区</td><td colspan="2">模块</td><td colspan="4">时间</td><td colspan="3">机器名称</td> <td colspan="2">进程ID</td><td colspan="3">并发量</td>
 * </tr>
 * </table>
 * <p>
 * <p>本类实例不可修改.</p>
 */
public final class ObjectId implements Comparable<ObjectId>, Serializable {
    private static final long serialVersionUID = 3503056789654483072L;
    private static final int BYTE_ARRAY_LENGTH = 16;
    private static final int LOW_ORDER_THREE_BYTES = 0x00ffffff;
    private static final short ADMIN_REGION_IDENTIFIER;
    private static final int MACHINE_IDENTIFIER;
    private static final short PROCESS_IDENTIFIER;
    private static final AtomicInteger NEXT_COUNTER = new AtomicInteger(new SecureRandom().nextInt());
    private static final char[] HEX_CHARS = new char[]{
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private final short adminRegionIdentifier;
    private final short bizModuleIdentifier;
    private final int timestamp;
    private final int machineIdentifier;
    private final short processIdentifier;
    private final int counter;
    /**
     * 创建一个新的ID对象.
     *
     * @return 新创建的ID对象.
     */
    public static ObjectId get(final short adminRegionIdentifier, final BizObject bizModuleIdentifier) {
        return new ObjectId(adminRegionIdentifier, bizModuleIdentifier);
    }
    /**
     * 检查是否为一个合法的 ObjectId 对象.
     *
     * @param hexString 一个可能转换为对象ID的字符串.
     * @return 字符串是否为合法的ObjectId.
     * @throws IllegalArgumentException hexString为空的情况下抛出.
     */
    public static boolean isValid(final String hexString) {
        if (hexString == null) {
            throw new IllegalArgumentException();
        }
        int len = hexString.length();
        if (len != BYTE_ARRAY_LENGTH * 2) {
            return false;
        }
        for (int i = 0; i < len; i++) {
            char c = hexString.charAt(i);
            if (c >= '0' && c <= '9') {
                continue;
            }
            if (c >= 'a' && c <= 'f') {
                continue;
            }
            if (c >= 'A' && c <= 'F') {
                continue;
            }
            return false;
        }
        return true;
    }
    /**
     * 获取产生该ID对象的机器标识.
     *
     * @return 机器标识的int表示.
     */
    public static int getGeneratedMachineIdentifier() {
        return MACHINE_IDENTIFIER;
    }
    /**
     * 获取产生该ID对象的进程标识.
     *
     * @return 进程ID.
     */
    public static int getGeneratedProcessIdentifier() {
        return PROCESS_IDENTIFIER;
    }
    /**
     * 创建一个ID对象.
     */
    public ObjectId(final short adminRegionIdentifier,
                    final BizObject bizModuleIdentifier) {
        this(adminRegionIdentifier, bizModuleIdentifier, new Date());
    }
    /**
     * 以日期初始化一个ID对象.
     *
     * @param date 日期对象.
     */
    public ObjectId(final short adminRegionIdentifier,
                    final BizObject bizModuleIdentifier,
                    final Date date) {
        this(adminRegionIdentifier, bizModuleIdentifier, dateToTimestampSeconds(date), MACHINE_IDENTIFIER, PROCESS_IDENTIFIER, NEXT_COUNTER.getAndIncrement(), false);
    }
    /**
     * 以日期与计数初始化一个ID对象.
     *
     * @param date    日期
     * @param counter 计数
     * @throws IllegalArgumentException 在计数值的高位为非零的情况下抛出.
     */
    public ObjectId(final short adminRegionIdentifier,
                    final BizObject bizModuleIdentifier,
                    final Date date,
                    final int counter) {
        this(adminRegionIdentifier, bizModuleIdentifier, date, MACHINE_IDENTIFIER, PROCESS_IDENTIFIER, counter);
    }
    /**
     * 以日期, 机器ID, 进程ID以及计数初始化一个ID对象.
     *
     * @param date              the date
     * @param machineIdentifier the machine identifier
     * @param processIdentifier the process identifier
     * @param counter           the counter
     * @throws IllegalArgumentException 在机器ID或计数值的高位为非零的情况下抛出.
     */
    public ObjectId(final short adminRegionIdentifier,
                    final BizObject bizModuleIdentifier,
                    final Date date,
                    final int machineIdentifier,
                    final short processIdentifier,
                    final int counter) {
        this(adminRegionIdentifier, bizModuleIdentifier, dateToTimestampSeconds(date), machineIdentifier, processIdentifier, counter);
    }
    /**
     * 以EPO毫秒数, 机器ID, 进程ID以及计数初始化一个ID对象.
     *
     * @param timestamp         the time in seconds
     * @param machineIdentifier the machine identifier
     * @param processIdentifier the process identifier
     * @param counter           the counter
     * @throws IllegalArgumentException 在机器ID或计数值的高位为非零的情况下抛出.
     */
    public ObjectId(final short adminRegionIdentifier,
                    final BizObject bizModuleIdentifier,
                    final int timestamp,
                    final int machineIdentifier,
                    final short processIdentifier,
                    final int counter) {
        this(adminRegionIdentifier, bizModuleIdentifier, timestamp, machineIdentifier, processIdentifier, counter, true);
    }
    private ObjectId(final short adminRegionIdentifier,
                     final BizObject bizModuleIdentifier,
                     final int timestamp,
                     final int machineIdentifier,
                     final short processIdentifier,
                     final int counter,
                     final boolean checkCounter) {
        if ((machineIdentifier & 0xff000000) != 0) {
            throw new IllegalArgumentException("机器ID必须位于 0 和 16777215 之间(即三个字节).");
        }
        if (checkCounter && ((counter & 0xff000000) != 0)) {
            throw new IllegalArgumentException("计数值必须位于 0 和 16777215 之间(即三个字节).");
        }
        this.adminRegionIdentifier = adminRegionIdentifier;
        this.bizModuleIdentifier = bizModuleIdentifier.getBizObject();
        this.timestamp = timestamp;
        this.machineIdentifier = machineIdentifier;
        this.processIdentifier = processIdentifier;
        this.counter = counter & LOW_ORDER_THREE_BYTES;
    }
    /**
     * 根据一个30个字节的字符串构造ID对象.
     *
     * @param hexString the string to convert
     * @throws IllegalArgumentException if the string is not a valid hex string representation of an ObjectId
     */
    public ObjectId(final String hexString) {
        this(parseHexString(hexString));
    }
    /**
     * 以字节数组创建一个对象ID.
     *
     * @param bytes 字节数组
     * @throws IllegalArgumentException 在字节数组为空, 或长度小于 BYTE_ARRAY_LENGTH 的时候抛出.
     */
    public ObjectId(final byte[] bytes) {
        if (bytes == null) {
            throw new IllegalArgumentException();
        }
        if (bytes.length != BYTE_ARRAY_LENGTH) {
            throw new IllegalArgumentException("need " + BYTE_ARRAY_LENGTH + " bytes");
        }
        adminRegionIdentifier = (short) makeInt((byte) 0, (byte) 0, bytes[0], bytes[1]);
        bizModuleIdentifier = (short) makeInt((byte) 0, (byte) 0, bytes[2], bytes[3]);
        timestamp = makeInt(bytes[4], bytes[5], bytes[6], bytes[7]);
        machineIdentifier = makeInt((byte) 0, bytes[8], bytes[9], bytes[10]);
        processIdentifier = (short) makeInt((byte) 0, (byte) 0, bytes[11], bytes[12]);
        counter = makeInt((byte) 0, bytes[13], bytes[14], bytes[15]);
    }
    /**
     * 转换为字节数组. 以 big-endian 顺序存储.
     *
     * @return the byte array
     */
    public byte[] toByteArray() {
        byte[] bytes = new byte[BYTE_ARRAY_LENGTH];
        bytes[0] = int1(adminRegionIdentifier);
        bytes[1] = int0(adminRegionIdentifier);
        bytes[2] = int1(bizModuleIdentifier);
        bytes[3] = int0(bizModuleIdentifier);
        bytes[4] = int3(timestamp);
        bytes[5] = int2(timestamp);
        bytes[6] = int1(timestamp);
        bytes[7] = int0(timestamp);
        bytes[8] = int2(machineIdentifier);
        bytes[9] = int1(machineIdentifier);
        bytes[10] = int0(machineIdentifier);
        bytes[11] = short1(processIdentifier);
        bytes[12] = short0(processIdentifier);
        bytes[13] = int2(counter);
        bytes[14] = int1(counter);
        bytes[15] = int0(counter);
        return bytes;
    }
    /**
     * 获取区域.
     *
     * @return 区域编码.
     */
    public short getAdminRegion() {
        return adminRegionIdentifier;
    }
    /**
     * 获取业务模块.
     *
     * @return 业务模块编码.
     */
    public short getBizModuleIdentifier() {
        return bizModuleIdentifier;
    }
    /**
     * 获取时间戳代表的日期对象.
     *
     * @return 日期对象
     */
    public Date getDate() {
        return new Date(timestamp * 1000L);
    }
    /**
     * 获取时间戳 (基于 Unix epoch 时间的秒数).
     *
     * @return 时间戳
     */
    public int getTimestamp() {
        return timestamp;
    }
    /**
     * 获取机器ID.
     *
     * @return 机器ID
     */
    public int getMachineIdentifier() {
        return machineIdentifier;
    }
    /**
     * 获取进程ID.
     *
     * @return 进程ID
     */
    public short getProcessIdentifier() {
        return processIdentifier;
    }
    /**
     * 获取计数.
     *
     * @return 计数
     */
    public int getCounter() {
        return counter;
    }
    /**
     * 将对象转换为一个含30个16进制字符的字符串表示.
     *
     * @return ID对象的16进制字符串表示.
     */
    public String toHexString() {
        char[] chars = new char[BYTE_ARRAY_LENGTH * 2];
        int i = 0;
        for (byte b : toByteArray()) {
            chars[i++] = HEX_CHARS[b >> 4 & 0xF];
            chars[i++] = HEX_CHARS[b & 0xF];
        }
        return new String(chars);
    }
    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ObjectId objectId = (ObjectId) o;
        if (adminRegionIdentifier != objectId.adminRegionIdentifier) {
            return false;
        }
        if (bizModuleIdentifier != objectId.bizModuleIdentifier) {
            return false;
        }
        if (counter != objectId.counter) {
            return false;
        }
        if (machineIdentifier != objectId.machineIdentifier) {
            return false;
        }
        if (processIdentifier != objectId.processIdentifier) {
            return false;
        }
        return timestamp == objectId.timestamp;
    }
    @Override
    public int hashCode() {
        int result = timestamp;
        result = 31 * result + adminRegionIdentifier;
        result = 31 * result + bizModuleIdentifier;
        result = 31 * result + machineIdentifier;
        result = 31 * result + (int) processIdentifier;
        result = 31 * result + counter;
        return result;
    }
    @Override
    public int compareTo(final ObjectId other) {
        if (other == null) {
            throw new NullPointerException();
        }
        byte[] byteArray = toByteArray();
        byte[] otherByteArray = other.toByteArray();
        for (int i = 0; i < BYTE_ARRAY_LENGTH; i++) {
            if (byteArray[i] != otherByteArray[i]) {
                return ((byteArray[i] & 0xff) < (otherByteArray[i] & 0xff)) ? -1 : 1;
            }
        }
        return 0;
    }
    @Override
    public String toString() {
        return toHexString();
    }
    static {
        try {
            ADMIN_REGION_IDENTIFIER = 3502;
            MACHINE_IDENTIFIER = createMachineIdentifier();
            PROCESS_IDENTIFIER = createProcessIdentifier();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // build a 2-byte machine piece based on NICs info
    private static int createMachineIdentifier() {
        int machinePiece;
        try {
            StringBuilder sb = new StringBuilder();
            Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                sb.append(ni.toString());
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    ByteBuffer bb = ByteBuffer.wrap(mac);
                    try {
                        sb.append(bb.getChar());
                        sb.append(bb.getChar());
                        sb.append(bb.getChar());
                    } catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
                        // mac with less than 6 bytes. continue
                    }
                }
            }
            machinePiece = sb.toString().hashCode();
        } catch (Throwable t) {
            // IBM的JAVA虚拟机有时候会出错, 使用随机数代替之
            machinePiece = (new SecureRandom().nextInt());
            //LOGGER.log(Level.WARNING, "根据网卡信息创建机器ID失败, 使用随机数代替", t);
        }
        machinePiece = machinePiece & LOW_ORDER_THREE_BYTES;
        return machinePiece;
    }
    // 创建进程ID. 此ID在每个类加载器不必唯一, 因为 NEXT_COUNTER 会创建一个唯一值.
    private static short createProcessIdentifier() {
        short processId;
        try {
            String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
            if (processName.contains("@")) {
                processId = (short) Integer.parseInt(processName.substring(0, processName.indexOf('@')));
            } else {
                processId = (short) java.lang.management.ManagementFactory.getRuntimeMXBean().getName().hashCode();
            }
        } catch (Throwable t) {
            processId = (short) new SecureRandom().nextInt();
            //LOGGER.log(Level.WARNING, "Failed to getEntity process identifier from JMX, using random number instead", t);
        }
        return processId;
    }
    private static byte[] parseHexString(final String s) {
        if (!isValid(s)) {
            throw new IllegalArgumentException("invalid hexadecimal representation of an ObjectId: [" + s + "]");
        }
        byte[] b = new byte[BYTE_ARRAY_LENGTH];
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
        }
        return b;
    }
    private static int dateToTimestampSeconds(final Date time) {
        return (int) (time.getTime() / 1000);
    }
    // Big-Endian 帮助函数, 因为MongoDB里的BSON数字是 litten-endian.
    private static int makeInt(final byte b3, final byte b2, final byte b1, final byte b0) {
        return (((b3) << 24) |
                ((b2 & 0xff) << 16) |
                ((b1 & 0xff) << 8) |
                ((b0 & 0xff)));
    }
    private static byte int3(final int x) {
        return (byte) (x >> 24);
    }
    private static byte int2(final int x) {
        return (byte) (x >> 16);
    }
    private static byte int1(final int x) {
        return (byte) (x >> 8);
    }
    private static byte int0(final int x) {
        return (byte) (x);
    }
    private static byte short1(final short x) {
        return (byte) (x >> 8);
    }
    private static byte short0(final short x) {
        return (byte) (x);
    }
}

+ 44 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/StringBuilderEx.java

@ -0,0 +1,44 @@
package com.yihu.wlyy.common.util;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.09.10 13:37
 */
public class StringBuilderEx {
    StringBuilder builder;
    int argIndex = 1;
    public StringBuilderEx(String string){
        this.builder = new StringBuilder(string);
    }
    public StringBuilderEx replace(String src, String dest){
        int index = builder.indexOf(src);
        builder.replace(index, index + src.length(), dest);
        return this;
    }
    public StringBuilderEx arg(String value){
        replace("%" + argIndex++, value);
        return this;
    }
    public StringBuilderEx arg(int value){
        replace("%" + argIndex++, Integer.toString(value));
        return this;
    }
    public StringBuilderEx arg(long value){
        replace("%" + argIndex++, Long.toString(value));
        return this;
    }
    public String toString(){
        return builder.toString();
    }
}

+ 129 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/URLQueryBuilder.java

@ -0,0 +1,129 @@
package com.yihu.wlyy.common.util;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * URL 查询构建器,在设置好需要的字段后,生成查询字段以方便URL使用。字段请使用Model中的名称。
 * 查询过滤器只支持单实体查询,不支持多实体联合查询,若需要联合查询,需要调用者自己根据需要调用多个服务的数据再合并。
 *
 * @author Sand
 * @version 1.0
 * @created 2016.02.05 9:46
 */
public class URLQueryBuilder {
    private List<String> fields = new ArrayList<>();
    private List<String> filters = new ArrayList<>();
    private List<String> sorter = new ArrayList<>();
    private int pageSize = 15;      // default page size
    private int pageNo = 1;         // default page number
    public URLQueryBuilder() {
    }
    /**
     * 添加要返回的字段。
     *
     * @param field
     * @return
     */
    public URLQueryBuilder addField(String field) {
        fields.add(field);
        return this;
    }
    /**
     * 添加过滤条件,
     *
     * @param field
     * @param operator
     * @param value
     * @param group    为空表示与其他的过滤条件之间的关系为 and. 若组名已存在,则与同名的过滤条件之间的关系为 or.
     * @return
     */
    public URLQueryBuilder addFilter(String field, String operator, String value, String group) {
        filters.add(field + operator + value + (StringUtils.isNotEmpty(group) ? " " + group : ""));
        return this;
    }
    public URLQueryBuilder addSorter(String field, boolean asc) {
        sorter.add(asc ? "+" : "-" + field);
        return this;
    }
    public URLQueryBuilder setPageSize(int size) {
        this.pageSize = size;
        return this;
    }
    public URLQueryBuilder setPageNumber(int pageNo) {
        this.pageNo = pageNo;
        return this;
    }
    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        if (fields.size() > 0) {
            stringBuilder.append("fields=");
            stringBuilder.append(String.join(";", fields)).append("&");
        }
        if (filters.size() > 0) {
            stringBuilder.append("filters=");
            stringBuilder.append(String.join(";", filters)).append("&");
        }
        if (sorter.size() > 0) {
            stringBuilder.append("sort=");
            stringBuilder.append(String.join(";", sorter)).append("&");
        }
        stringBuilder.append("page=").append(pageNo).append("&").append("size=").append(pageSize);
        return stringBuilder.toString();
    }
    public String toString(Map<String, Object>  params) {
        StringBuilder stringBuilder = new StringBuilder();
        int i=0;
        for (Object responseBody : params.keySet()) {
            i++;
            String encodedName = encode((String) responseBody);
            String encodedValue = encode(String.valueOf(params.get(responseBody)));
            if (i>1){
                stringBuilder.append("&");
            }
            stringBuilder.append(encodedName).append("=");
            stringBuilder.append(encodedValue);
        }
        return stringBuilder.toString();
    }
    public String encode(String source){
        try {
            return URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
    public String decode(String source){
        try {
            return URLDecoder.decode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
}

+ 15 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/util/UuidUtil.java

@ -0,0 +1,15 @@
package com.yihu.wlyy.common.util;
import java.util.UUID;
/**
 * @author 张进军
 * @date 2017/11/16 08:58
 */
public class UuidUtil {
    public static String randomUUID () {
        return UUID.randomUUID().toString().replace("-", "");
    }
}

+ 52 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/DefaultJSchUserInfo.java

@ -0,0 +1,52 @@
package com.yihu.wlyy.common.vo;
import com.jcraft.jsch.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * JSch UserInfo 的实现
 *
 * @author 张进军
 * @date 2017/12/11 16:23
 */
public class DefaultJSchUserInfo implements UserInfo {
    private static Logger logger = LoggerFactory.getLogger(DefaultJSchUserInfo.class);
    @Override
    public String getPassphrase() {
        logger.info("getPassphrase");
        return null;
    }
    @Override
    public String getPassword() {
        logger.info("getPassword");
        return null;
    }
    @Override
    public boolean promptPassword(String s) {
        logger.info("promptPassword:" + s);
        return false;
    }
    @Override
    public boolean promptPassphrase(String s) {
        logger.info("promptPassphrase:" + s);
        return false;
    }
    @Override
    public boolean promptYesNo(String s) {
        logger.info("promptYesNo:" + s);
        return true; // notice here!
    }
    @Override
    public void showMessage(String s) {
        logger.info("showMessage:" + s);
    }
}

+ 107 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisCacheAuthorization.java

@ -0,0 +1,107 @@
package com.yihu.wlyy.common.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
 * 缓存授权
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
public class MRedisCacheAuthorization implements Serializable{
    public Integer id; // 主键
    private String categoryCode; // 缓存分类编码
    private String appId; // 应用ID
    private String authorizedCode; // 授权码
    private String remark; // 备注
    private Date createDate; // 创建时间
    private String creator; // 创建者
    private Date modifyDate; // 修改时间
    private String modifier; // 修改者
    public MRedisCacheAuthorization() {
    }
    public MRedisCacheAuthorization(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getAuthorizedCode() {
        return authorizedCode;
    }
    public void setAuthorizedCode(String authorizedCode) {
        this.authorizedCode = authorizedCode;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 91 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisCacheCategory.java

@ -0,0 +1,91 @@
package com.yihu.wlyy.common.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
 * 缓存分类
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
public class MRedisCacheCategory implements Serializable{
    public Integer id; // 主键
    private String name; // 缓存分类名称
    private String code; // 缓存分类编码
    private String remark; // 备注
    private Date createDate; // 创建时间
    private String creator; // 创建者
    private Date modifyDate; // 修改时间
    private String modifier; // 修改者
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 127 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisCacheKeyRule.java

@ -0,0 +1,127 @@
package com.yihu.wlyy.common.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
 * 缓存Key规则
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
public class MRedisCacheKeyRule implements Serializable{
    public Integer id; // 主键
    private String name; // 规则名称
    private String code; // 规则编码
    private String categoryCode; // 缓存分类编码
    private String expression; // 规则表达式
    private String expireTime; // 过期时间,单位秒
    private String remark; // 备注
    private Date createDate; // 创建时间
    private String creator; // 创建者
    private Date modifyDate; // 修改时间
    private String modifier; // 修改者
    private String categoryName; // 缓存分类名称
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    public String getExpression() {
        return expression;
    }
    public void setExpression(String expression) {
        this.expression = expression;
    }
    public String getExpireTime() {
        return expireTime;
    }
    public void setExpireTime(String expireTime) {
        this.expireTime = expireTime;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    public String getCategoryName() {
        return categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
}

+ 136 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisMqChannel.java

@ -0,0 +1,136 @@
package com.yihu.wlyy.common.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
 * redis消息队列
 *
 * @author 张进军
 * @date 2017/11/10 11:14
 */
public class MRedisMqChannel implements Serializable{
    public Integer id; // 主键
    public String channel; // 消息队列编码
    public String channelName; // 消息队列名称
    public String messageTemplate; // 消息模版
    public String remark; // 备注
    public Date createDate; // 创建时间
    public String creator; // 创建者
    public Date modifyDate; // 修改时间
    public String modifier; // 修改者
    public String enqueuedNum; // 入列数
    public String dequeuedNum; // 出列数
    public String subscriberNum; // 订阅者数
    public String publisherNum; // 发布者数
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    public String getChannelName() {
        return channelName;
    }
    public void setChannelName(String channelName) {
        this.channelName = channelName;
    }
    public String getMessageTemplate() {
        return messageTemplate;
    }
    public void setMessageTemplate(String messageTemplate) {
        this.messageTemplate = messageTemplate;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    public String getEnqueuedNum() {
        return enqueuedNum;
    }
    public void setEnqueuedNum(String enqueuedNum) {
        this.enqueuedNum = enqueuedNum;
    }
    public String getDequeuedNum() {
        return dequeuedNum;
    }
    public void setDequeuedNum(String dequeuedNum) {
        this.dequeuedNum = dequeuedNum;
    }
    public String getSubscriberNum() {
        return subscriberNum;
    }
    public void setSubscriberNum(String subscriberNum) {
        this.subscriberNum = subscriberNum;
    }
    public String getPublisherNum() {
        return publisherNum;
    }
    public void setPublisherNum(String publisherNum) {
        this.publisherNum = publisherNum;
    }
}

+ 107 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisMqPublisher.java

@ -0,0 +1,107 @@
package com.yihu.wlyy.common.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
 * redis消息发布者
 *
 * @author 张进军
 * @date 2017/11/20 09:35
 */
public class MRedisMqPublisher implements Serializable {
    public Integer id; // 主键
    public String appId; // 应用ID
    public String authorizedCode; // 授权码
    public String channel; // 消息队列编码
    public String remark; // 备注
    public Date createDate; // 创建时间
    public String creator; // 创建者
    public Date modifyDate; // 修改时间
    public String modifier; // 修改者
    public MRedisMqPublisher() {
    }
    public MRedisMqPublisher(String channel) {
        this.channel = channel;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getAuthorizedCode() {
        return authorizedCode;
    }
    public void setAuthorizedCode(String authorizedCode) {
        this.authorizedCode = authorizedCode;
    }
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 107 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/common/vo/MRedisMqSubscriber.java

@ -0,0 +1,107 @@
package com.yihu.wlyy.common.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
/**
 * redis消息订阅者
 *
 * @author 张进军
 * @date 2017/11/13 15:14
 */
public class MRedisMqSubscriber implements Serializable {
    public Integer id; // 主键
    public String appId; // 应用ID
    public String subscribedUrl; // 订阅者服务地址
    public String channel; // 消息队列编码
    public String remark; // 备注
    public Date createDate; // 创建时间
    public String creator; // 创建者
    public Date modifyDate; // 修改时间
    public String modifier; // 修改者
    public MRedisMqSubscriber() {
    }
    public MRedisMqSubscriber(String channel) {
        this.channel = channel;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    public String getSubscribedUrl() {
        return subscribedUrl;
    }
    public void setSubscribedUrl(String subscribedUrl) {
        this.subscribedUrl = subscribedUrl;
    }
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 25 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/DataSourceConfig.java

@ -0,0 +1,25 @@
package com.yihu.wlyy.config;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
 * Created by yww on 2016/12/1.
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {
    @Bean(name="wlyyDataSource")
    @Primary // 默认数据源
    @ConfigurationProperties(prefix="spring.datasource.wlyy")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

+ 51 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/RedisConfig.java

@ -0,0 +1,51 @@
package com.yihu.wlyy.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * redis 配置
 *
 * @author 张进军
 * @date 2017/11/2 11:15
 */
@Configuration
public class RedisConfig {
    @Value("${spring.redis.host}")
    public String redisHost;
    @Value("${spring.redis.port}")
    public Integer redisPort;
    @Value("${spring.redis.password}")
    public String redisPassword;
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(redisHost);
        jedisConnectionFactory.setPort(redisPort);
        jedisConnectionFactory.setPassword(redisPassword);
        return jedisConnectionFactory;
    }
    @Bean
    RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(jedisConnectionFactory());
        return container;
    }
    @Bean
    RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setDefaultSerializer(new StringRedisSerializer());
        return template;
    }
}

+ 66 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/RepositoryWlyyConfig.java

@ -0,0 +1,66 @@
package com.yihu.wlyy.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
 * Created by yww on 2016/12/1.
 * 主数据库wlyy的jpa支持配置
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactory",
        transactionManagerRef="transactionManager",
        basePackages= { "com.yihu.wlyy.repository" })
public class RepositoryWlyyConfig {
    @Autowired
    private JpaProperties jpaProperties;
    @Autowired @Qualifier("wlyyDataSource")
    private DataSource dataSource;
    @Bean(name = "entityManager")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactory(builder).getObject().createEntityManager();
    }
    @Bean(name = "entityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(dataSource)
                .properties(getVendorProperties(dataSource))
                .packages("com.yihu.wlyy.entity")
                .persistenceUnit("persistenceUnit")
                .build();
    }
    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }
    @Bean(name = "transactionManager")
    @Primary
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactory(builder).getObject());
    }
}

+ 121 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/SpringSecurityConfig.java

@ -0,0 +1,121 @@
package com.yihu.wlyy.config;
import com.yihu.wlyy.filter.AccessDecisionManagerImpl;
import com.yihu.wlyy.filter.AccessDeniedHandlerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDecisionManager;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/7/21
 */
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置不拦截规则
        web.ignoring().antMatchers(
                "/static/**",
                "/error/**",
                "/out",
                "/**.jsp",
                "/common/**",
                "/login/**",
                "/yueren/**",
                "/customer/**",
                "/third/**",
                "/admin/hos/doctor/importFromExcel",
                "/admin/hos/doctor/importData",
                "/admin/team/importData",
                "/admin/hos/importData",
                "/admin/hos/doctor/toExcel",
                "/admin/device/toExcel",
                "/admin/patientDevice/toExcel",
                "/admin/healthIndex/toExcel",
                "/admin/static/prescription/toExcel",
                "/admin/static/wechat/listToExcel",
                "/admin/static/wechat/hosipitaTotalToExcel",
                "/admin/static/wechat/townTotalToExcel",
                "/admin/static/pay/signpayToExcel",
                "/admin/static/pay/prescriptionToExcel",
                "/admin/basedata/importData",
                "/admin/wlyyUserRole/importData",
                "/WEB—INF/views/**"
        );
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 设置拦截规则
        http
                .authorizeRequests()
                .accessDecisionManager(accessDecisionManager())
                .expressionHandler(webSecurityExpressionHandler())
                .antMatchers("/yueren/**").permitAll()
//                .antMatchers("/admin/main").permitAll()
//                .antMatchers("/login/**").permitAll()
//                .antMatchers("/admin/**").authenticated()
                .antMatchers("/admin/**").hasRole("USER")
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler())
                .and()
//                .headers().frameOptions().disable();//取消jfame的安全验证
//                .and()
                .headers().disable();
        // 自定义登录页面
//        http.csrf().disable().formLogin().loginPage("/login").permitAll();
        // 自定义注销
//        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login")
//                .invalidateHttpSession(true);
        // session管理
//        http.sessionManagement().sessionFixation().changeSessionId()
//                .maximumSessions(1).expiredUrl("/");
        // RemeberMe  和UserDetailsService合作 用来保存用户信息, 一段时间内可以不用在输入用户名和密码登录,暂不使用该功能
//        http.rememberMe().key("webmvc#FD637E6D9C0F1A5A67082AF56CE32485");
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    }
    /*
     * 最终访问控制器
     */
    @Bean(name = "accessDecisionManager")
    public AccessDecisionManager accessDecisionManager() {
        return new AccessDecisionManagerImpl();
    }
    /*
     * 错误信息拦截器
     */
    @Bean(name = "accessDeniedHandler")
    public AccessDeniedHandlerImpl accessDeniedHandler() {
        AccessDeniedHandlerImpl accessDeniedHandler = new AccessDeniedHandlerImpl();
//        accessDeniedHandler.setErrorPage("/error/403.jsp");
        return accessDeniedHandler;
    }
    /*
     * 表达式控制器
     */
    @Bean(name = "expressionHandler")
    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
        DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
        return webSecurityExpressionHandler;
    }
}

+ 48 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/SwaggerConfig.java

@ -0,0 +1,48 @@
package com.yihu.wlyy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan("com.yihu.wlyy.controller")
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    @Bean
    public Docket patientApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Wlyy-manager")
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(PathSelectors.any())
                .build()
                .apiInfo(patientApiInfo());
    }
    private ApiInfo patientApiInfo() {
        return new ApiInfoBuilder()
                .title("三师后台管理 RESTful APIs")
                .description("三师后台管理 Rest API, all the applications could access the Object model data via JSON")
                .termsOfServiceUrl("NO terms of service")
                .version("1.0")
                .contact(new Contact("yww@jkzl.com", "", ""))
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }
}

+ 59 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/config/WebMvcConfig.java

@ -0,0 +1,59 @@
package com.yihu.wlyy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        super.addResourceHandlers(registry);
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setOrder(1);
        return resolver;
    }
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource resolver = new ResourceBundleMessageSource();
        resolver.setBasenames("text/message");
        resolver.setDefaultEncoding("UTF-8");
        return resolver;
    }
//    //定义拦截器
//    @Bean
//    UserSessionInterceptor userSessionInterceptor() {
//        return new UserSessionInterceptor();
//    }
//
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(userSessionInterceptor())
//                .addPathPatterns("/admin/**");
//    }
}

+ 621 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/BaseController.java

@ -0,0 +1,621 @@
package com.yihu.wlyy.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.IdEntity;
import com.yihu.wlyy.controller.manager.account.ShiroDbRealm.ShiroUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
public class BaseController {
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	@Autowired
	protected HttpServletRequest request;
	/**
	 * 获取排序字段名称
	 * @return
	 */
	public String getSortName() {
		return request.getParameter("sortname");
	}
	/**
	 * 获取排序方式ASC,DESC
	 * @return
	 */
	public String getSortOrder() {
		return request.getParameter("sortorder");
	}
	/**
	 * 取出Shiro中的当前用户Id.
	 */
	public Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
	/**
	 * 取出Shiro中的当前用户标识.
	 */
	public String getCurrentUserCode() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.code;
	}
	/**
	 * 獲取髮送請求用戶的uid
	 * @return
	 */
	public String getUID() {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("uid");
		} catch (Exception e) {
			return null;
		}
	}
	public String getOpenid() {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("openid");
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 获取用户ID
	 * @return
	 */
	public long getId() {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getLong("id");
		} catch (Exception e) {
			return 0;
		}
	}
	public String getIMEI() {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("imei");
		} catch (Exception e) {
			return null;
		}
	}
	public String getToken() {
		try {
			String userAgent = request.getHeader("userAgent");
			if (StringUtils.isEmpty(userAgent)) {
				userAgent = request.getHeader("User-Agent");
			}
			JSONObject json = new JSONObject(userAgent);
			return json.getString("token");
		} catch (Exception e) {
			return null;
		}
	}
	public void error(Exception e) {
		logger.error(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	public void warn(Exception e) {
		logger.warn(getClass().getName() + ":", e.getMessage());
		e.printStackTrace();
	}
	/**
	 * 返回接口处理结果
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String error(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 接口处理成功
	 * @param msg
	 * @return
	 */
	public String success(String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", 200);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	public String write(int code, String msg) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return null;
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, String key, List<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, list);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONObject value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param total 总数
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, int total, String key, JSONArray value) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			json.put("total", total);
			json.put(key, value);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Object value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			// 是否为第一页
			map.put("isFirst", list.isFirst());
			// 是否为最后一页
			map.put("isLast", list.isLast());
			// 总条数
			map.put("total", list.getTotalElements());
			// 总页数
			map.put("totalPages", list.getTotalPages());
			map.put(key, list.getContent());
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", page.isFirst());
			// 是否为最后一页
			json.put("isLast", page.isLast());
			// 总条数
			json.put("total", page.getTotalElements());
			// 总页数
			json.put("totalPages", page.getTotalPages());
			json.put(key, array);
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @param value 结果数据
	 * @return
	 */
	public String write(int code, String msg, String key, Map<?, ?> value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @param value 结果数据
	* @return
	*/
	public String write(int code, String msg, String key, String value) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, value);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	* 返回接口处理结果
	*
	*
	* @param code 结果码,成功为200
	* @param msg 结果提示信息
	* @return
	*/
	public String write(int code, String msg, String key, IdEntity entity) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("status", code);
			map.put("msg", msg);
			map.put(key, entity);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	/**
	 * 返回接口处理结果
	 * 
	 * 
	 * @param code 结果码,成功为200
	 * @param msg 结果提示信息
	 * @return
	 */
	public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
		try {
			JSONObject json = new JSONObject();
			json.put("status", code);
			json.put("msg", msg);
			// 是否为第一页
			json.put("isFirst", isFirst);
			// 是否为最后一页
			json.put("isLast", isLast);
			// 总条数
			json.put("total", total);
			// 总页数
			json.put("totalPages", totalPages);
			json.put(key, values);
			return json.toString();
		} catch (Exception e) {
			logger.error("BaseController:", e.getMessage());
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	public String trimEnd(String param, String trimChars) {
		if (param.endsWith(trimChars)) {
			param = param.substring(0, param.length() - trimChars.length());
		}
		return param;
	}
	/**
	 * 无效用户消息返回
	 * @param e
	 * @param defaultCode
	 * @param defaultMsg
	 * @return
	 */
	public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
		try {
			// if (e instanceof UndeclaredThrowableException) {
			// UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
			// InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
			// if (iue != null) {
			// return error(iue.getCode(), iue.getMsg());
			// }
			// }
			return error(defaultCode, defaultMsg);
		} catch (Exception e2) {
			return null;
		}
	}
	/**
	 * 返回表格列表数据
	 * @param code 状态码:0成功,非0失败
	 * @param errorMsg 错误消息
	 * @param page 当前页码
	 * @param rows 分页大小
	 * @param list 查询的结果集
	 * @return
	 */
	public String write(int code, String errorMsg, int page, int rows, Page<?> list) {
		try {
			JSONObject object = new JSONObject();
			ObjectMapper mapper = new ObjectMapper();
			object.put("successFlg", code == 0);
			object.put("errorMsg", errorMsg);
			// 是否为第一页
			object.put("errorCode", code);
			// 是否为最后一页
			object.put("currPage", page);
			// 分页大小
			object.put("pageSize", rows);
			// 总条数
			object.put("totalCount", list.getTotalElements());
			// 总页数
			object.put("totalPage", list.getTotalPages());
			// 结果集
			object.put("detailModelList", list.getContent());
			 return object.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	
	public String write(int code, String errorMsg, int page, int rows, List<?> list) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("successFlg", code == 0);
			map.put("errorMsg", errorMsg);
			// 是否为第一页
			map.put("errorCode", code);
			// 是否为最后一页
			map.put("currPage", page);
			// 分页大小
			map.put("pageSize", rows);
			// 总条数
			map.put("totalCount", list.size());
			// 总页数
			map.put("totalPage", 1);
			// 结果集
			map.put("detailModelList", list);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
	
	public String error(int code, String errorMsg, int page, int rows) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			ObjectMapper mapper = new ObjectMapper();
			map.put("successFlg", code == 0);
			map.put("errorMsg", errorMsg);
			// 是否为第一页
			map.put("errorCode", code);
			// 是否为最后一页
			map.put("currPage", page);
			// 分页大小
			map.put("pageSize", rows);
			// 总条数
			map.put("totalCount", 0);
			// 总页数
			map.put("totalPage", 0);
			// 结果集
			map.put("detailModelList", null);
			return mapper.writeValueAsString(map);
		} catch (Exception e) {
			error(e);
			return error(-1, "服务器异常,请稍候再试!");
		}
	}
    //json串转集合
    public <T> Collection<T> jsonToEntities(String jsonDate, Collection<T> targets, Class<T> targetCls) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List modelList = objectMapper.readValue(jsonDate,List.class);
            Iterator ex = modelList.iterator();
            while(ex.hasNext()) {
                Object aModelList = ex.next();
                String objJsonData = objectMapper.writeValueAsString(aModelList);
                T model = objectMapper.readValue(objJsonData, targetCls);
                targets.add(model);
            }
            return targets;
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
    }
    public String write(int code, String errorMsg, int page, int rows, long total, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("successFlg", code == 0);
            map.put("errorMsg", errorMsg);
            // 是否为第一页
            map.put("errorCode", code);
            // 是否为最后一页
            map.put("currPage", page);
            // 分页大小
            map.put("pageSize", rows);
            // 总条数
            map.put("totalCount", total);
            // 总页数
            map.put("totalPage", 1);
            // 结果集
            map.put("detailModelList", list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
}

+ 85 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/common/account/LoginController.java

@ -0,0 +1,85 @@
package com.yihu.wlyy.controller.common.account;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.controller.BaseController;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.service.manager.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
/**
 * 用户登录的Controller.
 *
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login")
@SessionAttributes("current_user")
public class LoginController extends BaseController {
    @Autowired
    UserService userService;
    @RequestMapping(value = "validation")
    @ResponseBody
    public void userValidation(Model model, HttpServletRequest req, HttpServletResponse resp, String userName, String password) throws Exception {
        User curUser = userService.userValidation(userName, password);
        System.out.println("validation");
        ObjectMapper objectMapper = new ObjectMapper();
        if(curUser == null){
            System.out.println("curUser is null");
            req.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, "登入失败");
            req.getSession().setAttribute("isLogin", "false");
            resp.sendRedirect(req.getContextPath()+"/login");
        }else{
            System.out.println("curUser is success");
            model.addAttribute("current_user", curUser);
            //获取用户角色信息
            Collection<GrantedAuthority> gas = new ArrayList<>();
            //TODO 改成来源字典
            if(curUser.getType() == 1){
                curUser.setTypeName("管理员");
            }
            if (StringUtils.equals("admin", curUser.getCode())) {
                curUser.setTypeName("超级管理员");
            }
            if(curUser.getType() == 2){
                curUser.setTypeName("医生");
            }
            if (curUser.getType() == 0) {
                curUser.setTypeName("其他");
            }
            System.out.println("curUser is success :userInfo"+curUser.toString());
            req.getSession().setAttribute("userInfo",curUser);
            req.getSession().setAttribute("mobile", curUser.getMobile());
            req.getSession().setAttribute("code",curUser.getCode());
            req.getSession().setAttribute("name",curUser.getName());
            req.getSession().setAttribute("isLogin", "true");
            //生成认证token
            Authentication token = new UsernamePasswordAuthenticationToken(userName, password, gas);
            //将信息存放到SecurityContext
            SecurityContextHolder.getContext().setAuthentication(token);
            resp.sendRedirect(req.getContextPath()+"/admin/main");
        }
    }
}

+ 22 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/common/account/LogoutController.java

@ -0,0 +1,22 @@
package com.yihu.wlyy.controller.common.account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by yww on 2016/12/7.
 */
@Controller
@RequestMapping(value = "/logout")
public class LogoutController {
    @RequestMapping(value = "")
    public void login(HttpServletRequest request,HttpServletResponse response) throws Exception{
        request.getSession().removeAttribute("userInfo");
        request.getSession().removeAttribute("isLogin");
        response.sendRedirect(request.getContextPath() + "/login");
    }
}

+ 146 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/common/account/RegisterController.java

@ -0,0 +1,146 @@
package com.yihu.wlyy.controller.common.account;
import com.yihu.wlyy.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 用户注册的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController extends BaseController {
	// @Autowired
	// private DoctorService doctorService;
//	@Autowired
//	private PatientService patientService;
//	@Autowired
//	private SMSService smsService;
	// /**
	// * 医生注册
	// * @param name 医生姓名
	// * @param mobile 登录手机号
	// * @param password 登录密码
	// * @param captcha 手机验证码
	// * @return
	// */
	// @RequestMapping(value = "doctor")
	// @ResponseBody
	// public String doctor(String name, String mobile, String password, String captcha) {
	// try {
	// if (doctorService.findDoctorByMobile(mobile) != null) {
	// return error(-1, "该手机号已被注册!");
	// }
	// Doctor doctor = new Doctor();
	// doctor.setName(name);
	// doctor.setMobile(mobile);
	// doctor.setPassword(password);
	// JSONObject json = doctorService.registerDoctor(doctor, getIMEI());
	// if (json != null) {
	// // 注册成功
	// return write(200, "注册成功!", "data", json);
	// } else {
	// // 注册失败
	// return error(-1, "注册失败!");
	// }
	// } catch (Exception e) {
	// error(e);
	// return error(-1, "注册失败!");
	// }
	// }
//	/**
//	 * 患者注册
//	 * @param name 姓名
//	 * @param idcard 身份證號
//	 * @param ssc 社保卡号
//	 * @param mobile 登录手机号
//	 * @param captcha 手机验证码
//	 * @param type 1校验,2保存
//	 * @return
//	 */
//	@RequestMapping(value = "patient")
//	@ResponseBody
//	public String patient(String name, String idcard, String ssc, String mobile, String captcha, int type) {
//		try {
//			if (type != 1 && type != 2) {
//				return error(-1, "无效请求!");
//			}
//			if (StringUtils.isEmpty(name)) {
//				return error(-1, "姓名不允许为空!");
//			}
//			if (StringUtils.isEmpty(idcard)) {
//				return error(-1, "身份证号码不允许为空!");
//			}
//			if (StringUtils.isEmpty(ssc)) {
//				return error(-1, "社保卡号不允许为空!");
//			}
//			if (StringUtils.isEmpty(mobile)) {
//				return error(-1, "手机号码不允许为空!");
//			}
//			if (StringUtils.isEmpty(captcha)) {
//				return error(-1, "验证码不允许为空!");
//			}
//			if (StringUtils.isNotEmpty(getOpenid())) {
//				Patient patient = patientService.findByOpenid(getOpenid());
//				if (patient != null) {
//					return error(-1, "当前微信号已绑定身份证:" + CommonUtil.getIdcardEncode(patient.getIdcard()) + " !");
//				}
//			}
//			// 对验证码进行校验
//			int res = smsService.check(mobile, 1, captcha);
//			switch (res) {
//			case -2:
//				return error(-1, "验证码已过期!");
//			case -1:
//				return error(-1, "请输入正确的验证码!");
//			case 0:
//				return error(-1, "验证码无效!");
//			}
//			// 解密身份证号
//			idcard = RSAUtils.getInstance(patientService).decryptString(idcard);
//			idcard = URLDecoder.decode(idcard, "UTF-8");
//			idcard = StringUtils.reverse(idcard);
//			// 判断用户是否已注册
//			Patient patient = patientService.findByIdcard(idcard);
//			if (patient != null) {
//				return error(-1, "该帐号已绑定手机号" + CommonUtil.getMobileEncode(patient.getMobile()) + ",请直接使用此手机号登录");
//			}
//			patient = patientService.findBySsc(ssc);
//			if (patient != null) {
//				return error(-1, "该帐号已绑定手机号" + CommonUtil.getMobileEncode(patient.getMobile()) + ",请直接使用此手机号登录");
//			}
//			patient = patientService.findByMobile(mobile);
//			if (patient != null) {
//				return error(-1, "该手机号码已绑定其他身份证和医保卡,建议您重新输入新手机号码");
//			}
//			if (type == 2) {
//				patient = new Patient();
//				patient.setIdcard(idcard);
//				patient.setMobile(mobile);
//				patient.setName(name);
//				patient.setSsc(ssc);
//				patient.setOpenid(getOpenid());
//				JSONObject json = patientService.register(patient, getIMEI(), 1);
//				if (json != null) {
//					// 注册成功
//					return write(200, "注册成功!", "data", json);
//				} else {
//					// 注册失败
//					return error(-1, "注册失败!");
//				}
//			} else {
//				return success("验证通过!");
//			}
//		} catch (Exception e) {
//			error(e);
//			return error(-1, "注册失败!");
//		}
//	}
}

+ 32 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/AdminController.java

@ -0,0 +1,32 @@
package com.yihu.wlyy.controller.manager;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求),
 * 
 * 真正登录的POST请求由Filter完成,
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login")
public class AdminController {
	@RequestMapping(method = RequestMethod.GET)
	public String login() {
		return "login";
	}
	@RequestMapping(method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "login";
	}
}

+ 17 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/MainController.java

@ -0,0 +1,17 @@
package com.yihu.wlyy.controller.manager;
import com.yihu.wlyy.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value = "/admin")
public class MainController extends BaseController {
	@RequestMapping(value = "main", method = RequestMethod.GET)
	public String index() {
		return "main";
	}
}

+ 127 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/account/ShiroDbRealm.java

@ -0,0 +1,127 @@
package com.yihu.wlyy.controller.manager.account;
import com.google.common.base.Objects;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.service.manager.account.AdminService;
import com.yihu.wlyy.util.EncodesUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springside.modules.utils.Encodes;
import javax.annotation.PostConstruct;
import java.io.Serializable;
public class ShiroDbRealm extends AuthorizingRealm {
	protected AdminService adminService;
	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = adminService.findUserByMobile(token.getUsername());
		if (user != null) {
			byte[] salt = Encodes.decodeHex(user.getSalt());
			return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getCode(), user.getMobile(), user.getName()), user.getPassword(), ByteSource.Util.bytes(salt), getName());
		} else {
			return null;
		}
	}
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		User user = adminService.findUserByMobile(shiroUser.mobile);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRoles(user.getRoleList());
		return info;
	}
	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(EncodesUtil.HASH_ALGORITHM);
		matcher.setHashIterations(EncodesUtil.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}
	/**
	 * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public Long id;
		public String mobile;
		public String name;
		public String code;
		public ShiroUser(Long id, String code, String mobile, String name) {
			this.id = id;
			this.mobile = mobile;
			this.name = name;
			this.code = code;
		}
		public String getName() {
			return name;
		}
		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return mobile;
		}
		/**
		 * 重载hashCode,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(mobile);
		}
		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			ShiroUser other = (ShiroUser) obj;
			if (mobile == null) {
				if (other.mobile != null) {
					return false;
				}
			} else if (!mobile.equals(other.mobile)) {
				return false;
			}
			return true;
		}
	}
}

+ 220 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/manager/user/UserController.java

@ -0,0 +1,220 @@
package com.yihu.wlyy.controller.manager.user;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.controller.BaseController;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.service.manager.user.UserService;
import com.yihu.wlyy.util.Envelop;
import com.yihu.wlyy.util.MD5;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * Created by yww on 2016/12/6.
 */
@Controller
@RequestMapping(value = "admin/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private ObjectMapper objectMapper;
    @RequestMapping(value = "initial", method = RequestMethod.GET)
    public String listPageInit(){
        return "user/user_list";
    }
    @RequestMapping(value = "infoInit",method = RequestMethod.GET)
    public String infoPageInit(Long id,String mode){
        request.setAttribute("id",id);
        request.setAttribute("mode",mode);
        return "user/user_modify";
    }
    @RequestMapping(value = "userList")
    @ResponseBody
    public String searchList(
            @RequestParam(value = "code",required = false) String code,
            @RequestParam(value = "name",required = false) String name,
            @RequestParam(value = "mobile",required = false) String mobile,
            @RequestParam(value= "page",required = false) Integer page,
            @RequestParam(value = "rows",required = false) Integer pageSize){
        try{
            Page<User> userPage = userService.searchList(code, name, mobile, page, pageSize);
            return write(200,"操作成功",page,pageSize,userPage);
        }catch (Exception ex){
            error(ex);
            return error(-1,"操作失败!");
        }
    }
    @RequestMapping(value = "user")
    @ResponseBody
    public String getUser(
            @ApiParam(name = "id", defaultValue = "2")
            @RequestParam(name = "id", required = true) Long id) {
        try{
            User user = userService.retrieve(id);
            return write(200,"操作成功","data",user);
        }catch (Exception ex){
            error(ex);
            return error(-1,"操作失败!");
        }
    }
    @RequestMapping(value = "isCodeExist")
    @ResponseBody
    public String isCodeExist(String code){
        List<User> users = userService.findByField("code", code);
        if(users != null && users.size()>0){
            return "true";
        }
        return "false";
    }
    @RequestMapping(value = "isMobileExist")
    @ResponseBody
    public String isMobileExist(String mobile){
        List<User> users = userService.findByField("mobile", mobile);
        if(users != null && users.size()>0){
            return "true";
        }
        return "false";
    }
    @RequestMapping(value = "delete")
    @ResponseBody
    public String deleteUser(Long id){
        try{
            if (id == null) {
                return error(-1, "id不能为空!");
            }
            User user = userService.retrieve(id);
            if (StringUtils.equals(user.getCode(), "admin")) {
                return error(-1, "超级管理员admin不允许删除!");
            }
            userService.deleteUser(id);
            return write(200,"操作成功!");
        }catch (Exception ex){
            error(ex);
            return error(-1,"操作失败!");
        }
    }
    @RequestMapping(value = "create")
    @ResponseBody
    public String createUser(String jsonData){
        try{
            User user = objectMapper.readValue(jsonData, User.class);
            String mobile = user.getMobile();
            if(mobile == null){
                return write(-1,"手机号不能为空");
            }
            user.setCzrq(new Date());
            String password=user.getMobile().substring(5);
            String salt= UUID.randomUUID().toString().replace("-", "");
            password = MD5.GetMD5Code(password+salt);
            user.setPassword(password);
            user.setSalt(salt);
            User userNew = userService.save(user);
            return write(200,"操作成功!");
        }catch (Exception ex){
            error(ex);
            return error(-1,"操作失败!");
        }
    }
    @RequestMapping(value = "update")
    @ResponseBody
    public String updateUser(String jsonData){
        try{
            User user = objectMapper.readValue(jsonData, User.class);
            String mobile = user.getMobile();
            if(mobile == null){
                return write(-1,"手机号不能为空");
            }
            User userNew = userService.retrieve(user.getId());
            userNew.setCode(user.getCode());
            userNew.setName(user.getName());
            userNew.setType(user.getType());
            userNew.setMobile(user.getMobile());
            userNew.setOrganizationId(user.getOrganizationId());
            userNew.setRoles(user.getRoles());
            //修改手机号对应初始化密码(因暂未提供修改密码操作)-手机号后六位
            if(userNew.getMobile() != user.getMobile()){
                String password=mobile.substring(5);
                String salt= UUID.randomUUID().toString().replace("-", "");
                password = MD5.GetMD5Code(password+salt);
                userNew.setPassword(password);
                userNew.setSalt(salt);
            }
            userNew = userService.save(userNew);
            return write(200,"操作成功!");
        }catch (Exception ex){
            error(ex);
            return error(-1,"操作失败!");
        }
    }
    //初始化密码
    @RequestMapping(value = "initPwd")
    @ResponseBody
    public String initPwd(
            @RequestParam(value = "mobile",required = true)String mobile){
        try{
            boolean res = userService.initPwd(mobile);
            if(!res){
                return error(-1,"操作失败!");
            }
            return write(200,"操作成功!");
        }catch (Exception ex){
            error(ex);
            return error(-1,"操作失败!");
        }
    }
    //修改密码
    @RequestMapping(value = "changePwd")
    @ResponseBody
    public String changePwd(
            @RequestParam(value = "mobile")String mobile,
            @RequestParam(value = "oldPwd")String oldPwd,
            @RequestParam(value = "newPwd")String newPwd){
        try {
            return write(200,"操作成功");
        }catch (Exception ex){
            error(ex);
            return error(-1, "操作失败!");
        }
    }
    //根据姓名获取所有有效用户列表(用于分页下拉框)
    @RequestMapping("/searchUsers")
    @ResponseBody
    public Object searchUsers(String searchNm, int page, int rows) {
        try {
            Page<User> users = userService.searchUsers(searchNm, page, rows);
            return write(200, "操作成功", page, rows, users);
        } catch (Exception ex) {
            error(ex);
            return error(-1,"操作失败!");
        }
    }
}

+ 169 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheAuthorizationEndPoint.java

@ -0,0 +1,169 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.vo.MRedisCacheAuthorization;
import com.yihu.wlyy.entity.redis.RedisCacheAuthorization;
import com.yihu.wlyy.service.redis.cache.RedisCacheAuthorizationService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 缓存授权 接口
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "缓存授权接口", tags = {"缓存服务管理--缓存授权接口"})
public class RedisCacheAuthorizationEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisCacheAuthorizationService redisCacheAuthorizationService;
    @ApiOperation("根据ID获取缓存授权")
    @RequestMapping(value = ServiceApi.Redis.CacheAuthorization.GetById, method = RequestMethod.GET)
    public Envelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            MRedisCacheAuthorization mRedisCacheAuthorization = convertToModel(redisCacheAuthorizationService.getById(id), MRedisCacheAuthorization.class);
            envelop.setObj(mRedisCacheAuthorization);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存授权。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存授权发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取缓存授权")
    @RequestMapping(value = ServiceApi.Redis.CacheAuthorization.Search, method = RequestMethod.GET)
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空则返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "筛选条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "rows", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "rows", required = false) int rows) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            List<RedisCacheAuthorization> redisCacheAuthorization = redisCacheAuthorizationService.search(fields, filters, sorts, page, rows);
            int count = (int) redisCacheAuthorizationService.getCount(filters);
            List<MRedisCacheAuthorization> mRedisCacheAuthorization = (List<MRedisCacheAuthorization>) convertToModels(redisCacheAuthorization, new ArrayList<MRedisCacheAuthorization>(), MRedisCacheAuthorization.class, fields);
            envelop = getPageResult(mRedisCacheAuthorization, count, page, rows);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存授权列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存授权发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增缓存授权")
    @RequestMapping(value = ServiceApi.Redis.CacheAuthorization.Save, method = RequestMethod.POST)
    public Envelop add(
            @ApiParam(value = "缓存授权JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheAuthorization newEntity = objectMapper.readValue(entityJson, RedisCacheAuthorization.class);
            newEntity = redisCacheAuthorizationService.save(newEntity);
            MRedisCacheAuthorization mRedisCacheAuthorization = convertToModel(newEntity, MRedisCacheAuthorization.class);
            envelop.setObj(mRedisCacheAuthorization);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功新增缓存授权。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("新增缓存授权发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新缓存授权")
    @RequestMapping(value = ServiceApi.Redis.CacheAuthorization.Save, method = RequestMethod.PUT)
    public Envelop update(
            @ApiParam(value = "缓存授权JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheAuthorization updateEntity = objectMapper.readValue(entityJson, RedisCacheAuthorization.class);
            updateEntity = redisCacheAuthorizationService.save(updateEntity);
            MRedisCacheAuthorization mRedisCacheAuthorization = convertToModel(updateEntity, MRedisCacheAuthorization.class);
            envelop.setObj(mRedisCacheAuthorization);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功更新缓存授权。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("更新缓存授权发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除缓存授权")
    @RequestMapping(value = ServiceApi.Redis.CacheAuthorization.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "缓存授权ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            redisCacheAuthorizationService.delete(id);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功删除缓存授权。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("删除缓存授权发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证指定缓存分类下应用ID是否唯一")
    @RequestMapping(value = ServiceApi.Redis.CacheAuthorization.IsUniqueAppId, method = RequestMethod.GET)
    public Envelop isUniqueAppId(
            @ApiParam(name = "id", value = "缓存授权ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "categoryCode", value = "缓存分类编码", required = true)
            @RequestParam(value = "categoryCode") String categoryCode,
            @ApiParam(name = "appId", value = "应用ID", required = true)
            @RequestParam(value = "appId") String appId) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisCacheAuthorizationService.isUniqueAppId(id, categoryCode, appId);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("当前缓存分类下的当前应用ID已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 215 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheCategoryEndPoint.java

@ -0,0 +1,215 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.vo.MRedisCacheCategory;
import com.yihu.wlyy.entity.redis.RedisCacheCategory;
import com.yihu.wlyy.service.redis.cache.RedisCacheCategoryService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 缓存分类 接口
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "缓存分类接口", tags = {"缓存服务管理--缓存分类接口"})
public class RedisCacheCategoryEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisCacheCategoryService redisCacheCategoryService;
    @ApiOperation("根据ID获取缓存分类")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.GetById, method = RequestMethod.GET)
    public Envelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            MRedisCacheCategory mRedisCacheCategory = convertToModel(redisCacheCategoryService.getById(id), MRedisCacheCategory.class);
            envelop.setObj(mRedisCacheCategory);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存分类。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存分类发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取缓存分类")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.Search, method = RequestMethod.GET)
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空则返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "searchContent", value = "筛选条件")
            @RequestParam(value = "searchContent", required = false) String searchContent,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "rows", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "rows", required = false) int rows) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            String filters = null;
            if (!StringUtils.isEmpty(searchContent)) {
                filters = "code?" + searchContent + ";name?" + searchContent + ";";
            }
            List<RedisCacheCategory> redisCacheCategoryList = redisCacheCategoryService.search(fields, filters, sorts, page, rows);
            int count = (int) redisCacheCategoryService.getCount(filters);
            List<MRedisCacheCategory> mRedisCacheCategoryList = (List<MRedisCacheCategory>) convertToModels(redisCacheCategoryList, new ArrayList<MRedisCacheCategory>(), MRedisCacheCategory.class, fields);
            envelop = getPageResult(mRedisCacheCategoryList, count, page, rows);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存分类列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存分类发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取缓存分类(不分页)")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.SearchNoPage, method = RequestMethod.GET)
    public Envelop searchNoPage(
            @ApiParam(name = "filters", value = "筛选条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            List<RedisCacheCategory> redisCacheCategoryList = redisCacheCategoryService.search(filters, sorts);
            envelop.setDetailModelList(redisCacheCategoryList);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存分类列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存分类发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增缓存分类")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.Save, method = RequestMethod.POST)
    public Envelop add(
            @ApiParam(value = "缓存分类JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheCategory newEntity = objectMapper.readValue(entityJson, RedisCacheCategory.class);
            newEntity = redisCacheCategoryService.save(newEntity);
            MRedisCacheCategory mRedisCacheCategory = convertToModel(newEntity, MRedisCacheCategory.class);
            envelop.setObj(mRedisCacheCategory);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功新增缓存分类。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("新增缓存分类发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新缓存分类")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.Save, method = RequestMethod.PUT)
    public Envelop update(
            @ApiParam(value = "缓存分类JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheCategory updateEntity = objectMapper.readValue(entityJson, RedisCacheCategory.class);
            updateEntity = redisCacheCategoryService.save(updateEntity);
            MRedisCacheCategory mRedisCacheCategory = convertToModel(updateEntity, MRedisCacheCategory.class);
            envelop.setObj(mRedisCacheCategory);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功更新缓存分类。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("更新缓存分类发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除缓存分类")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "缓存分类ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            redisCacheCategoryService.delete(id);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功删除缓存分类。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("删除缓存分类发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证缓存分类名称是否唯一")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.IsUniqueName, method = RequestMethod.GET)
    public Envelop isUniqueName(
            @ApiParam(name = "id", value = "缓存分类ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "name", value = "缓存分类名称", required = true)
            @RequestParam(value = "name") String name) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisCacheCategoryService.isUniqueName(id, name);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该缓存分类名称已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证缓存分类编码是否唯一")
    @RequestMapping(value = ServiceApi.Redis.CacheCategory.IsUniqueCode, method = RequestMethod.GET)
    public Envelop isUniqueCode(
            @ApiParam(name = "id", value = "缓存分类ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "code", value = "缓存分类编码", required = true)
            @RequestParam(value = "code") String code) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisCacheCategoryService.isUniqueCode(id, code);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该缓存分类编码已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 189 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheKeyRuleEndPoint.java

@ -0,0 +1,189 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.vo.MRedisCacheKeyRule;
import com.yihu.wlyy.entity.redis.RedisCacheKeyRule;
import com.yihu.wlyy.service.redis.cache.RedisCacheKeyRuleService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 缓存Key规则 接口
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "缓存Key规则接口", tags = {"缓存服务管理--缓存Key规则接口"})
public class RedisCacheKeyRuleEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisCacheKeyRuleService redisCacheKeyRuleService;
    @ApiOperation("根据ID获取缓存Key规则")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.GetById, method = RequestMethod.GET)
    public Envelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            MRedisCacheKeyRule mRedisCacheKeyRule = convertToModel(redisCacheKeyRuleService.getById(id), MRedisCacheKeyRule.class);
            envelop.setObj(mRedisCacheKeyRule);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存Key规则。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存Key规则发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取缓存Key规则")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.Search, method = RequestMethod.GET)
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空则返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "筛选条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "rows", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "rows", required = false) int rows) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            List<RedisCacheKeyRule> redisCacheKeyRuleList = redisCacheKeyRuleService.search(fields, filters, sorts, page, rows);
            int count = (int) redisCacheKeyRuleService.getCount(filters);
            List<MRedisCacheKeyRule> mRedisCacheKeyRule = (List<MRedisCacheKeyRule>) convertToModels(redisCacheKeyRuleList, new ArrayList<MRedisCacheKeyRule>(), MRedisCacheKeyRule.class, fields);
            envelop = getPageResult(mRedisCacheKeyRule, count, page, rows);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取缓存Key规则列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存Key规则发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增缓存Key规则")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.Save, method = RequestMethod.POST)
    public Envelop add(
            @ApiParam(value = "缓存Key规则JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheKeyRule newEntity = objectMapper.readValue(entityJson, RedisCacheKeyRule.class);
            newEntity = redisCacheKeyRuleService.save(newEntity);
            MRedisCacheKeyRule mRedisCacheKeyRule = convertToModel(newEntity, MRedisCacheKeyRule.class);
            envelop.setObj(mRedisCacheKeyRule);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功新增缓存Key规则。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("新增缓存Key规则发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新缓存Key规则")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.Save, method = RequestMethod.PUT)
    public Envelop update(
            @ApiParam(value = "缓存Key规则JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheKeyRule updateEntity = objectMapper.readValue(entityJson, RedisCacheKeyRule.class);
            updateEntity = redisCacheKeyRuleService.save(updateEntity);
            MRedisCacheKeyRule mRedisCacheKeyRule = convertToModel(updateEntity, MRedisCacheKeyRule.class);
            envelop.setObj(mRedisCacheKeyRule);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功更新缓存Key规则。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("更新缓存Key规则发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除缓存Key规则")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "缓存Key规则ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            redisCacheKeyRuleService.delete(id);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功删除缓存Key规则。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("删除缓存Key规则发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证缓存Key规则名称是否唯一")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.IsUniqueName, method = RequestMethod.GET)
    public Envelop isUniqueName(
            @ApiParam(name = "id", value = "缓存Key规则ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "name", value = "缓存Key规则名称", required = true)
            @RequestParam(value = "name") String name) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisCacheKeyRuleService.isUniqueName(id, name);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该缓存Key规则名称已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证缓存Key规则编码是否唯一")
    @RequestMapping(value = ServiceApi.Redis.CacheKeyRule.IsUniqueCode, method = RequestMethod.GET)
    public Envelop isUniqueCode(
            @ApiParam(name = "id", value = "缓存Key规则ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "code", value = "缓存Key规则编码", required = true)
            @RequestParam(value = "code") String code) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisCacheKeyRuleService.isUniqueCode(id, code);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该缓存Key规则编码已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 151 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheOperationEndPoint.java

@ -0,0 +1,151 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.entity.redis.RedisCacheAuthorization;
import com.yihu.wlyy.entity.redis.RedisCacheKeyRule;
import com.yihu.wlyy.service.redis.CacheCommonBiz;
import com.yihu.wlyy.service.redis.cache.RedisCacheAuthorizationService;
import com.yihu.wlyy.service.redis.cache.RedisCacheKeyRuleService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
 * 缓存操作
 *
 * @author 张进军
 * @date 2017/11/23 15:09
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "缓存操作接口", tags = {"缓存服务管理--缓存操作接口"})
public class RedisCacheOperationEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisCacheKeyRuleService redisCacheKeyRuleService;
    @Autowired
    private RedisCacheAuthorizationService redisCacheAuthorizationService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @ApiOperation("根据Key规则,获取指定key的缓存值")
    @RequestMapping(value = ServiceApi.Redis.CacheOperation.Get, method = RequestMethod.GET)
    public Envelop get(
            @ApiParam(name = "keyRuleCode", value = "Key规则编码", required = true)
            @RequestParam("keyRuleCode") String keyRuleCode,
            @ApiParam(name = "ruleParams", value = "规则参数,JSON字符串")
            @RequestParam(value = "ruleParams", required = false) String ruleParams) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheKeyRule redisCacheKeyRule = redisCacheKeyRuleService.findByCode(keyRuleCode);
            if (redisCacheKeyRule == null) {
                envelop.setErrorMsg("Key规则 " + keyRuleCode + " 不存在。");
                return envelop;
            }
            String categoryCode = redisCacheKeyRule.getCategoryCode();
            String keyRuleExpression = redisCacheKeyRule.getExpression();
            // 获取缓存值
            ValueOperations<String, Object> valOps = redisTemplate.opsForValue();
            String key = CacheCommonBiz.generateKey(keyRuleExpression, ruleParams, categoryCode);
            Object value = valOps.get(key);
            envelop.setSuccessFlg(true);
            envelop.setObj(value);
            envelop.setErrorMsg("成功获取缓存。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("根据Key规则,设置指定key的缓存值")
    @RequestMapping(value = ServiceApi.Redis.CacheOperation.Set, method = RequestMethod.POST)
    public Envelop set(
            @ApiParam(name = "appId", value = "应用ID", required = true)
            @RequestParam("appId") String appId,
            @ApiParam(name = "value", value = "值", required = true)
            @RequestParam("value") String value,
            @ApiParam(name = "keyRuleCode", value = "Key规则编码", required = true)
            @RequestParam("keyRuleCode") String keyRuleCode,
            @ApiParam(name = "ruleParams", value = "规则参数,JSON字符串")
            @RequestParam(value = "ruleParams", required = false) String ruleParams) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheKeyRule redisCacheKeyRule = redisCacheKeyRuleService.findByCode(keyRuleCode);
            if (redisCacheKeyRule == null) {
                envelop.setErrorMsg("Key规则 " + keyRuleCode + " 不存在。");
                return envelop;
            }
            String categoryCode = redisCacheKeyRule.getCategoryCode();
            String keyRuleExpression = redisCacheKeyRule.getExpression();
            RedisCacheAuthorization redisCacheAuthorization = redisCacheAuthorizationService.findByCategoryCodeAndAppId(categoryCode, appId);
            // 判断应用ID是否在缓存分类上绑定
            if (redisCacheAuthorization == null) {
                envelop.setErrorMsg("该应用ID还未绑定到缓存分类 " + categoryCode + "上,请先绑定。");
                return envelop;
            }
            // 设置缓存值
            ValueOperations<String, Object> valOps = redisTemplate.opsForValue();
            String key = CacheCommonBiz.generateKey(keyRuleExpression, ruleParams, categoryCode);
            valOps.set(key, value);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功设置缓存。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("设置缓存发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("根据Key规则,移除指定key的缓存值")
    @RequestMapping(value = ServiceApi.Redis.CacheOperation.Remove, method = RequestMethod.POST)
    public Envelop remove(
            @ApiParam(name = "keyRuleCode", value = "Key规则编码", required = true)
            @RequestParam("keyRuleCode") String keyRuleCode,
            @ApiParam(name = "ruleParams", value = "规则参数,JSON字符串")
            @RequestParam(value = "ruleParams", required = false) String ruleParams) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisCacheKeyRule redisCacheKeyRule = redisCacheKeyRuleService.findByCode(keyRuleCode);
            if (redisCacheKeyRule == null) {
                envelop.setErrorMsg("Key规则 " + keyRuleCode + " 不存在。");
                return envelop;
            }
            String categoryCode = redisCacheKeyRule.getCategoryCode();
            String keyRuleExpression = redisCacheKeyRule.getExpression();
            // 移除缓存值
            String key = CacheCommonBiz.generateKey(keyRuleExpression, ruleParams, categoryCode);
            redisTemplate.delete(key);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功移除缓存。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取缓存发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 132 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisCacheStatisticsEndPoint.java

@ -0,0 +1,132 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.entity.redis.RedisCacheCategory;
import com.yihu.wlyy.service.redis.CacheCommonBiz;
import com.yihu.wlyy.service.redis.cache.RedisCacheCategoryService;
import com.yihu.wlyy.service.redis.cache.RedisCacheKeyMemoryService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 缓存统计
 *
 * @author 张进军
 * @date 2017/11/30 17:07
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "缓存统计接口", tags = {"缓存服务管理--缓存统计接口"})
public class RedisCacheStatisticsEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisCacheCategoryService redisCacheCategoryService;
    @Autowired
    private RedisCacheKeyMemoryService redisCacheKeyMemoryService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @ApiOperation("统计缓存分类的缓存数量")
    @RequestMapping(value = ServiceApi.Redis.CacheStatistics.GetCategoryKeys, method = RequestMethod.GET)
    public Envelop getCategoryKeys() {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            Map<String, Object> result = new HashMap<>();
            List<String> categoryNameList = new ArrayList<>();
            List<Integer> categoryNumList = new ArrayList<>();
            List<RedisCacheCategory> categoryList = redisCacheCategoryService.search("");
            for (RedisCacheCategory category : categoryList) {
                categoryNameList.add(category.getName());
                String keysPattern = CacheCommonBiz.makeKeyPrefix(category.getCode()) + "*";
                categoryNumList.add(redisTemplate.keys(keysPattern).size());
            }
            result.put("categoryNameList", categoryNameList);
            result.put("categoryNumList", categoryNumList);
            envelop.setObj(result);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取数据。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("统计缓存分类的缓存内存比率(近似值,比实际略小)")
    @RequestMapping(value = ServiceApi.Redis.CacheStatistics.GetCategoryMemory, method = RequestMethod.GET)
    public Envelop getCategoryMemory() {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            Map<String, Object> result = new HashMap<>();
            List<String> categoryNameList = new ArrayList<>();
            List<Map<String, Object>> categoryMemoryList = new ArrayList<>();
            // Redis使用的总内存
            long redisUsedMemory = (long) redisTemplate.execute(new RedisCallback() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    return Long.parseLong(connection.info("memory").get("used_memory").toString());
                }
            });
            List<RedisCacheCategory> categoryList = redisCacheCategoryService.search("");
            long categoryMemoryTotal = 0;
            for (RedisCacheCategory category : categoryList) {
                categoryNameList.add(category.getName());
                String keyPrefix = CacheCommonBiz.makeKeyPrefix(category.getCode());
                Long categoryMemory = redisCacheKeyMemoryService.sumCategoryMemory(keyPrefix);
                Map<String, Object> rateMap = new HashMap<>();
                rateMap.put("name", category.getName());
                rateMap.put("value", categoryMemory);
                categoryMemoryList.add(rateMap);
                categoryMemoryTotal += categoryMemory;
            }
            String noCategoryName = "未分类";
            categoryNameList.add(noCategoryName);
            Map<String, Object> noCategoryMemMap = new HashMap<>();
            Long noCategoryMemory = redisCacheKeyMemoryService.sumNotCategoryMemory();
            noCategoryMemMap.put("name", noCategoryName);
            noCategoryMemMap.put("value", noCategoryMemory);
            categoryMemoryList.add(noCategoryMemMap);
            String idleMemoryName = "闲置内存";
            categoryNameList.add(idleMemoryName);
            Map<String, Object> idleMemoryMap = new HashMap<>();
            idleMemoryMap.put("name", idleMemoryName);
            idleMemoryMap.put("value", redisUsedMemory - categoryMemoryTotal - noCategoryMemory);
            categoryMemoryList.add(idleMemoryMap);
            result.put("categoryNameList", categoryNameList);
            result.put("categoryMemoryList", categoryMemoryList);
            envelop.setObj(result);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取数据。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 35 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisIndexController.java

@ -0,0 +1,35 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * @author yeshijie on 2017/12/20.
 */
@Controller
@RequestMapping(value = "admin/redis")
public class RedisIndexController extends BaseController {
    @RequestMapping(value = "channel", method = RequestMethod.GET)
    public String channel(){
        return "redis/mq/channel/list";
    }
    @RequestMapping(value = "cacheCategory", method = RequestMethod.GET)
    public String cacheCategory(){
        return "redis/cache/category/list";
    }
    @RequestMapping(value = "cacheKey", method = RequestMethod.GET)
    public String cacheKey(){
        return "redis/cache/keyRule/list";
    }
    @RequestMapping(value = "authorization/index", method = RequestMethod.GET)
    public String authorization_index(){
        return "redis/cache/keyRule/list";
    }
}

+ 241 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisMqChannelEndPoint.java

@ -0,0 +1,241 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.vo.MRedisCacheCategory;
import com.yihu.wlyy.common.vo.MRedisMqChannel;
import com.yihu.wlyy.entity.redis.RedisMqChannel;
import com.yihu.wlyy.entity.redis.RedisMqMessageLog;
import com.yihu.wlyy.entity.redis.RedisMqSubscriber;
import com.yihu.wlyy.service.redis.CustomMessageListenerAdapter;
import com.yihu.wlyy.service.redis.MessageCommonBiz;
import com.yihu.wlyy.service.redis.pubsub.RedisMqChannelService;
import com.yihu.wlyy.service.redis.pubsub.RedisMqMessageLogService;
import com.yihu.wlyy.service.redis.pubsub.RedisMqPublisherService;
import com.yihu.wlyy.service.redis.pubsub.RedisMqSubscriberService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
 * Redis消息队列 接口
 *
 * @author 张进军
 * @date 2017/11/10 11:45
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "消息队列接口", tags = {"Redis消息发布订阅--消息队列接口"})
public class RedisMqChannelEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisMqChannelService redisMqChannelService;
    @Autowired
    private RedisMqMessageLogService redisMqMessageLogService;
    @Autowired
    private RedisMqSubscriberService redisMqSubscriberService;
    @Autowired
    private RedisMqPublisherService redisMqPublisherService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RedisMessageListenerContainer redisMessageListenerContainer;
    @ApiOperation("根据ID获取消息队列")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.GetById, method = RequestMethod.GET)
    public Envelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            MRedisMqChannel mRedisMqChannel = convertToModel(redisMqChannelService.getById(id), MRedisMqChannel.class);
            envelop.setObj(mRedisMqChannel);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取消息队列。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取消息队列发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取消息队列")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.Search, method = RequestMethod.GET)
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空则返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "筛选条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "rows", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "rows", required = false) int rows) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            List<RedisMqChannel> redisMqChannelList = redisMqChannelService.search(fields, filters, sorts, page, rows);
            int count = (int) redisMqChannelService.getCount(filters);
            List<MRedisMqChannel> mRedisMqChannelList = (List<MRedisMqChannel>) convertToModels(redisMqChannelList, new ArrayList<MRedisMqChannel>(), MRedisMqChannel.class, fields);
            envelop = getPageResult(mRedisMqChannelList, count, page, rows);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取消息队列列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取消息队列发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增消息队列")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.Save, method = RequestMethod.POST)
    public Envelop add(
            @ApiParam(value = "消息队列JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisMqChannel newEntity = objectMapper.readValue(entityJson, RedisMqChannel.class);
            newEntity = redisMqChannelService.save(newEntity);
            // 开启该订阅者的消息队列的消息监听
            String channel = newEntity.getChannel();
            CustomMessageListenerAdapter messageListener = MessageCommonBiz.newCustomMessageListenerAdapter(channel);
            redisMessageListenerContainer.addMessageListener(messageListener, new ChannelTopic(channel));
            MRedisCacheCategory mRedisCacheCategory = convertToModel(newEntity, MRedisCacheCategory.class);
            envelop.setObj(mRedisCacheCategory);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功新增消息队列。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("新增消息队列发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新消息队列")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.Save, method = RequestMethod.PUT)
    public Envelop update(
            @ApiParam(value = "消息队列JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisMqChannel updateEntity = objectMapper.readValue(entityJson, RedisMqChannel.class);
            updateEntity = redisMqChannelService.save(updateEntity);
            MRedisMqChannel mRedisMqChannel = convertToModel(updateEntity, MRedisMqChannel.class);
            envelop.setObj(mRedisMqChannel);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功更新消息队列。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("更新消息队列发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除消息队列")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "消息队列ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        RedisMqChannel redisMqChannel = redisMqChannelService.getById(id);
        String channel = redisMqChannel.getChannel();
        List<RedisMqMessageLog> messageLogList = redisMqMessageLogService.findByChannelAndStatus(channel, "0");
        if (messageLogList.size() != 0) {
            envelop.setSuccessFlg(false);
            envelop.setErrorMsg("该消息队列存在未消费消息,不能删除。");
            return envelop;
        }
        List<RedisMqSubscriber> subscriberList = redisMqSubscriberService.findByChannel(channel);
        if (subscriberList.size() != 0) {
            envelop.setSuccessFlg(false);
            envelop.setErrorMsg("该消息队列存在订阅者,不能删除。");
            return envelop;
        }
        redisMqChannelService.delete(id);
        // 删除该消息队列的消息监听
        CustomMessageListenerAdapter messageListener = MessageCommonBiz.newCustomMessageListenerAdapter(channel);
        redisMessageListenerContainer.removeMessageListener(messageListener, new ChannelTopic(channel));
        envelop.setSuccessFlg(true);
        return envelop;
    }
    @ApiOperation("验证消息队列编码是否唯一")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.IsUniqueChannel, method = RequestMethod.GET)
    public Envelop isUniqueChannel(
            @ApiParam(name = "id", value = "消息队列ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "channel", value = "消息队列编码", required = true)
            @RequestParam(value = "channel") String channel) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisMqChannelService.isUniqueChannel(id, channel);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该消息队列编码已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证消息队列名称是否唯一")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.IsUniqueChannelName, method = RequestMethod.GET)
    public Envelop isUniqueChannelName(
            @ApiParam(name = "id", value = "消息队列ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "channelName", value = "消息队列名称", required = true)
            @RequestParam(value = "channelName") String channelName) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisMqChannelService.isUniqueChannelName(id, channelName);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该消息队列名称已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("发布消息")
    @RequestMapping(value = ServiceApi.Redis.MqChannel.SendMessage, method = RequestMethod.POST)
    public Envelop sendMessage(
            @ApiParam(name = "publisherAppId", value = "发布者应用ID", required = true)
            @RequestParam(value = "publisherAppId") String publisherAppId,
            @ApiParam(name = "channel", value = "消息队列编码", required = true)
            @RequestParam(value = "channel") String channel,
            @ApiParam(name = "message", value = "消息", required = true)
            @RequestParam(value = "message") String message) {
        return redisMqChannelService.sendMessage(publisherAppId, channel, message);
    }
}

+ 169 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisMqPublisherEndPoint.java

@ -0,0 +1,169 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.vo.MRedisMqPublisher;
import com.yihu.wlyy.entity.redis.RedisMqPublisher;
import com.yihu.wlyy.service.redis.pubsub.RedisMqPublisherService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * Redis消息发布者 接口
 *
 * @author 张进军
 * @date 2017/11/20 09:35
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "消息发布者接口", tags = {"Redis消息发布订阅--消息发布者接口"})
public class RedisMqPublisherEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisMqPublisherService redisMqPublisherService;
    @ApiOperation("根据ID获取消息发布者")
    @RequestMapping(value = ServiceApi.Redis.MqPublisher.GetById, method = RequestMethod.GET)
    public Envelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            MRedisMqPublisher mRedisMqPublisher = convertToModel(redisMqPublisherService.getById(id), MRedisMqPublisher.class);
            envelop.setObj(mRedisMqPublisher);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取消息发布者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取消息发布者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取消息发布者")
    @RequestMapping(value = ServiceApi.Redis.MqPublisher.Search, method = RequestMethod.GET)
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空则返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "筛选条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "size", required = false) int size) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            List<RedisMqPublisher> list = redisMqPublisherService.search(fields, filters, sorts, page, size);
            int count = (int) redisMqPublisherService.getCount(filters);
            List<MRedisMqPublisher> mList = (List<MRedisMqPublisher>) convertToModels(list, new ArrayList<MRedisMqPublisher>(), MRedisMqPublisher.class, fields);
            envelop = getPageResult(mList, count, page, size);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取消息发布者列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取消息发布者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增消息发布者")
    @RequestMapping(value = ServiceApi.Redis.MqPublisher.Save, method = RequestMethod.POST)
    public Envelop add(
            @ApiParam(value = "消息发布者JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisMqPublisher newEntity = objectMapper.readValue(entityJson, RedisMqPublisher.class);
            newEntity = redisMqPublisherService.save(newEntity);
            MRedisMqPublisher mRedisMqPublisher = convertToModel(newEntity, MRedisMqPublisher.class);
            envelop.setObj(mRedisMqPublisher);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功新增消息发布者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("新增消息发布者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新消息发布者")
    @RequestMapping(value = ServiceApi.Redis.MqPublisher.Save, method = RequestMethod.PUT)
    public Envelop update(
            @ApiParam(value = "消息发布者JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisMqPublisher updateEntity = objectMapper.readValue(entityJson, RedisMqPublisher.class);
            updateEntity = redisMqPublisherService.save(updateEntity);
            MRedisMqPublisher mRedisMqPublisher = convertToModel(updateEntity, MRedisMqPublisher.class);
            envelop.setObj(mRedisMqPublisher);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功更新消息发布者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("更新消息发布者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除消息发布者")
    @RequestMapping(value = ServiceApi.Redis.MqPublisher.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "消息发布者ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            redisMqPublisherService.delete(id);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功删除消息发布者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("删除消息发布者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证指定队列中发布者应用ID是否唯一")
    @RequestMapping(value = ServiceApi.Redis.MqPublisher.IsUniqueAppId, method = RequestMethod.GET)
    public Envelop isUniqueAppId(
            @ApiParam(name = "id", value = "消息订阅者ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "channel", value = "消息队列编码", required = true)
            @RequestParam(value = "channel") String channel,
            @ApiParam(name = "appId", value = "发布者应用ID", required = true)
            @RequestParam(value = "appId") String appId) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisMqPublisherService.isUniqueAppId(id, channel, appId);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该指定队列的发布者应用ID已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 199 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisMqSubscriberEndPoint.java

@ -0,0 +1,199 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.vo.MRedisMqSubscriber;
import com.yihu.wlyy.entity.redis.RedisMqSubscriber;
import com.yihu.wlyy.service.redis.pubsub.RedisMqChannelService;
import com.yihu.wlyy.service.redis.pubsub.RedisMqSubscriberService;
import com.yihu.wlyy.util.Envelop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * Redis消息订阅者 接口
 *
 * @author 张进军
 * @date 2017/11/13 15:14
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "消息订阅者接口", tags = {"Redis消息发布订阅--消息订阅者接口"})
public class RedisMqSubscriberEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisMqSubscriberService redisMqSubscriberService;
    @Autowired
    private RedisMqChannelService redisMqChannelService;
    @Autowired
    private RedisMessageListenerContainer redisMessageListenerContainer;
    @ApiOperation("根据ID获取消息订阅者")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.GetById, method = RequestMethod.GET)
    public Envelop getById(
            @ApiParam(name = "id", value = "主键", required = true)
            @PathVariable(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            MRedisMqSubscriber mRedisMqSubscriber = convertToModel(redisMqSubscriberService.getById(id), MRedisMqSubscriber.class);
            envelop.setObj(mRedisMqSubscriber);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取消息订阅者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取消息订阅者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation(value = "根据条件获取消息订阅者")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.Search, method = RequestMethod.GET)
    public Envelop search(
            @ApiParam(name = "fields", value = "返回的字段,为空则返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "筛选条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "page", value = "页码", defaultValue = "1")
            @RequestParam(value = "page", required = false) int page,
            @ApiParam(name = "rows", value = "分页大小", defaultValue = "15")
            @RequestParam(value = "rows", required = false) int rows) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            List<RedisMqSubscriber> list = redisMqSubscriberService.search(fields, filters, sorts, page, rows);
            int count = (int) redisMqSubscriberService.getCount(filters);
            List<MRedisMqSubscriber> mList = (List<MRedisMqSubscriber>) convertToModels(list, new ArrayList<MRedisMqSubscriber>(), MRedisMqSubscriber.class, fields);
            envelop = getPageResult(mList, count, page, rows);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功获取消息订阅者列表。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("获取消息订阅者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("新增消息订阅者")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.Save, method = RequestMethod.POST)
    public Envelop add(
            @ApiParam(value = "消息订阅者JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisMqSubscriber newEntity = objectMapper.readValue(entityJson, RedisMqSubscriber.class);
            newEntity = redisMqSubscriberService.save(newEntity);
            MRedisMqSubscriber mRedisMqSubscriber = convertToModel(newEntity, MRedisMqSubscriber.class);
            envelop.setObj(mRedisMqSubscriber);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功新增消息订阅者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("新增消息订阅者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("更新消息订阅者")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.Save, method = RequestMethod.PUT)
    public Envelop update(
            @ApiParam(value = "消息订阅者JSON", required = true)
            @RequestBody String entityJson) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            RedisMqSubscriber updateEntity = objectMapper.readValue(entityJson, RedisMqSubscriber.class);
            updateEntity = redisMqSubscriberService.save(updateEntity);
            MRedisMqSubscriber mRedisMqSubscriber = convertToModel(updateEntity, MRedisMqSubscriber.class);
            envelop.setObj(mRedisMqSubscriber);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功更新消息订阅者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("更新消息订阅者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("删除消息订阅者")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.Delete, method = RequestMethod.DELETE)
    public Envelop delete(
            @ApiParam(name = "id", value = "消息订阅者ID", required = true)
            @RequestParam(value = "id") Integer id) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            redisMqSubscriberService.delete(id);
            envelop.setSuccessFlg(true);
            envelop.setErrorMsg("成功删除消息订阅者。");
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("删除消息订阅者发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证指定消息队列中订阅者应用ID是否唯一")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.IsUniqueAppId, method = RequestMethod.GET)
    public Envelop isUniqueAppId(
            @ApiParam(name = "id", value = "消息订阅者ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "channel", value = "消息队列编码", required = true)
            @RequestParam(value = "channel") String channel,
            @ApiParam(name = "appId", value = "消息订阅者应用ID", required = true)
            @RequestParam(value = "appId") String appId) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisMqSubscriberService.isUniqueAppId(id, channel, appId);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该指定消息队列中订阅者应用ID已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
    @ApiOperation("验证指定消息队列中订阅者服务地址是否唯一")
    @RequestMapping(value = ServiceApi.Redis.MqSubscriber.IsUniqueSubscribedUrl, method = RequestMethod.GET)
    public Envelop isUniqueSubscribedUrl(
            @ApiParam(name = "id", value = "消息订阅者ID", required = true)
            @RequestParam(value = "id") Integer id,
            @ApiParam(name = "channel", value = "消息队列编码", required = true)
            @RequestParam(value = "channel") String channel,
            @ApiParam(name = "subscriberUrl", value = "消息订阅者服务地址", required = true)
            @RequestParam(value = "subscriberUrl") String subscriberUrl) {
        Envelop envelop = new Envelop();
        envelop.setSuccessFlg(false);
        try {
            boolean result = redisMqSubscriberService.isUniqueSubscribedUrl(id, channel, subscriberUrl);
            envelop.setSuccessFlg(result);
            if (!result) {
                envelop.setErrorMsg("该指定消息队列中订阅者服务地址已被使用,请重新填写!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            envelop.setErrorMsg("发生异常:" + e.getMessage());
        }
        return envelop;
    }
}

+ 198 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisScheduledController.java

@ -0,0 +1,198 @@
package com.yihu.wlyy.controller.redis;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.util.UuidUtil;
import com.yihu.wlyy.common.vo.DefaultJSchUserInfo;
import com.yihu.wlyy.entity.redis.RedisCacheKeyMemory;
import com.yihu.wlyy.service.redis.RedisCacheKeyMemorySetMapper;
import com.yihu.wlyy.service.redis.cache.RedisCacheKeyMemoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
 * 定时任务
 *
 * @author ysj
 * @date 2017/12/20
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "定时任务", tags = {"缓存服务管理--定时任务"})
public class RedisScheduledController {
    Logger logger = LoggerFactory.getLogger(RedisScheduledController.class);
    @Value("${ehr-redis.cache.memory.rdbFilePath}")
    private String rdbFilePath;
    @Value("${ehr-redis.cache.memory.outFilePath}")
    private String outFilePath;
//    @Value("${ehr-redis.server.host}")
//    private String redisServerHost;
//    @Value("${ehr-redis.server.username}")
//    private String redisServerUsername;
//    @Value("${ehr-redis.server.password}")
//    private String redisServerPwd;
//    @Value("${ehr-redis.server.ssh-port}")
//    private int redisServerSshPort;
    private String redisServerHost = "";
    private String redisServerUsername = "";
    private String redisServerPwd = "";
    private int redisServerSshPort = 22;
    @Autowired
    private RedisCacheKeyMemoryService redisCacheKeyMemoryService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @RequestMapping(value = "/redis/cache/statistics/backupRedis", method = RequestMethod.GET)
    @ApiOperation("生成 Redis 快照")
    public void backupRedis() {
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.bgSave();
                return null;
            }
        });
        logger.info("已执行Redis快照命令。");
    }
    @RequestMapping(value = "/redis/cache/statistics/exportAndImportRedisMemoryData", method = RequestMethod.GET)
    @ApiOperation("导出 redis 内存分析报告,并导入到数据库")
    public void exportAndImportRedisMemoryData() {
        long start = System.currentTimeMillis();
        try {
            // 导出内存分析报告CSV文件(得到的内存值是近似值,比实际略小)
            // 生产环境服务器不允许代码直接通过SSH访问服务器,故暂时注释,另寻方法。
            exportRedisMemoryReport();
            long export = System.currentTimeMillis();
            logger.info("成功导出Redis内存分析报告,耗时:" + (export - start) + " 毫秒");
            // 导入CSV格式的内存分析数据
            FlatFileItemReader<RedisCacheKeyMemory> itemReader = new FlatFileItemReader<>();
            itemReader.setResource(new FileSystemResource(outFilePath));
            itemReader.setLinesToSkip(1);
            DefaultLineMapper<RedisCacheKeyMemory> lineMapper = new DefaultLineMapper<>();
            lineMapper.setLineTokenizer(new DelimitedLineTokenizer());
            lineMapper.setFieldSetMapper(new RedisCacheKeyMemorySetMapper());
            itemReader.setLineMapper(lineMapper);
            itemReader.open(new ExecutionContext());
            long deleteBe = System.currentTimeMillis();
            redisCacheKeyMemoryService.deleteAllInBatch();
            logger.info("清空旧的内存分析表数据,耗时:" + (System.currentTimeMillis() - deleteBe) + " 毫秒");
            List<RedisCacheKeyMemory> redisCacheKeyMemoryList = new ArrayList<>();
            RedisCacheKeyMemory redisCacheKeyMemory = null;
            int i = 0;
            while ((redisCacheKeyMemory = itemReader.read()) != null) {
                redisCacheKeyMemory.setId(UuidUtil.randomUUID());
                redisCacheKeyMemoryList.add(redisCacheKeyMemory);
                if (redisCacheKeyMemoryList.size() == 1000) {
                    redisCacheKeyMemoryService.save(redisCacheKeyMemoryList);
                    redisCacheKeyMemoryList.clear();
                    i += 1000;
                    logger.info("已导入 " + i + " 条数据。");
                }
            }
            redisCacheKeyMemoryService.save(redisCacheKeyMemoryList);
            logger.info("总共导入 " + (i + redisCacheKeyMemoryList.size()) + " 条数据。");
            logger.info("成功导入Redis内存分析数据到数据库,耗时:" + (System.currentTimeMillis() - export) + " 毫秒");
            logger.info("导出Redis内存分析报告,并导入到数据库,总耗时:" + (System.currentTimeMillis() - start) + " 毫秒");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发生异常:" + e.getMessage());
        }
    }
    /**
     * 导出 Redis 的内存分析报告为CSV文件
     */
    private void exportRedisMemoryReport() throws Exception {
        long start = System.currentTimeMillis();
        FileOutputStream fileOut = null;
        BufferedOutputStream bufOut = null;
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(redisServerUsername, redisServerHost);
            session.setPassword(redisServerPwd);
            session.setPort(redisServerSshPort);
            session.setUserInfo(new DefaultJSchUserInfo());
            session.connect();
            long conEnd = System.currentTimeMillis();
            logger.info("JSch 连接耗时:" + (conEnd - start) + " 毫秒");
            String command = "rdb -c memory " + rdbFilePath;
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            channel.setInputStream(null);
            channel.setErrStream(System.err);
            InputStream in = channel.getInputStream();
            channel.connect();
            File outFile = new File(outFilePath);
            if (!outFile.exists()){
                outFile.createNewFile();
            }
            fileOut = new FileOutputStream(outFile);
            bufOut = new BufferedOutputStream(fileOut);
            byte[] tmp = new byte[1024];
            int count = 0;
            while ((count = in.read(tmp, 0, 1024)) != -1) {
                bufOut.write(tmp, 0, count);
            }
            bufOut.flush();
            logger.info("生成Redis内存分析报告文件,耗时:" + (System.currentTimeMillis() - conEnd) + " 毫秒");
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            logger.error("生成Redis内存分析报告发生异常:" + e.getMessage());
            throw new Exception();
        } finally {
            try {
                if (bufOut != null) {
                    bufOut.close();
                }
                if (fileOut != null) {
                    fileOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

+ 67 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/controller/redis/RedisSubscribeMessageEndPoint.java

@ -0,0 +1,67 @@
package com.yihu.wlyy.controller.redis;
import com.yihu.wlyy.common.constants.ApiVersion;
import com.yihu.wlyy.common.constants.ServiceApi;
import com.yihu.wlyy.common.controller.EnvelopRestEndPoint;
import com.yihu.wlyy.common.util.UuidUtil;
import com.yihu.wlyy.entity.redis.RedisCacheKeyRule;
import com.yihu.wlyy.entity.redis.RedisCacheResponseTimeLog;
import com.yihu.wlyy.service.redis.CacheCommonBiz;
import com.yihu.wlyy.service.redis.cache.RedisCacheKeyRuleService;
import com.yihu.wlyy.service.redis.cache.RedisCacheResponseTimeLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
 * @author 张进军
 * @date 2017/12/4 15:19
 */
@RestController
@RequestMapping(value = ApiVersion.Version1_0)
@Api(description = "接收消息队列的消息订阅接口", tags = {"缓存服务管理--接收消息队列的消息订阅接口"})
public class RedisSubscribeMessageEndPoint extends EnvelopRestEndPoint {
    @Autowired
    private RedisCacheResponseTimeLogService responseTimeLogService;
    @Autowired
    private RedisCacheKeyRuleService keyRuleService;
    @ApiOperation("记录缓存获取接口的响应时间")
    @RequestMapping(value = ServiceApi.Redis.SubscribeMessage.ReceiveResponseTime, method = RequestMethod.POST)
    public void receiveResponseTime(
            @ApiParam(value = "消息", required = true)
            @RequestBody String message) {
        try {
            Map<String, Object> messageMap = objectMapper.readValue(message, Map.class);
            String keyRuleCode = messageMap.get("keyRuleCode").toString();
            String ruleParams = messageMap.get("ruleParams") == null ? "" : messageMap.get("ruleParams").toString();
            int responseTime = (Integer) messageMap.get("responseTime");
            RedisCacheKeyRule redisCacheKeyRule = keyRuleService.findByCode(keyRuleCode);
            if (redisCacheKeyRule != null) {
                String categoryCode = redisCacheKeyRule.getCategoryCode();
                String keyRuleExpression = redisCacheKeyRule.getExpression();
                String key = CacheCommonBiz.generateKey(keyRuleExpression, ruleParams, categoryCode);
                RedisCacheResponseTimeLog responseTimeLog = new RedisCacheResponseTimeLog();
                responseTimeLog.setId(UuidUtil.randomUUID());
                responseTimeLog.setCacheKey(key);
                responseTimeLog.setCategoryCode(categoryCode);
                responseTimeLog.setResponseTime(responseTime);
                responseTimeLogService.save(responseTimeLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 54 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/DictEntryKey.java

@ -0,0 +1,54 @@
package com.yihu.wlyy.entity;
import java.io.Serializable;
import java.util.Objects;
/**
 * 字典项主键(联合主键)。
 */
public class DictEntryKey implements Serializable {
    String code;
    long dictId;
    public DictEntryKey() {
    }
    public DictEntryKey(String code, Long dictId) {
        this.code = code == null ? "" : code;
        this.dictId = dictId == null ? null : dictId;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public long getDictId() {
        return dictId;
    }
    public void setDictId(long dictId) {
        this.dictId = dictId;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof DictEntryKey) {
            DictEntryKey pk = (DictEntryKey) obj;
            if (this.code == pk.getCode() && this.dictId == (pk.getDictId())) {
                return true;
            }
        }
        return false;
    }
    @Override
    public int hashCode() {
        return Objects.hash(code, dictId);
    }
}

+ 44 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/IdEntity.java

@ -0,0 +1,44 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.entity;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
 * 统一定义id的entity基类.
 * 
 * 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
 * Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
 * 
 * @author calvin
 */
// JPA 基类的标识
@MappedSuperclass
public abstract class IdEntity implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3673803562328635206L;
	
	// 非业务主键
	protected Long id;
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	
}

+ 133 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/SocialSecurityInfo.java

@ -0,0 +1,133 @@
package com.yihu.wlyy.entity;
import javax.persistence.*;
/**
 * 社保信息
 *
 * @author lyr
 */
@Entity
@Table(name = "sb_info")
public class SocialSecurityInfo {
    private String id;
    private String xming0;
    private String xbie00;
    private String csrqi0;
    private String zjlxbh;
    private String sfzh18;
    private String grsfen;
    private String id0000;
    private String gzztai;
    private String cardno;
    private String card16;
    private String zhgxsj;
    private String bjlxbh;
    @Id
    @GeneratedValue
    @Column(name = "id",unique = true, nullable = false)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Column(name = "XMING0",nullable = false)
    public String getXming0() {
        return xming0;
    }
    public void setXming0(String xming0) {
        this.xming0 = xming0;
    }
    @Column(name = "XBIE00",nullable = false)
    public String getXbie00() {
        return xbie00;
    }
    public void setXbie00(String xbie00) {
        this.xbie00 = xbie00;
    }
    @Column(name = "CSRQI0",nullable = false)
    public String getCsrqi0() {
        return csrqi0;
    }
    public void setCsrqi0(String csrqi0) {
        this.csrqi0 = csrqi0;
    }
    @Column(name = "ZJLXBH")
    public String getZjlxbh() {
        return zjlxbh;
    }
    public void setZjlxbh(String zjlxbh) {
        this.zjlxbh = zjlxbh;
    }
    @Column(name = "SFZH18")
    public String getSfzh18() {
        return sfzh18;
    }
    public void setSfzh18(String sfzh18) {
        this.sfzh18 = sfzh18;
    }
    @Column(name = "GRSFEN",nullable = false)
    public String getGrsfen() {
        return grsfen;
    }
    public void setGrsfen(String grsfen) {
        this.grsfen = grsfen;
    }
    @Column(name = "ID0000")
    public String getId0000() {
        return id0000;
    }
    public void setId0000(String id0000) {
        this.id0000 = id0000;
    }
    @Column(name = "GZZTAI",nullable = false)
    public String getGzztai() {
        return gzztai;
    }
    public void setGzztai(String gzztai) {
        this.gzztai = gzztai;
    }
    @Column(name = "CARDNO")
    public String getCardno() {
        return cardno;
    }
    public void setCardno(String cardno) {
        this.cardno = cardno;
    }
    @Column(name = "CARD16",nullable = false)
    public String getCard16() {
        return card16;
    }
    public void setCard16(String card16) {
        this.card16 = card16;
    }
    @Column(name = "ZHGXSJ")
    public String getZhgxsj() {
        return zhgxsj;
    }
    public void setZhgxsj(String zhgxsj) {
        this.zhgxsj = zhgxsj;
    }
    @Column(name = "BJLXBH")
    public String getBjlxbh() {
        return bjlxbh;
    }
    public void setBjlxbh(String bjlxbh) {
        this.bjlxbh = bjlxbh;
    }
}

+ 106 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/SystemDict.java

@ -0,0 +1,106 @@
package com.yihu.wlyy.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
 * SystemDict entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "system_dict")
public class SystemDict  implements java.io.Serializable {
	// Fields
	private String dictName;
	private String code;
	private String value;
	private String pyCode;
	private Integer sort;
	private String id;
	// Constructors
	/** default constructor */
	public SystemDict() {
	}
	/** minimal constructor */
	public SystemDict(String dictName, String code, String value) {
		this.dictName = dictName;
		this.code = code;
		this.value = value;
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	/** full constructor */
	public SystemDict(String dictName, String code, String value,
			String pyCode, Integer sort) {
		this.dictName = dictName;
		this.code = code;
		this.value = value;
		this.pyCode = pyCode;
		this.sort = sort;
	}
	@Column(name = "dict_name", nullable = false, length = 50)
	public String getDictName() {
		return this.dictName;
	}
	public void setDictName(String dictName) {
		this.dictName = dictName;
	}
	@Column(name = "code", nullable = false, length = 50)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "value", nullable = false, length = 50)
	public String getValue() {
		return this.value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	@Column(name = "py_code", length = 50)
	public String getPyCode() {
		return this.pyCode;
	}
	public void setPyCode(String pyCode) {
		this.pyCode = pyCode;
	}
	@Column(name = "sort")
	public Integer getSort() {
		return this.sort;
	}
	public void setSort(Integer sort) {
		this.sort = sort;
	}
}

+ 152 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/SystemDictList.java

@ -0,0 +1,152 @@
package com.yihu.wlyy.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
/**
 * SystemDictList entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "system_dict_list")
public class SystemDictList   implements java.io.Serializable {
	// Fields
	private String dictName;
	private String chineseName;
	private String pyCode;
	private String pid;
	private String remark;
	private String relationTable;
	private String relationColCode;
	private String relationColValue;
	private String relationColExtend;
	private String id;
	// Constructors
	/** default constructor */
	public SystemDictList() {
	}
	/** minimal constructor */
	public SystemDictList(String dictName, String chineseName, String pid) {
		this.dictName = dictName;
		this.chineseName = chineseName;
		this.pid = pid;
	}
	/** full constructor */
	public SystemDictList(String dictName, String chineseName, String pyCode,
			String pid, String remark, String relationTable,
			String relationColCode, String relationColValue,
			String relationColExtend) {
		this.dictName = dictName;
		this.chineseName = chineseName;
		this.pyCode = pyCode;
		this.pid = pid;
		this.remark = remark;
		this.relationTable = relationTable;
		this.relationColCode = relationColCode;
		this.relationColValue = relationColValue;
		this.relationColExtend = relationColExtend;
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "dict_name", nullable = false, length = 50)
	public String getDictName() {
		return this.dictName;
	}
	public void setDictName(String dictName) {
		this.dictName = dictName;
	}
	@Column(name = "chinese_name", nullable = false, length = 50)
	public String getChineseName() {
		return this.chineseName;
	}
	public void setChineseName(String chineseName) {
		this.chineseName = chineseName;
	}
	@Column(name = "py_code", length = 50)
	public String getPyCode() {
		return this.pyCode;
	}
	public void setPyCode(String pyCode) {
		this.pyCode = pyCode;
	}
	@Column(name = "pid", nullable = false, length = 50)
	public String getPid() {
		return this.pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}
	@Column(name = "remark", length = 200)
	public String getRemark() {
		return this.remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	@Column(name = "relation_table", length = 50)
	public String getRelationTable() {
		return this.relationTable;
	}
	public void setRelationTable(String relationTable) {
		this.relationTable = relationTable;
	}
	@Column(name = "relation_col_code", length = 50)
	public String getRelationColCode() {
		return this.relationColCode;
	}
	public void setRelationColCode(String relationColCode) {
		this.relationColCode = relationColCode;
	}
	@Column(name = "relation_col_value", length = 50)
	public String getRelationColValue() {
		return this.relationColValue;
	}
	public void setRelationColValue(String relationColValue) {
		this.relationColValue = relationColValue;
	}
	@Column(name = "relation_col_extend", length = 50)
	public String getRelationColExtend() {
		return this.relationColExtend;
	}
	public void setRelationColExtend(String relationColExtend) {
		this.relationColExtend = relationColExtend;
	}
}

+ 456 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/User.java

@ -0,0 +1,456 @@
package com.yihu.wlyy.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.ImmutableList;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.List;
/**
 * 用户表
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_user")
public class User extends IdEntity {
    private static final long serialVersionUID = 5397123441067268436L;
	// 用户标识
	private String code;
    // 姓名
    private String name;
    // 手机号
    private String mobile;
    // 登录密码
    private String password;
    // 密码加密密钥
    private String salt;
    // 用户类型:1超级管理员,2医生   3客服管理员   4普通客服
    private int type;
    //用户类型名称
    private String typeName;
    //用户拥有的权限标识,以逗号分隔
    private String roles;
    // 用户找拥有的权限以逗号分隔
    private String roleName;
	// 添加日期
	private Date czrq;
	// 所属机构
	private long organizationId;
    // 所属机构名称
    private String organizationName;
    //客服工号
    private String jobNo;
    //客服坐席号
    private String seat;
    //客服电话
    private String phone;
    //是否在线 0不在线   1离开  2在线
    private String online;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSalt() {
        return salt;
    }
    public void setSalt(String salt) {
        this.salt = salt;
    }
    public int getType() {
        return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    @Transient
    public String getTypeName() {
        return typeName;
    }
    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
    public String getRoles() {
        return roles;
    }
    public void setRoles(String roles) {
        this.roles = roles;
    }
    @Transient
    @JsonIgnore
    public String getRoleName() {
        return roleName;
    }
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "organization_id")
    public long getOrganizationId() {
        return organizationId;
    }
    public void setOrganizationId(long organizationId) {
        this.organizationId = organizationId;
    }
    @Transient
    public String getOrganizationName() {
        return organizationName;
    }
    public void setOrganizationName(String organizationName) {
        this.organizationName = organizationName;
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    @Transient
    @JsonIgnore
    public List<String> getRoleList() {
        // 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
        return ImmutableList.copyOf(StringUtils.split("", ","));
    }
    public String getJobNo() {
        return jobNo;
    }
    public void setJobNo(String jobNo) {
        this.jobNo = jobNo;
    }
    public String getSeat() {
        return seat;
    }
    public void setSeat(String seat) {
        this.seat = seat;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getOnline() {
        return online;
    }
    public void setOnline(String online) {
        this.online = online;
    }
    /**
	 * 
	 */
//	private static final long serialVersionUID = 5397123441067268436L;
//
//	// 用户标识
//	private String code;
//	// 添加日期
//	private Date czrq;
//	//科室code
//	private String hospitalDept;
//	//是否签约 1是 0否
//	private String isSign;
//	//职务code
//	private String mbjob;
//	// 手机号
//	private String mobile;
//	// 姓名
//	private String name;
//	//部门code
//	private String organizationDept;
//	// 所属机构
//	private long organizationId;
//	// 登录密码
//	private String password;
//	//简介
//	private String  remark;
//	// 密码加密密钥
//	private String salt;
//	//性别
//	private String  sex;
//	//专场
//	private String speciality;
//	// 用户类型:1超级管理员,2医生
//	private int type;
//
//	// 用户找拥有的权限以逗号分隔
//	private String roles;
//	// 用户找拥有的权限以逗号分隔
//	private String roleName;
//	private String photo;
//	//职务code
//	private String mbjobName;;
//	//科室code
//	private String hospitalDeptName;
//
//	private String organizationDeptName;
//
//	public String getCode() {
//		return code;
//	}
//
//	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
//	public Date getCzrq() {
//		return czrq;
//	}
//
//	@Column(name = "hospital_dept")
//	public String getHospitalDept() {
//		return hospitalDept;
//	}
//
//	@Column(name = "is_sign")
//	public String getIsSign() {
//		return isSign;
//	}
//
//	@Column(name = "mbjob")
//	public String getMbjob() {
//		return mbjob;
//	}
//
//	public String getMobile() {
//		return mobile;
//	}
//
//	public String getName() {
//		return name;
//	}
//
//	@Column(name = "organization_dept")
//	public String getOrganizationDept() {
//		return organizationDept;
//	}
//
//	@Column(name = "organization_id")
//	public long getOrganizationId() {
//		return organizationId;
//	}
//
//	public String getPassword() {
//		return password;
//	}
//
//	@Column(name = "remark")
//	public String getRemark() {
//		return remark;
//	}
//
//	@Transient
//	@JsonIgnore
//	public List<String> getRoleList() {
//		// 角色列表在数据库中实际以逗号分隔字符串存储,因此返回不能修改的List.
//		return ImmutableList.copyOf(StringUtils.split("", ","));
//	}
//
//	public String getRoles() {
//		return roles;
//	}
//
//	public String getSalt() {
//		return salt;
//	}
//
//	public String getSex() {
//		return sex;
//	}
//
//
//
//	public String getPhoto() {
//		return photo;
//	}
//
//	public void setPhoto(String photo) {
//		this.photo = photo;
//	}
//
//	@Column(name = "speciality")
//	public String getSpeciality() {
//		return speciality;
//	}
//
//	public int getType() {
//		return type;
//	}
//
//	public void setCode(String code) {
//		this.code = code;
//	}
//
//	public void setCzrq(Date czrq) {
//		this.czrq = czrq;
//	}
//
//	public void setHospitalDept(String hospitalDept) {
//		this.hospitalDept = hospitalDept;
//	}
//
//	public void setIsSign(String isSign) {
//		this.isSign = isSign;
//	}
//
//	public void setMbjob(String mbjob) {
//		this.mbjob = mbjob;
//	}
//
//	public void setMobile(String mobile) {
//		this.mobile = mobile;
//	}
//
//	public void setName(String name) {
//		this.name = name;
//	}
//
//	public void setOrganizationDept(String organizationDept) {
//		this.organizationDept = organizationDept;
//	}
//
//	public void setOrganizationId(long organizationId) {
//		this.organizationId = organizationId;
//	}
//
//	public void setPassword(String password) {
//		this.password = password;
//	}
//
//	public void setRemark(String remark) {
//		this.remark = remark;
//	}
//
//	public void setRoles(String roles) {
//		this.roles = roles;
//	}
//
//	public void setSalt(String salt) {
//		this.salt = salt;
//	}
//
//	public void setSex(String sex) {
//		this.sex = sex;
//	}
//
//	public void setSpeciality(String speciality) {
//		this.speciality = speciality;
//	}
//
//	public void setType(int type) {
//		this.type = type;
//	}
//
//	@Override
//	public String toString() {
//		return ToStringBuilder.reflectionToString(this);
//	}
//
//	@Transient
//	public String getRoleName() {
//		return roleName;
//	}
//
//	public void setRoleName(String roleName) {
//		this.roleName = roleName;
//	}
//
//	@Transient
//	public String getMbjobName() {
//		return mbjobName;
//	}
//
//	public void setMbjobName(String mbjobName) {
//		this.mbjobName = mbjobName;
//	}
//
//	@Transient
//	public String getHospitalDeptName() {
//		return hospitalDeptName;
//	}
//
//	public void setHospitalDeptName(String hospitalDeptName) {
//		this.hospitalDeptName = hospitalDeptName;
//	}
//
//	@Transient
//	public String getOrganizationDeptName() {
//		return organizationDeptName;
//	}
//
//	public void setOrganizationDeptName(String organizationDeptName) {
//		this.organizationDeptName = organizationDeptName;
//	}
	
}

+ 56 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/BaseAssignedEntity.java

@ -0,0 +1,56 @@
package com.yihu.wlyy.entity.redis;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
/**
 * Entity - 基类(非自动递增)
 * Created by progr1mmer on 2017/11/17.
 */
@MappedSuperclass
public abstract class BaseAssignedEntity implements Serializable {
    private static final long serialVersionUID = -67186388306700736L;
    /** ID */
    private String id;
    @Id
    @GeneratedValue(generator = "Generator")
    @GenericGenerator(name = "Generator", strategy = "assigned")
    @Column(name = "id", unique = true, nullable = false)
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!BaseAssignedEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        BaseAssignedEntity other = (BaseAssignedEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 130 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheAuthorization.java

@ -0,0 +1,130 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 缓存授权 entity
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
@Entity
@Table(name = "redis_cache_authorization")
public class RedisCacheAuthorization extends IdEntity {
    private String categoryCode; // 缓存分类编码
    private String appId; // 应用ID
    private String authorizedCode; // 授权码
    private String remark; // 备注
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "category_code", nullable = false)
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    @Column(name = "app_id", nullable = false)
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    @Column(name = "authorized_code", nullable = false)
    public String getAuthorizedCode() {
        return authorizedCode;
    }
    public void setAuthorizedCode(String authorizedCode) {
        this.authorizedCode = authorizedCode;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!IdEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        IdEntity other = (IdEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 120 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheCategory.java

@ -0,0 +1,120 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 缓存分类 entity
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
@Entity
@Table(name = "redis_cache_category")
public class RedisCacheCategory extends IdEntity {
    private String name; // 缓存分类名称
    private String code; // 缓存分类编码
    private String remark; // 备注
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "name", nullable = false, unique = true)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "code", nullable = false, unique = true)
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!IdEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        IdEntity other = (IdEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 137 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheKeyMemory.java

@ -0,0 +1,137 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 缓存Key值占用内存分析 entity
 *
 * @author 张进军
 * @date 2017/12/6 14:58
 */
@Entity
@Table(name = "redis_cache_key_memory")
public class RedisCacheKeyMemory extends BaseAssignedEntity {
    private int databaseNo; // Redis数据库编号
    private String type; // 数据类型
    private String cacheKey; // Redis Key编码
    private long sizeInBytes; // Key值内存字节大小
    private String encoding; // RDB编码类型
    private int numElements;
    private int lenLargestElement;
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "database_no", nullable = false)
    public int getDatabaseNo() {
        return databaseNo;
    }
    public void setDatabaseNo(int databaseNo) {
        this.databaseNo = databaseNo;
    }
    @Column(name = "type", nullable = false)
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    @Column(name = "cache_key", nullable = false)
    public String getCacheKey() {
        return cacheKey;
    }
    public void setCacheKey(String cacheKey) {
        this.cacheKey = cacheKey;
    }
    @Column(name = "size_in_bytes", nullable = false)
    public long getSizeInBytes() {
        return sizeInBytes;
    }
    public void setSizeInBytes(long sizeInBytes) {
        this.sizeInBytes = sizeInBytes;
    }
    @Column(name = "encoding", nullable = false)
    public String getEncoding() {
        return encoding;
    }
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }
    @Column(name = "num_elements", nullable = false)
    public int getNumElements() {
        return numElements;
    }
    public void setNumElements(int numElements) {
        this.numElements = numElements;
    }
    @Column(name = "len_largest_element", nullable = false)
    public int getLenLargestElement() {
        return lenLargestElement;
    }
    public void setLenLargestElement(int lenLargestElement) {
        this.lenLargestElement = lenLargestElement;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 163 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheKeyRule.java

@ -0,0 +1,163 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import org.hibernate.annotations.Formula;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 缓存Key生成规则 entity
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
@Entity
@Table(name = "redis_cache_key_rule")
public class RedisCacheKeyRule extends IdEntity {
    private String name; // 规则名称
    private String code; // 规则编码
    private String categoryCode; // 缓存分类编码
    private String expression; // 规则表达式
    private String expireTime; // 过期时间,单位秒
    private String remark; // 备注
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    // 临时字段
    private String categoryName; // 缓存分类名称
    @Column(name = "name", nullable = false)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "code", nullable = false)
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "category_code", nullable = false)
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    @Column(name = "expression", nullable = false)
    public String getExpression() {
        return expression;
    }
    public void setExpression(String expression) {
        this.expression = expression;
    }
    @Column(name = "expire_time")
    public String getExpireTime() {
        return expireTime;
    }
    public void setExpireTime(String expireTime) {
        this.expireTime = expireTime;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Formula("( SELECT c.name FROM redis_cache_category c WHERE c.code = category_code )")
    public String getCategoryName() {
        return categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!IdEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        IdEntity other = (IdEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 99 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisCacheResponseTimeLog.java

@ -0,0 +1,99 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 缓存获取的响应时间日志 entity
 *
 * @author 张进军
 * @date 2017/12/4 08:56
 */
@Entity
@Table(name = "redis_cache_response_time_log")
public class RedisCacheResponseTimeLog extends BaseAssignedEntity {
    private String cacheKey; // 缓存Key
    private String categoryCode; // 缓存分类编码
    private long responseTime; // 响应时长,单位毫秒
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "cache_key", nullable = false)
    public String getCacheKey() {
        return cacheKey;
    }
    public void setCacheKey(String cacheKey) {
        this.cacheKey = cacheKey;
    }
    @Column(name = "category_code", nullable = false)
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    @Column(name = "response_time", nullable = false)
    public long getResponseTime() {
        return responseTime;
    }
    public void setResponseTime(long responseTime) {
        this.responseTime = responseTime;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 174 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqChannel.java

@ -0,0 +1,174 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import org.hibernate.annotations.Formula;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * redis消息队列 Entity
 *
 * @author 张进军
 * @date 2017/11/10 11:14
 */
@Entity
@Table(name = "redis_mq_channel")
public class RedisMqChannel extends IdEntity {
    public String channel; // 消息队列编码
    public String channelName; // 消息队列名称
    public String messageTemplate; // 消息模版
    public String remark; // 备注
    // 临时属性
    public String enqueuedNum; // 入列数
    public String dequeuedNum; // 出列数
    public String subscriberNum; // 订阅者数
    public String publisherNum; // 发布者数
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "channel")
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    @Column(name = "channel_name")
    public String getChannelName() {
        return channelName;
    }
    public void setChannelName(String channelName) {
        this.channelName = channelName;
    }
    @Column(name = "message_template")
    public String getMessageTemplate() {
        return messageTemplate;
    }
    public void setMessageTemplate(String messageTemplate) {
        this.messageTemplate = messageTemplate;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @Formula("( SELECT COUNT(1) FROM redis_mq_message_log ml WHERE ml.status = 0 AND ml.channel = channel )")
    public String getEnqueuedNum() {
        return enqueuedNum;
    }
    public void setEnqueuedNum(String enqueuedNum) {
        this.enqueuedNum = enqueuedNum;
    }
    @Formula("( SELECT COUNT(1) FROM redis_mq_message_log ml WHERE ml.status = 1 AND ml.channel = channel )")
    public String getDequeuedNum() {
        return dequeuedNum;
    }
    public void setDequeuedNum(String dequeuedNum) {
        this.dequeuedNum = dequeuedNum;
    }
    @Formula("( SELECT COUNT(1) FROM redis_mq_subscriber s WHERE s.channel = channel )")
    public String getSubscriberNum() {
        return subscriberNum;
    }
    public void setSubscriberNum(String subscriberNum) {
        this.subscriberNum = subscriberNum;
    }
    @Formula("( SELECT COUNT(1) FROM redis_mq_publisher mp WHERE mp.channel = channel )")
    public String getPublisherNum() {
        return publisherNum;
    }
    public void setPublisherNum(String publisherNum) {
        this.publisherNum = publisherNum;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!IdEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        IdEntity other = (IdEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 130 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqMessageLog.java

@ -0,0 +1,130 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * redis消息记录 Entity
 *
 * @author 张进军
 * @date 2017/11/10 11:14
 */
@Entity
@Table(name = "redis_mq_message_log")
public class RedisMqMessageLog extends BaseAssignedEntity {
    public String message; // 消息
    public String channel; // 消息队列编码
    public String publisherAppId; // 发布者应用ID
    public String status; // 消息状态,0:未消费,1:已消费
    public String isRealConsumed; // 是否真实被订阅消费,0:否,1:是
    public Integer consumedNum; // 真实消费的次数
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "message")
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    @Column(name = "channel")
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    @Column(name = "publisher_app_id")
    public String getPublisherAppId() {
        return publisherAppId;
    }
    public void setPublisherAppId(String publisherAppId) {
        this.publisherAppId = publisherAppId;
    }
    @Column(name = "status")
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    @Column(name = "is_real_consumed")
    public String getIsRealConsumed() {
        return isRealConsumed;
    }
    public void setIsRealConsumed(String isRealConsumed) {
        this.isRealConsumed = isRealConsumed;
    }
    @Column(name = "consumed_num")
    public Integer getConsumedNum() {
        return consumedNum;
    }
    public void setConsumedNum(Integer consumedNum) {
        this.consumedNum = consumedNum;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
}

+ 131 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqPublisher.java

@ -0,0 +1,131 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * redis消息发布者 Entity
 *
 * @author 张进军
 * @date 2017/11/20 09:35
 */
@Entity
@Table(name = "redis_mq_publisher")
public class RedisMqPublisher extends IdEntity {
    public String appId; // 应用ID
    public String authorizedCode; // 授权码
    public String channel; // 消息队列编码
    public String remark; // 备注
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "app_id")
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    @Column(name = "authorized_code")
    public String getAuthorizedCode() {
        return authorizedCode;
    }
    public void setAuthorizedCode(String authorizedCode) {
        this.authorizedCode = authorizedCode;
    }
    @Column(name = "channel")
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!IdEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        IdEntity other = (IdEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 131 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/redis/RedisMqSubscriber.java

@ -0,0 +1,131 @@
package com.yihu.wlyy.entity.redis;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * redis消息订阅者 Entity
 *
 * @author 张进军
 * @date 2017/11/10 11:14
 */
@Entity
@Table(name = "redis_mq_subscriber")
public class RedisMqSubscriber extends IdEntity {
    public String appId; // 应用ID
    public String subscribedUrl; // 订阅者服务地址
    public String channel; // 消息队列编码
    public String remark; // 备注
    /** 创建日期 */
    private Date createDate;
    /** 创建者 */
    private String creator;
    /** 修改日期 */
    private Date modifyDate;
    /** 修改者 */
    private String modifier;
    @Column(name = "app_id")
    public String getAppId() {
        return appId;
    }
    public void setAppId(String appId) {
        this.appId = appId;
    }
    @Column(name = "subscribed_url")
    public String getSubscribedUrl() {
        return subscribedUrl;
    }
    public void setSubscribedUrl(String subscribedUrl) {
        this.subscribedUrl = subscribedUrl;
    }
    @Column(name = "channel")
    public String getChannel() {
        return channel;
    }
    public void setChannel(String channel) {
        this.channel = channel;
    }
    @Column(name = "remark")
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_date", nullable = false, updatable = false)
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    @Column(name = "creator")
    public String getCreator() {
        return creator;
    }
    public void setCreator(String creator) {
        this.creator = creator;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "modify_date", nullable = false)
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
    @Column(name = "modifier")
    public String getModifier() {
        return modifier;
    }
    public void setModifier(String modifier) {
        this.modifier = modifier;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!IdEntity.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        IdEntity other = (IdEntity) obj;
        return getId() != null ? getId().equals(other.getId()) : false;
    }
    @Override
    public int hashCode() {
        int hashCode = 17;
        hashCode += null == getId() ? 0 : getId().hashCode() * 31;
        return hashCode;
    }
}

+ 65 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/AccessToken.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.entity.security;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table(name = "wx_access_token")
public class AccessToken extends IdEntity {
    private static final long serialVersionUID = -3297644428262254694L;
    private String access_token;
    private String acc_id;
    private Long add_timestamp;
    private Long expires_in;
    private Date czrq;
    public String getAcc_id() {
        return acc_id;
    }
    public void setAcc_id(String acc_id) {
        this.acc_id = acc_id;
    }
    public String getAccess_token() {
        return access_token;
    }
    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }
    public Long getAdd_timestamp() {
        return add_timestamp;
    }
    public void setAdd_timestamp(Long add_timestamp) {
        this.add_timestamp = add_timestamp;
    }
    public Long getExpires_in() {
        return expires_in;
    }
    public void setExpires_in(Long expires_in) {
        this.expires_in = expires_in;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 71 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/JsApiTicket.java

@ -0,0 +1,71 @@
package com.yihu.wlyy.entity.security;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * JavaScript API访问所需要的凭据
 */
@Entity
@Table(name = "wx_jsapi_ticket")
public class JsApiTicket extends IdEntity {
    private static final long serialVersionUID = -3297644428262254694L;
    private String jsapi_ticket;
    private String acc_id;;
    private Long add_timestamp;
    private Long expires_in;
    private Date czrq;
    public String getAcc_id() {
        return acc_id;
    }
    public void setAcc_id(String acc_id) {
        this.acc_id = acc_id;
    }
    public String getJsapi_ticket() {
        return jsapi_ticket;
    }
    public void setJsapi_ticket(String jsapi_ticket) {
        this.jsapi_ticket = jsapi_ticket;
    }
    public Long getAdd_timestamp() {
        return add_timestamp;
    }
    public void setAdd_timestamp(Long add_timestamp) {
        this.add_timestamp = add_timestamp;
    }
    public Long getExpires_in() {
        return expires_in;
    }
    public void setExpires_in(Long expires_in) {
        this.expires_in = expires_in;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 29 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/RSA.java

@ -0,0 +1,29 @@
package com.yihu.wlyy.entity.security;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
/**
 * 非对象算法加密信息
 * @author George
 *
 */
@Entity
@Table(name = "dm_rsa")
public class RSA extends IdEntity {
	private static final long serialVersionUID = 7832717679571844202L;
	
	private byte[] data;
	@Lob
	public byte[] getData() {
	    return data;
	}
	
	public void setData(byte[] data){
		this.data = data;
	}
}

+ 81 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/entity/security/Token.java

@ -0,0 +1,81 @@
package com.yihu.wlyy.entity.security;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table(name = "wlyy_token")
public class Token extends IdEntity {
	private static final long serialVersionUID = -3297644428262254694L;
	private String user;
	private Integer platform;   // 1患者端,2医生端app,3微信公众号wechat,4医生端pc
	private Date timeout;
	private String imei;
	private String token;
	private Date czrq;
	private String del;
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public Integer getPlatform() {
		return platform;
	}
	public void setPlatform(Integer platform) {
		this.platform = platform;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getTimeout() {
		return timeout;
	}
	public void setTimeout(Date timeout) {
		this.timeout = timeout;
	}
	public String getImei() {
		return imei;
	}
	public void setImei(String imei) {
		this.imei = imei;
	}
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
}

+ 116 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/AccessDecisionManagerImpl.java

@ -0,0 +1,116 @@
package com.yihu.wlyy.filter;
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.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/7/22
 */
/**
 * Spring Security提供了一些拦截器,来控制对安全对象的访问权限,例如方法调用或web请求。
 * 一个是否允许执行调用的预调用决定,是由AccessDecisionManager实现的。
 * 这个 AccessDecisionManager 被AbstractSecurityInterceptor调用,
 * 它用来作最终访问控制的决定。
 */
public class AccessDecisionManagerImpl implements AccessDecisionManager {
    @Autowired
    RoleCache roleCache;
    @Autowired
    private HttpServletRequest request;
    /**
     * 验证用户是否拥有权限
     *
     * @param authentication   用户权限列表
     * @param object           FilterInvocation 请求信息
     * @param configAttributes 当前访问路径所需权限
     * @throws AccessDeniedException               如无权限 抛出该异常
     * @throws InsufficientAuthenticationException
     */
    public void decide(Authentication authentication, Object object,
                       Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
        if (configAttributes == null) {
            return;
        }
//        if(true)return;
        FilterInvocation fi = (FilterInvocation) object;
        String url = fi.getRequestUrl();
        Iterator<ConfigAttribute> ite = configAttributes.iterator();
        ConfigAttribute ca;
        int index;
        while (ite.hasNext()) {
            ca = ite.next();
            if ("anonymous".equals(ca.toString()) || "permitAll".equals(ca.toString())) {
                return;
            }
        }
        index = url.indexOf("?");
        if (index != -1)
            url = url.substring(0, index);
        url.replaceAll("/+", "/");
        if (!roleCache.contains(url))
            return;
        Object res = null;
        try {
            res = request.getSession().getAttribute("token");
        } catch (Exception ex) {
            res = fi.getRequest().getSession().getAttribute("token");
        }
        //ga 为用户所被赋予的权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//        if(authentication.getAuthorities().contains(new SimpleGrantedAuthority(url)))
//            return;
        if (res != null) {
            ArrayList<String> token = (ArrayList<String>) res;
            if (token.contains(url))
                return;
        }
        throw new AccessDeniedException("没有权限!");
    }
    /**
     * 在启动的时候被AbstractSecurityInterceptor调用,)
     * 来决定AccessDecisionManager是否可以执行传递ConfigAttribute。
     *
     * @param attribute
     * @return
     */
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }
    /**
     * 被安全拦截器实现调用,
     * 包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型。
     *
     * @param clazz
     * @return
     */
    public boolean supports(Class<?> clazz) {
        return true;
    }
}

+ 61 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/AccessDeniedHandlerImpl.java

@ -0,0 +1,61 @@
package com.yihu.wlyy.filter;
import com.yihu.wlyy.util.ControllerTools;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/7/22
 */
/**
 * 错误信息拦截器
 */
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    private String errorPage = "/error/403.jsp";
    /**
     * 拦截错误信息, 并按逻辑返回错误到前端页面
     *
     * @param request
     * @param response
     * @param accessDeniedException
     * @throws IOException
     * @throws ServletException
     */
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        if (ControllerTools.isAjaxRequest(request)) {
            response.setHeader("noPermission", "true");
            ControllerTools.print(response, "{}");
        } else if (!response.isCommitted()) {
            if (errorPage != null) {
                // Set the 403 status code.
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                // forward to error page.
                RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
                dispatcher.forward(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
            }
        }
    }
    public void setErrorPage(String errorPage) {
        if ((errorPage != null) && !errorPage.startsWith("/")) {
            throw new IllegalArgumentException("errorPage must begin with '/'");
        }
        this.errorPage = errorPage;
    }
}

+ 33 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/RoleCache.java

@ -0,0 +1,33 @@
package com.yihu.wlyy.filter;
import org.springframework.stereotype.Service;
import java.util.concurrent.CopyOnWriteArrayList;
@Service("roleCache")
public class RoleCache {
    private static CopyOnWriteArrayList<String> resourceList = new CopyOnWriteArrayList<>();
    public RoleCache() throws Exception {
    }
    public boolean contains(String url) {
        return resourceList.contains(url);
    }
    public void addRes(String res) {
        synchronized (resourceList) {
            resourceList.add(res);
        }
    }
    public void removeRes(String res) {
        synchronized (resourceList) {
            resourceList.remove(res);
        }
    }
    public void loadRes(CopyOnWriteArrayList<String> resList) {
        resourceList = resList;
    }
}

+ 41 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/filter/SessionOutTimeFilter.java

@ -0,0 +1,41 @@
package com.yihu.wlyy.filter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author lincl
 * @version 1.0
 * @created 2016/3/26
 */
@Component("loginFilter")
public class SessionOutTimeFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String path = httpServletRequest.getRequestURI();
        if (path.indexOf("/login") != -1
                || path.indexOf("/out") != -1
                || path.indexOf("/error") != -1
                || path.indexOf(httpServletRequest.getContextPath() + "/static") != -1
                || path.indexOf("swagger") != -1
                || path.indexOf(httpServletRequest.getContextPath() + "/v2/api-docs") != -1) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        Object isLogin = httpServletRequest.getSession().getAttribute("isLogin");
        if (isLogin == null || (String) isLogin != "true") {
//            request.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"请重新登入");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login");
            return;
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

+ 36 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/interceptors/UserSessionInterceptor.java

@ -0,0 +1,36 @@
//package com.yihu.wlyy.interceptors;
//
//import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
//import org.springframework.web.servlet.ModelAndView;
//import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
///**
// * Created by yww on 2016/10/19.
// */
//public class UserSessionInterceptor extends HandlerInterceptorAdapter {
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //判断是否登录
//        Object isLogin = request.getSession().getAttribute("isLogin");
//        if(isLogin != null && (String)isLogin == "true"){
//            return true;
//        }else {
////            request.setAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"请重新登入");
//            response.sendRedirect(request.getContextPath()+"/login");
//            return false;
//        }
//    }
//
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        super.postHandle(request, response, handler, modelAndView);
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        super.afterCompletion(request, response, handler, ex);
//    }
//}

+ 86 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/listener/ApplicationReadyEventListener.java

@ -0,0 +1,86 @@
package com.yihu.wlyy.listener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.redis.RedisMqChannel;
import com.yihu.wlyy.entity.redis.RedisMqMessageLog;
import com.yihu.wlyy.service.redis.CustomMessageListenerAdapter;
import com.yihu.wlyy.service.redis.MessageCommonBiz;
import com.yihu.wlyy.service.redis.pubsub.RedisMqChannelService;
import com.yihu.wlyy.service.redis.pubsub.RedisMqMessageLogService;
import com.yihu.wlyy.service.redis.pubsub.RedisMqSubscriberService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * SpringBoot 启动完成的监听器
 *
 * @author 张进军
 * @date 2017/11/14 17:48
 */
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
    Logger logger = Logger.getLogger(ApplicationReadyEventListener.class);
    @Autowired
    RedisMessageListenerContainer redisMessageListenerContainer;
    @Autowired
    RedisMqChannelService redisMqChannelService;
    @Autowired
    RedisMqSubscriberService redisMqSubscriberService;
    @Autowired
    RedisMqMessageLogService redisMqMessageLogService;
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    ObjectMapper objectMapper;
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        try {
            logger.info("开启消息队列,并添加队列的消息监听器 start...");
            // 开启消息队列,并添加队列的消息监听器
            List<RedisMqChannel> channelList = redisMqChannelService.search("");
            for (RedisMqChannel channel : channelList) {
                ChannelTopic topic = new ChannelTopic(channel.getChannel());
                CustomMessageListenerAdapter messageListener = MessageCommonBiz.newCustomMessageListenerAdapter(channel.getChannel());
                redisMessageListenerContainer.addMessageListener(messageListener, topic);
                // 将未消费的消息重新加入到队列进行发布
                String msgFilter = "channel=" + channel.getChannel() + ";status=0;";
                List<RedisMqMessageLog> messageLogList = redisMqMessageLogService.search(msgFilter);
                for (RedisMqMessageLog messageLog : messageLogList) {
                    // 重新记录消息,并删除该消息的旧记录
                    RedisMqMessageLog redisMqMessageLog = MessageCommonBiz.newMessageLog(channel.getChannel(),
                            messageLog.getPublisherAppId(), messageLog.getMessage());
                    redisMqMessageLogService.saveAndDeleteOld(redisMqMessageLog, messageLog.getId());
                    // 发布消息
                    Map<String, Object> messageMap = new HashMap<>();
                    messageMap.put("messageLogId", redisMqMessageLog.getId());
                    messageMap.put("messageContent", messageLog.getMessage());
                    redisTemplate.convertAndSend(channel.getChannel(), objectMapper.writeValueAsString(messageMap));
                }
            }
            logger.info("开启消息队列,并添加队列的消息监听器 end...");
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

+ 19 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/listener/ApplicationStart.java

@ -0,0 +1,19 @@
package com.yihu.wlyy.listener;
import com.yihu.wlyy.filter.RoleCache;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class ApplicationStart implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
            RoleCache roleCache = (RoleCache) contextRefreshedEvent.getApplicationContext().getBean("roleCache");
        }
    }
}

+ 19 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/SocialSecurityInfoDao.java

@ -0,0 +1,19 @@
package com.yihu.wlyy.repository;
import com.yihu.wlyy.entity.SocialSecurityInfo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by lyr on 2016/8/8.
 */
public interface SocialSecurityInfoDao extends PagingAndSortingRepository<SocialSecurityInfo, String>, JpaSpecificationExecutor<SocialSecurityInfo> {
    SocialSecurityInfo findBySfzh18(String idcard);
    @Query("select a from SocialSecurityInfo a where a.id = (select max(b.id) from SocialSecurityInfo b where b.sfzh18 = ?1)")
    SocialSecurityInfo findBySfzh18Max(String idcard);
    @Query("select a from SocialSecurityInfo a where a.id = (select max(b.id) from SocialSecurityInfo b where b.id0000 = ?1)")
    SocialSecurityInfo findBySfzh15Max(String idcard);
}

+ 22 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/SystemDictDao.java

@ -0,0 +1,22 @@
package com.yihu.wlyy.repository;
import com.yihu.wlyy.entity.SystemDict;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/13.
 */
public interface SystemDictDao extends PagingAndSortingRepository<SystemDict, Long>, JpaSpecificationExecutor<SystemDict> {
    @Query("from SystemDict s where s.dictName=?1 order by sort asc ")
    List<SystemDict> findByDictName(String name);
    List<SystemDict> findByDictNameAndCode(String name,String code);
    @Query("select s.value from SystemDict s where s.dictName=?1 and s.code =?2")
    String findByDictNameAndCode2(String dictName, String code);
}

+ 12 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/SystemDictListDao.java

@ -0,0 +1,12 @@
package com.yihu.wlyy.repository;
import com.yihu.wlyy.entity.SystemDictList;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Administrator on 2016/8/13.
 */
public interface SystemDictListDao extends PagingAndSortingRepository<SystemDictList, Long>, JpaSpecificationExecutor<SystemDictList> {
}

+ 41 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/UserDao.java

@ -0,0 +1,41 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.wlyy.entity.User;
public interface UserDao extends PagingAndSortingRepository<User, Long>, JpaSpecificationExecutor<User> {
	User findByMobile(String mobile);
	
	User findByCode(String code);
	
	@Query("select a from User a where a.organizationId = ?1")
	List<User> findByOrgid(long orgId);
	@Query("from User a where a.mobile = ?1")
	List<User> findByPhone(String mobile);
	@Query("from User a where a.mobile = ?1 and a.id!=?2")
	List<User> findByPhoneWithOutId(String mobile, Long id);
    @Query("from User a where a.name like ?1 order by code")
    Page<User> searchUsersByName(String name, Pageable pageRequest);
	List<User> findBySeat(String seat);
	User findByJobNo(String jobNo);
}

+ 21 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheAuthorizationDao.java

@ -0,0 +1,21 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisCacheAuthorization;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
/**
 * 缓存授权 DAO
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
public interface RedisCacheAuthorizationDao extends PagingAndSortingRepository<RedisCacheAuthorization, Integer> {
    RedisCacheAuthorization findByCategoryCodeAndAppId(@Param("categoryCode") String categoryCode, @Param("appId") String appId);
    @Query(" FROM RedisCacheAuthorization a WHERE a.id <> :id AND a.categoryCode = :categoryCode AND a.appId = :appId ")
    RedisCacheAuthorization isUniqueAppId(@Param("id") Integer id, @Param("categoryCode") String categoryCode, @Param("appId") String appId);
}

+ 22 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheCategoryDao.java

@ -0,0 +1,22 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisCacheCategory;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
/**
 * 缓存分类 DAO
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
public interface RedisCacheCategoryDao extends PagingAndSortingRepository<RedisCacheCategory, Integer> {
    @Query(" FROM RedisCacheCategory a WHERE a.id <> :id AND a.name = :name ")
    RedisCacheCategory isUniqueName(@Param("id") Integer id, @Param("name") String name);
    @Query(" FROM RedisCacheCategory a WHERE a.id <> :id AND a.code = :code ")
    RedisCacheCategory isUniqueCode(@Param("id") Integer id, @Param("code") String code);
}

+ 21 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheKeyMemoryDao.java

@ -0,0 +1,21 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisCacheKeyMemory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
 * 缓存Key值占用内存分析 DAO
 *
 * @author 张进军
 * @date 2017/12/6 14:58
 */
public interface RedisCacheKeyMemoryDao extends JpaRepository<RedisCacheKeyMemory, Integer> {
    RedisCacheKeyMemory findByCacheKey(@Param("cacheKey") String cacheKey);
    @Query(value = "SELECT SUM(a.size_in_bytes) FROM redis_cache_key_memory a WHERE a.cache_key LIKE :keyPrefix%", nativeQuery = true)
    Long sumCategoryMemory(@Param("keyPrefix") String keyPrefix);
}

+ 24 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheKeyRuleDao.java

@ -0,0 +1,24 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisCacheKeyRule;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
/**
 * 缓存Key生成规则 DAO
 *
 * @author 张进军
 * @date 2017/11/23 11:28
 */
public interface RedisCacheKeyRuleDao extends PagingAndSortingRepository<RedisCacheKeyRule, Integer> {
    RedisCacheKeyRule findByCode(@Param("code") String code);
    @Query(" FROM RedisCacheKeyRule a WHERE a.id <> :id AND a.name = :name ")
    RedisCacheKeyRule isUniqueName(@Param("id") Integer id, @Param("name") String name);
    @Query(" FROM RedisCacheKeyRule a WHERE a.id <> :id AND a.code = :code ")
    RedisCacheKeyRule isUniqueCode(@Param("id") Integer id, @Param("code") String code);
}

+ 19 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisCacheResponseTimeLogDao.java

@ -0,0 +1,19 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisCacheResponseTimeLog;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * 缓存获取的响应时间日志 DAO
 *
 * @author 张进军
 * @date 2017/12/4 08:56
 */
public interface RedisCacheResponseTimeLogDao extends PagingAndSortingRepository<RedisCacheResponseTimeLog, String> {
    List<RedisCacheResponseTimeLog> findByCacheKeyOrderByCreateDateAsc(@Param("cacheKey") String cacheKey);
}

+ 24 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqChannelDao.java

@ -0,0 +1,24 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisMqChannel;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
/**
 * redis消息队列 DAO
 *
 * @author 张进军
 * @date 2017/11/10 11:45
 */
public interface RedisMqChannelDao extends PagingAndSortingRepository<RedisMqChannel, Integer> {
    RedisMqChannel findByChannel(@Param("channel") String channel);
    @Query(" FROM RedisMqChannel rmc WHERE rmc.id <> :id AND rmc.channel = :channel ")
    RedisMqChannel isUniqueChannel(@Param("id") Integer id, @Param("channel") String channel);
    @Query(" FROM RedisMqChannel rmc WHERE rmc.id <> :id AND rmc.channelName = :channelName ")
    RedisMqChannel isUniqueChannelName(@Param("id") Integer id, @Param("channelName") String channelName);
}

+ 19 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqMessageLogDao.java

@ -0,0 +1,19 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisMqMessageLog;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * redis消息记录 DAO
 *
 * @author 张进军
 * @date 2017/11/10 11:45
 */
public interface RedisMqMessageLogDao extends PagingAndSortingRepository<RedisMqMessageLog, String> {
    List<RedisMqMessageLog> findByChannelAndStatus(@Param("channel") String channel, @Param("status") String status);
}

+ 25 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqPublisherDao.java

@ -0,0 +1,25 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisMqPublisher;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * redis消息发布者 DAO
 *
 * @author 张进军
 * @date 2017/11/20 09:35
 */
public interface RedisMqPublisherDao extends PagingAndSortingRepository<RedisMqPublisher, Integer> {
    List<RedisMqPublisher> findByChannel(@Param("channel") String channel);
    RedisMqPublisher findByChannelAndAppId(@Param("channel") String channel, @Param("appId") String appId);
    @Query(" FROM RedisMqPublisher rmp WHERE rmp.id <> :id AND rmp.channel = :channel AND rmp.appId = :appId ")
    RedisMqPublisher isUniqueAppId(@Param("id") Integer id, @Param("channel") String channel, @Param("appId") String appId);
}

+ 26 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/redis/RedisMqSubscriberDao.java

@ -0,0 +1,26 @@
package com.yihu.wlyy.repository.redis;
import com.yihu.wlyy.entity.redis.RedisMqSubscriber;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
 * redis消息订阅者 DAO
 *
 * @author 张进军
 * @date 2017/11/10 11:45
 */
public interface RedisMqSubscriberDao extends PagingAndSortingRepository<RedisMqSubscriber, Integer> {
    List<RedisMqSubscriber> findByChannel(@Param("channel") String channel);
    @Query(" FROM RedisMqSubscriber rms WHERE rms.id <> :id AND rms.channel = :channel AND rms.appId = :appId ")
    RedisMqSubscriber isUniqueAppId(@Param("id") Integer id, @Param("channel") String channel, @Param("appId") String appId);
    @Query(" FROM RedisMqSubscriber rms WHERE rms.id <> :id AND rms.channel = :channel AND rms.subscribedUrl = :subscribedUrl ")
    RedisMqSubscriber isUniqueSubscribedUrl(@Param("id") Integer id, @Param("channel") String channel, @Param("subscribedUrl") String subscribedUrl);
}

+ 17 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/AccessTokenDao.java

@ -0,0 +1,17 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository.security;
import com.yihu.wlyy.entity.security.AccessToken;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface AccessTokenDao extends PagingAndSortingRepository<AccessToken, Long> {
	
	@Query("select p from AccessToken p where p.acc_id = ?1 order by p.add_timestamp desc")
	Iterable<AccessToken> findAccessToken(String accId);
	
}

+ 17 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/JsapiTicketDao.java

@ -0,0 +1,17 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository.security;
import com.yihu.wlyy.entity.security.JsApiTicket;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface JsapiTicketDao extends PagingAndSortingRepository<JsApiTicket, Long> {
	
	@Query("select p from JsApiTicket p where p.acc_id = ?1 order by p.add_timestamp desc")
	Iterable<JsApiTicket> findJsapiTicket(String accId);
	
}

+ 14 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/RSADao.java

@ -0,0 +1,14 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.repository.security;
import com.yihu.wlyy.entity.security.RSA;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface RSADao extends PagingAndSortingRepository<RSA, Long>, JpaSpecificationExecutor<RSA> {
	
}

+ 46 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/repository/security/TokenDao.java

@ -0,0 +1,46 @@
package com.yihu.wlyy.repository.security;
import com.yihu.wlyy.entity.security.Token;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TokenDao extends PagingAndSortingRepository<Token, Long> {
	
	@Modifying
	@Query("delete Token a where a.user = ?1")
	int deleteByUser(String user);
	@Modifying
	@Query("delete Token a where a.user = ?1 and platform=?2")
	int deleteByUserAndPlatform(String user, Integer platform);
	
	@Modifying
	@Query("delete Token a where a.token = ?1")
	int deleteByToken(String token);
	
//	@Query("select a from Token a where a.user = ?1 and a.platform = ?2 and a.del = '1'")
//	Token findByUser(String user, int platform);
	
//	@Query("select a from Token a where a.user = ?1 and a.del = '1'")
//	Token findByUser(String user);
	
//	@Query("select count(1) from Token a where a.user = ?1 and a.del = '1'")
//	int countByUser(String user);
	
	@Query("select a from Token a where a.token = ?1 and a.del = '1'")
	Token findByToken(String token);
	
	@Query("select a from Token a where a.user = ?1 and a.platform = ?2 and a.del = '1'")
	Token findByPatient(String patient, int platform);
	
	@Modifying
	@Query("delete Token a where a.user = ?1 and a.platform = 3 and a.del = '1'")
	int deleteWxTokenByPatient(String patient);
	@Query("select a from Token a where a.imei = ?1 and a.platform = 3")
	Page<Token> findByOpenid(String openid, Pageable pageable);
}

Fichier diff supprimé car celui-ci est trop grand
+ 99 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/BaseService.java


+ 34 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/ServiceException.java

@ -0,0 +1,34 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.service;
/**
 * Service层公用的Exception.
 * 
 * 继承自RuntimeException, 从由Spring管理事务的函数中抛出时会触发事务回滚.
 * 
 * @author calvin
 */
public class ServiceException extends RuntimeException {
	private static final long serialVersionUID = 3583566093089790852L;
	public ServiceException() {
		super();
	}
	public ServiceException(String message) {
		super(message);
	}
	public ServiceException(Throwable cause) {
		super(cause);
	}
	public ServiceException(String message, Throwable cause) {
		super(message, cause);
	}
}

+ 55 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/manager/account/AdminService.java

@ -0,0 +1,55 @@
package com.yihu.wlyy.service.manager.account;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yihu.wlyy.entity.User;
import com.yihu.wlyy.repository.UserDao;
@Service
public class AdminService {
	private UserDao userDao;
	
	@Autowired
	public void setUserDao(UserDao userDao){
		this.userDao = userDao;
	}
	
	public List<User> getAllUser() {
		return (List<User>) userDao.findAll();
	}
	
	public User getUser(Long id) {
		return userDao.findOne(id);
	}
	/**
	 * 根据手机号查询用户信息
	 * @param mobile 手机号
	 * @return
	 */
	public User findUserByMobile(String mobile) {
		return userDao.findByMobile(mobile);
	}
	
//	/**
//	 * 判断是否超级管理员.
//	 */
//	private boolean isSupervisor(Long id) {
//		return id == 1;
//	}
//
//	/**
//	 * 取出Shiro中的当前用户LoginName.
//	 */
//	private String getCurrentUserName() {
//		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		return user.mobile;
//	}
}

+ 0 - 0
patient-co-manage/redis-cache/src/main/java/com/yihu/wlyy/service/manager/dict/SystemDictService.java


Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff