ソースを参照

添加redis缓存

zhoutg 4 年 前
コミット
6f72ca927e

+ 5 - 0
pom.xml

@@ -141,6 +141,11 @@
             <artifactId>spring-boot-starter-data-redis</artifactId>
             <artifactId>spring-boot-starter-data-redis</artifactId>
         </dependency>
         </dependency>
 
 
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-pool2</artifactId>
+        </dependency>
+
         <dependency>
         <dependency>
             <groupId>net.logstash.logback</groupId>
             <groupId>net.logstash.logback</groupId>
             <artifactId>logstash-logback-encoder</artifactId>
             <artifactId>logstash-logback-encoder</artifactId>

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

@@ -0,0 +1,187 @@
+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.cache}")
+    private String databaseCache;
+    @Value("${spring.redis.database.token}")
+    private String databaseMr;
+    @Value("${spring.redis.host}")
+    private String host;
+    @Value("${spring.redis.password}")
+    private String password;
+    @Value("${spring.redis.port}")
+    private int port;
+    @Value("${spring.redis.timeout}")
+    private int timeout;
+    @Value("${spring.redis.lettuce.pool.max-active}")
+    private int maxActive;
+    @Value("${spring.redis.lettuce.pool.max-idle}")
+    private int maxIdle;
+    @Value("${spring.redis.lettuce.pool.max-wait}")
+    private long maxWaitMillis;
+    @Value("${spring.redis.lettuce.pool.min-idle}")
+    private int minIdle;
+
+    @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;
+        };
+    }
+
+    /**
+     * Token使用的redis
+     *
+     * @return
+     */
+    @Bean("factoryForToken")
+    public LettuceConnectionFactory redisConnectionFactoryForToken() {
+        return getRedisConnectionFactory(Integer.valueOf(databaseMr));
+    }
+
+    @Bean(name = "redisTemplateForToken")
+    public RedisTemplate<String, Object> redisTemplateForToken(@Qualifier("factoryForToken") LettuceConnectionFactory factory) {
+        return getRedisTemplate(factory);
+    }
+
+
+    private LettuceConnectionFactory getRedisConnectionFactory(Integer database) {
+        RedisStandaloneConfiguration connection = new RedisStandaloneConfiguration();
+        connection.setHostName(host);
+        connection.setPort(port);
+        connection.setPassword(password);
+        connection.setDatabase(database);
+        GenericObjectPoolConfig poolConfig = getRedisConfig();
+        LettuceClientConfiguration builder = LettucePoolingClientConfiguration.builder()
+                .commandTimeout(Duration.ofMillis(timeout))
+                .poolConfig(poolConfig)
+                .shutdownTimeout(Duration.ZERO)
+                .build();
+        LettuceConnectionFactory factory = new LettuceConnectionFactory(connection, builder);
+        return factory;
+    }
+
+    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
+        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
+        redisTemplate.setConnectionFactory(factory);
+
+        // value值的序列化
+        redisTemplate.setValueSerializer(getSerializer());
+        redisTemplate.setHashValueSerializer(getSerializer());
+        // key的序列化采用StringRedisSerializer
+        redisTemplate.setKeySerializer(new StringRedisSerializer());
+        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
+        redisTemplate.afterPropertiesSet();
+        return redisTemplate;
+    }
+}
+ 

+ 1 - 0
src/main/java/com/diagbot/facade/BillFacade.java

@@ -35,6 +35,7 @@ public class BillFacade {
         BillNeoDTO billNeoDTO = neoFacade.getBillNeo(billNeoVO);
         BillNeoDTO billNeoDTO = neoFacade.getBillNeo(billNeoVO);
 
 
         // 规则开发 TODO
         // 规则开发 TODO
+        neoFacade.getDrugCache();
         return null;
         return null;
     }
     }
 }
 }

+ 17 - 0
src/main/java/com/diagbot/facade/NeoFacade.java

@@ -2,8 +2,13 @@ package com.diagbot.facade;
 
 
 import com.diagbot.dto.BillNeoDTO;
 import com.diagbot.dto.BillNeoDTO;
 import com.diagbot.vo.BillNeoVO;
 import com.diagbot.vo.BillNeoVO;
+import org.springframework.cache.annotation.Cacheable;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
 /**
 /**
  * @Description: 图谱facade
  * @Description: 图谱facade
  * @author: Mark
  * @author: Mark
@@ -21,4 +26,16 @@ public class NeoFacade {
         // TODO 待处理业务
         // TODO 待处理业务
         return null;
         return null;
     }
     }
+
+    /**
+     * 返回药品缓存信息
+     *
+     * @return
+     */
+    @Cacheable(value = "cache", key = "'drugCache'")
+    public Map<String, List<String>> getDrugCache() {
+        Map<String, List<String>> res = new HashMap<>();
+
+        return res;
+    }
 }
 }

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

@@ -63,6 +63,22 @@ spring:
           username: root
           username: root
           password: lantone
           password: lantone
 
 
+  #redis
+  redis:
+    database:
+      cache: 8 # cache索引
+      token: 8 # Token索引
+    host: 192.168.2.236  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
   servlet:
   servlet:
     multipart:
     multipart:
       max-request-size: 2048MB
       max-request-size: 2048MB

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

@@ -63,6 +63,22 @@ spring:
           username: root
           username: root
           password: lantone
           password: lantone
 
 
+  #redis
+  redis:
+    database:
+      cache: 11 # cache索引
+      token: 11 # Token索引
+    host: 192.168.2.236  #Redis服务器地址
+    port: 6378 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
   servlet:
   servlet:
     multipart:
     multipart:
       max-request-size: 2048MB
       max-request-size: 2048MB

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

@@ -63,6 +63,22 @@ spring:
           username: teamback
           username: teamback
           password: goTulmLeon
           password: goTulmLeon
 
 
+  #redis
+  redis:
+    database:
+      cache: 8 # cache索引
+      token: 8 # Token索引
+    host: 192.168.2.121  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
   servlet:
   servlet:
     multipart:
     multipart:
       max-request-size: 2048MB
       max-request-size: 2048MB

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

@@ -63,6 +63,22 @@ spring:
           username: root
           username: root
           password: lantone
           password: lantone
 
 
+  #redis
+  redis:
+    database:
+      cache: 8 # cache索引
+      token: 8 # Token索引
+    host: 192.168.2.122  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
   servlet:
   servlet:
     multipart:
     multipart:
       max-request-size: 2048MB
       max-request-size: 2048MB

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

@@ -63,6 +63,22 @@ spring:
           username: root
           username: root
           password: lantone
           password: lantone
 
 
+  #redis
+  redis:
+    database:
+      cache: 8 # cache索引
+      token: 8 # Token索引
+    host: 192.168.2.241  #Redis服务器地址
+    port: 6379 # Redis服务器连接端口(本地环境端口6378,其他环境端口是6379)
+    password: lantone # Redis服务器连接密码(默认为空)
+    lettuce:
+      pool:
+        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
+        max-idle: 5 # 连接池中的最大空闲连接
+        max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
+        min-idle: 0 # 连接池中的最小空闲连接
+    timeout: 20000 # 连接超时时间(毫秒)
+
   servlet:
   servlet:
     multipart:
     multipart:
       max-request-size: 2048MB
       max-request-size: 2048MB