소스 검색

知识库预处理加入redis缓存

gaodm 5 년 전
부모
커밋
1654f0b30a

+ 11 - 0
aipt-service/pom.xml

@@ -159,6 +159,17 @@
             <artifactId>spring-boot-data-aggregator-starter</artifactId>
         </dependency>
 
+        <!--redis设置-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+        <!-- 必须加上,jedis依赖此  -->
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-pool2</artifactId>
+        </dependency>
+
     </dependencies>
 
     <build>

+ 5 - 2
data-service/src/main/java/com/diagbot/config/CacheDelete.java

@@ -1,19 +1,21 @@
 package com.diagbot.config;
 
 import com.diagbot.facade.CacheFacade;
+import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.CommandLineRunner;
 import org.springframework.core.annotation.Order;
 import org.springframework.stereotype.Component;
 
 /**
- * @description:
+ * @description: 项目启动后初始化缓存
  * @author: zhoutg
  * @time: 2020/4/3 14:31
  */
 @Component //把类交给spring容器管理
 @Order(100)  //使用order属性,设置该类在spring容器中的加载顺序
-public class CacheDelete  implements CommandLineRunner {
+@Slf4j
+public class CacheDeleteInit implements CommandLineRunner {
 
     @Autowired
     CacheFacade cacheFacade;
@@ -21,6 +23,7 @@ public class CacheDelete  implements CommandLineRunner {
     @Override
     public void run(String... args) throws Exception {
         // 服务启动清除redis缓存
+        log.info("知识库预处理缓存启动初始化成功!");
         cacheFacade.clear();
     }
 }

+ 169 - 0
aipt-service/src/main/java/com/diagbot/config/RedisConfigurer.java

@@ -0,0 +1,169 @@
+package com.diagbot.config;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.cache.CacheManager;
+import org.springframework.cache.annotation.CachingConfigurerSupport;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.cache.interceptor.KeyGenerator;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+import org.springframework.data.redis.cache.RedisCacheConfiguration;
+import org.springframework.data.redis.cache.RedisCacheManager;
+import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
+import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
+import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
+import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializationContext;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+import java.time.Duration;
+
+@Configuration
+@EnableCaching
+@Slf4j
+public class RedisConfigurer extends CachingConfigurerSupport {
+
+    @Value("${spring.redis.database.data-service}")
+    private String databaseCache;
+    @Value("${spring.redis.host}")
+    private String host;
+    @Value("${spring.redis.password}")
+    private String password;
+    @Value("${spring.redis.port}")
+    private int port;
+    @Value("${spring.redis.timeout}")
+    private int timeout;
+    @Value("${spring.redis.lettuce.pool.max-active}")
+    private int maxActive;
+    @Value("${spring.redis.lettuce.pool.max-idle}")
+    private int maxIdle;
+    @Value("${spring.redis.lettuce.pool.max-wait}")
+    private long maxWaitMillis;
+    @Value("${spring.redis.lettuce.pool.min-idle}")
+    private int minIdle;
+
+    @Autowired
+    @Qualifier("factoryForCache")
+    private LettuceConnectionFactory lettuceConnectionFactory;
+
+    @Bean
+    public GenericObjectPoolConfig getRedisConfig() {
+        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
+        poolConfig.setMaxTotal(maxActive);
+        poolConfig.setMaxIdle(maxIdle);
+        poolConfig.setMaxWaitMillis(maxWaitMillis);
+        poolConfig.setMinIdle(minIdle);
+        return poolConfig;
+    }
+
+    @Bean
+    @Override
+    public CacheManager cacheManager() {
+        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
+                // 设置 key为string序列化
+                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
+                // 设置value为json序列化
+                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getSerializer()))
+                // 不缓存空值
+                .disableCachingNullValues();
+        RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
+                .cacheDefaults(redisCacheConfiguration)
+                .transactionAware()
+                .build();
+        cacheManager.afterPropertiesSet();
+        log.info("RedisCacheManager config success");
+        return cacheManager;
+    }
+
+    @Bean(name = "springSessionDefaultRedisSerializer")
+    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
+        return new GenericJackson2JsonRedisSerializer();
+    }
+
+    /**
+     * 缓存使用的redis
+     *
+     * @return
+     */
+    @Bean("factoryForCache")
+    @Primary
+    public LettuceConnectionFactory redisConnectionFactory() {
+        return getRedisConnectionFactory(Integer.valueOf(databaseCache));
+    }
+
+    @Bean
+    public RedisTemplate<String, Object> redisTemplate() {
+        return getRedisTemplate(lettuceConnectionFactory);
+    }
+
+    private Jackson2JsonRedisSerializer getSerializer() {
+        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
+        ObjectMapper om = new ObjectMapper();
+        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(om);
+        return jackson2JsonRedisSerializer;
+    }
+
+    @Bean
+    @Override
+    public KeyGenerator keyGenerator() {
+        //  设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
+        // 使用:进行分割,可以很多显示出层级关系
+        // 这里其实就是new了一个KeyGenerator对象
+        return (target, method, params) -> {
+            StringBuilder sb = new StringBuilder();
+            sb.append(target.getClass().getName());
+            sb.append(":");
+            sb.append(method.getName());
+            for (Object obj : params) {
+                sb.append(":" + String.valueOf(obj));
+            }
+            String rsToUse = String.valueOf(sb);
+            log.info("自动生成Redis Key -> [{}]", rsToUse);
+            return rsToUse;
+        };
+    }
+
+    private LettuceConnectionFactory getRedisConnectionFactory(Integer database) {
+        RedisStandaloneConfiguration connection = new RedisStandaloneConfiguration();
+        connection.setHostName(host);
+        connection.setPort(port);
+        connection.setPassword(password);
+        connection.setDatabase(database);
+        GenericObjectPoolConfig poolConfig = getRedisConfig();
+        LettuceClientConfiguration builder = LettucePoolingClientConfiguration.builder()
+                .commandTimeout(Duration.ofMillis(timeout))
+                .poolConfig(poolConfig)
+                .shutdownTimeout(Duration.ZERO)
+                .build();
+        LettuceConnectionFactory factory = new LettuceConnectionFactory(connection, builder);
+        return factory;
+    }
+
+    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
+        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
+        redisTemplate.setConnectionFactory(factory);
+
+        // value值的序列化
+        redisTemplate.setValueSerializer(getSerializer());
+        redisTemplate.setHashValueSerializer(getSerializer());
+        // key的序列化采用StringRedisSerializer
+        redisTemplate.setKeySerializer(new StringRedisSerializer());
+        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
+        redisTemplate.afterPropertiesSet();
+        return redisTemplate;
+    }
+}
+ 

+ 23 - 0
aipt-service/src/main/java/com/diagbot/facade/CacheFacade.java

@@ -0,0 +1,23 @@
+package com.diagbot.facade;
+
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.stereotype.Component;
+
+/**
+ * @Description:
+ * @Author:zhoutg
+ * @time: 2018/11/23 11:37
+ */
+@Component
+public class CacheFacade {
+
+    /**
+     * 清除缓存信息
+     *
+     * @return
+     */
+    @CacheEvict(value = "aipt-service", allEntries = true)
+    public void clear() {
+
+    }
+}

+ 39 - 0
aipt-service/src/main/java/com/diagbot/web/CacheController.java

@@ -0,0 +1,39 @@
+package com.diagbot.web;
+
+import com.diagbot.annotation.SysLogger;
+import com.diagbot.dto.RespDTO;
+import com.diagbot.facade.CacheFacade;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * <p>
+ * 缓存 前端控制器
+ * </p>
+ *
+ * @author zhoutg
+ * @since 2018-12-25
+ */
+@RequestMapping("/cache")
+@RestController
+@SuppressWarnings("unchecked")
+@Api(value = "知识库预处理缓存API", tags = { "知识库预处理缓存API" })
+public class CacheController {
+
+
+    @Autowired
+    CacheFacade cacheFacade;
+
+    @ApiOperation(value = "清除缓存[by:zhoutg]",
+            notes = "")
+    @PostMapping("/clear")
+    @SysLogger("clear")
+    public RespDTO<Boolean> clear() {
+        cacheFacade.clear();
+        return RespDTO.onSuc(true);
+    }
+}

+ 15 - 0
config-server/src/main/resources/shared/aipt-service-dev.yml

@@ -66,6 +66,21 @@ spring:
     publisher-confirms: true
     virtual-host: /
 
+  #redis
+  redis:
+    database:
+      data-service: 9 # aipt服务缓存信息
+    host: 192.168.2.236  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
 #mybatis
 mybatis-plus:
   mapper-locations: classpath:/mapper/*Mapper.xml

+ 15 - 0
config-server/src/main/resources/shared/aipt-service-local.yml

@@ -66,6 +66,21 @@ spring:
     publisher-confirms: true
     virtual-host: /
 
+  #redis
+  redis:
+    database:
+      data-service: 9 # aipt服务缓存信息
+    host: 192.168.2.236  #Redis服务器地址
+    port: 6378 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
 #mybatis
 mybatis-plus:
   mapper-locations: classpath:/mapper/*Mapper.xml

+ 15 - 0
config-server/src/main/resources/shared/aipt-service-pre.yml

@@ -66,6 +66,21 @@ spring:
     publisher-confirms: true
     virtual-host: /
 
+  #redis
+  redis:
+    database:
+      data-service: 9 # aipt服务缓存信息
+    host: 192.168.2.121  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
 #mybatis
 mybatis-plus:
   mapper-locations: classpath:/mapper/*Mapper.xml

+ 15 - 0
config-server/src/main/resources/shared/aipt-service-pro.yml

@@ -66,6 +66,21 @@ spring:
     publisher-confirms: true
     virtual-host: /
 
+  #redis
+  redis:
+    database:
+      data-service: 9 # aipt服务缓存信息
+    host: 192.168.2.122  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
 #mybatis
 mybatis-plus:
   mapper-locations: classpath:/mapper/*Mapper.xml

+ 15 - 0
config-server/src/main/resources/shared/aipt-service-test.yml

@@ -66,6 +66,21 @@ spring:
     publisher-confirms: true
     virtual-host: /
 
+  #redis
+  redis:
+    database:
+      data-service: 9 # aipt服务缓存信息
+    host: 192.168.2.241  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
 #mybatis
 mybatis-plus:
   mapper-locations: classpath:/mapper/*Mapper.xml

+ 29 - 0
data-service/src/main/java/com/diagbot/config/CacheDeleteInit.java

@@ -0,0 +1,29 @@
+package com.diagbot.config;
+
+import com.diagbot.facade.CacheFacade;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.CommandLineRunner;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+
+/**
+ * @description: 项目启动后初始化缓存
+ * @author: zhoutg
+ * @time: 2020/4/3 14:31
+ */
+@Component //把类交给spring容器管理
+@Order(100)  //使用order属性,设置该类在spring容器中的加载顺序
+@Slf4j
+public class CacheDeleteInit  implements CommandLineRunner {
+
+    @Autowired
+    CacheFacade cacheFacade;
+
+    @Override
+    public void run(String... args) throws Exception {
+        // 服务启动清除redis缓存
+        log.info("页面推送模式缓存启动初始化成功!");
+        cacheFacade.clear();
+    }
+}

+ 1 - 1
data-service/src/main/java/com/diagbot/web/CacheController.java

@@ -21,7 +21,7 @@ import org.springframework.web.bind.annotation.RestController;
 @RequestMapping("/cache")
 @RestController
 @SuppressWarnings("unchecked")
-@Api(value = "缓存API", tags = { "缓存API" })
+@Api(value = "页面推送模式缓存API", tags = { "页面推送模式缓存API" })
 public class CacheController {
 
 

+ 1 - 1
data-service/src/main/java/com/diagbot/web/DictionaryInfoController.java

@@ -32,7 +32,7 @@ public class DictionaryInfoController {
     @Autowired
     DictionaryFacade dictionaryFacade;
 
-    @ApiOperation(value = "返回字典信息[by:zhoutg]",
+    @ApiOperation(value = "[已加缓存]返回字典信息[by:zhoutg]",
             notes = "")
     @PostMapping("/getList")
     @SysLogger("getList")

+ 1 - 1
data-service/src/main/java/com/diagbot/web/DisclaimerInformationController.java

@@ -29,7 +29,7 @@ public class DisclaimerInformationController {
     @Autowired
     DisclaimerInformationFacade disclaimerInformationFacade;
 
-    @ApiOperation(value = "获取免责申明详情[by:wangfeng]", notes = "获取免责申明详情")
+    @ApiOperation(value = "[已加缓存]获取免责申明详情[by:wangfeng]", notes = "获取免责申明详情")
     @PostMapping("/getDisclaimerInformations")
     @SysLogger("getDisclaimerInformations")
     public RespDTO<List<DisclaimerInformationDTO>> getDisclaimerInformations() {

+ 1 - 1
data-service/src/main/java/com/diagbot/web/SysSetController.java

@@ -34,7 +34,7 @@ public class SysSetController {
     @Autowired
     SysSetFacade sysSetFacade;
 
-    @ApiOperation(value = "根据医院编码获取配置信息[by:wangfeng]", notes = "hospitalCode :医院code  必填<br> ")
+    @ApiOperation(value = "[已加缓存]根据医院编码获取配置信息[by:wangfeng]", notes = "hospitalCode :医院code  必填<br> ")
     @PostMapping("/getSysSetInfoDatas")
     @SysLogger("getSysSetInfoDatas")
     public RespDTO<List<SysSetInfoDTO>> getSysSetInfoDatas(@Valid @RequestBody HospitalSetVO hospitalSetVO) {

+ 1 - 1
data-service/src/main/java/com/diagbot/web/VersionInfoController.java

@@ -28,7 +28,7 @@ public class VersionInfoController {
     @Autowired
     VersionInfoFacade versionInfoFacade;
 
-    @ApiOperation(value = "获取版本信息[by:wangfeng]", notes = "获取版本信息")
+    @ApiOperation(value = "[已加缓存]获取版本信息[by:wangfeng]", notes = "获取版本信息")
     @PostMapping("/getVersionInfoAlls")
     @SysLogger("getVersionInfoAlls")
     public RespDTO<VersionWrapperDTO> getVersionInfoAlls() {