소스 검색

更改redis config 内存升回3G

wuweihao 3 년 전
부모
커밋
ad62cb3113

+ 2 - 2
720yun_local_manage/gis_admin/src/main/java/com/gis/admin/controller/LoginController.java

@@ -117,7 +117,7 @@ public class LoginController {
         // 保存操作日志
         saveLog(userId);
 
-        redisUtil.set(configConstant.redisPrefix + token, token, 86400);
+        redisUtil.setEx(configConstant.redisPrefix + token, token, 23, TimeUnit.HOURS);
 
 
         return Result.success(result);
@@ -131,7 +131,7 @@ public class LoginController {
         if (StringUtils.isBlank(token)) {
             log.info("token is null");
         }
-        redisUtil.del(configConstant.redisPrefix + token);
+        redisUtil.delete(configConstant.redisPrefix + token);
         return Result.success();
     }
 

+ 2 - 0
720yun_local_manage/gis_admin/src/main/java/com/gis/admin/service/SysUserService.java

@@ -39,4 +39,6 @@ public interface SysUserService extends IService<SysUserEntity> {
 
     Result retrievePassword(ResetPasswordDto param);
 
+    SysUserEntity cacheById(Long userId);
+
 }

+ 20 - 0
720yun_local_manage/gis_admin/src/main/java/com/gis/admin/service/impl/SysUserServiceImpl.java

@@ -33,6 +33,7 @@ import java.time.LocalDateTime;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 
 /**
@@ -48,10 +49,16 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity
     @Autowired
     HttpServletRequest request;
 
+    @Autowired
+    RedisUtil redisUtil;
+
 
     /**重置密码redis key*/
     final static String RESET_PASSWORD_KEY = "reset:password:";
 
+    /**redis 用户名*/
+    final static String USER_KEY = "user:";
+
 
     @Override
     public SysUserEntity findByUserName(String userName) {
@@ -88,6 +95,19 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity
     }
 
     @Override
+    public SysUserEntity cacheById(Long userId) {
+        SysUserEntity entity;
+        String userKey = USER_KEY + userId;
+        if (redisUtil.hasKey(userKey)){
+            entity =  redisUtil.getCacheObject(userKey);
+        } else {
+            entity = this.getById(userId);
+            redisUtil.setCacheObject(userKey, entity, 5, TimeUnit.MINUTES);
+        }
+        return entity;
+    }
+
+    @Override
     public Result removes(String ids) {
         List<String> idList = Arrays.asList(ids);
         List<SysUserEntity> entityList = this.listByIds(idList);

+ 3 - 18
720yun_local_manage/gis_admin/src/main/java/com/gis/admin/shiro/ShiroRealm.java

@@ -4,7 +4,6 @@ import cn.hutool.core.collection.CollectionUtil;
 import com.gis.common.constant.ConfigConstant;
 import com.gis.common.util.JwtUtil;
 import com.gis.admin.entity.po.SysUserEntity;
-import com.gis.admin.service.SysResourceService;
 import com.gis.admin.service.SysUserService;
 import com.gis.common.util.RedisUtil;
 import lombok.extern.slf4j.Slf4j;
@@ -18,14 +17,12 @@ import org.apache.shiro.authz.SimpleAuthorizationInfo;
 import org.apache.shiro.realm.AuthorizingRealm;
 import org.apache.shiro.subject.PrincipalCollection;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
 
 /**
  * @Description: 用户登录鉴权和获取用户授权
@@ -36,25 +33,13 @@ import java.util.Set;
 @Component
 @Slf4j
 public class ShiroRealm extends AuthorizingRealm {
-//	@Lazy
-//    @Resource
-//    private CommonAPI commonAPI;
-
-//    @Lazy
-//    @Resource
-//    private RedisUtil redisUtil;
 
     @Resource
     HttpServletRequest request;
 
-//    @Autowired
-//    SysResourceService sysResourceService;
-
     @Autowired
     SysUserService sysUserService;
 
-//    @Autowired
-//    RedisTemplate<String, String> redisTemplate;
 
     @Autowired
     ConfigConstant configConstant;
@@ -88,7 +73,6 @@ public class ShiroRealm extends AuthorizingRealm {
         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
 
         String token = request.getHeader("token");
-//        log.info("token: {}", token);
         if (StringUtils.isNotBlank(token)){
             List userRole = JwtUtil.getUserRole(token);
 //            userId = JwtUtil.getUserId(token);
@@ -142,7 +126,7 @@ public class ShiroRealm extends AuthorizingRealm {
         }
 
 //        String redisToken = redisTemplate.opsForValue().get(configConstant.redisPrefix + token);
-        String redisToken = (String)redisUtil.get(configConstant.redisPrefix + token);
+        String redisToken = redisUtil.getCacheObject(configConstant.redisPrefix + token);
 
         if (!token.equals(redisToken)) {
             log.error("redis token is null");
@@ -155,7 +139,8 @@ public class ShiroRealm extends AuthorizingRealm {
             throw new JwtAuthenticationException(5001, "token invalid");
         }
 
-        SysUserEntity userEntity = sysUserService.findByUserName(username);
+//        SysUserEntity userEntity = sysUserService.findByUserName(username);
+        SysUserEntity userEntity = sysUserService.cacheById(JwtUtil.getUserId(token));
         if (userEntity == null) {
             log.error("error token userEntity");
             throw new JwtAuthenticationException(5001, "User didn't existed!");

+ 72 - 0
720yun_local_manage/gis_common/src/main/java/com/gis/common/config/FastJson2JsonRedisSerializer.java

@@ -0,0 +1,72 @@
+package com.gis.common.config;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.ParserConfig;
+import com.alibaba.fastjson.serializer.SerializerFeature;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import org.springframework.data.redis.serializer.RedisSerializer;
+import org.springframework.data.redis.serializer.SerializationException;
+import org.springframework.util.Assert;
+
+import java.nio.charset.Charset;
+
+/**
+ * Redis使用FastJson序列化
+ * 
+ * @author fdkk
+ */
+public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
+{
+    @SuppressWarnings("unused")
+    private ObjectMapper objectMapper = new ObjectMapper();
+
+    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
+
+    private Class<T> clazz;
+
+    static
+    {
+        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
+    }
+
+    public FastJson2JsonRedisSerializer(Class<T> clazz)
+    {
+        super();
+        this.clazz = clazz;
+    }
+
+    @Override
+    public byte[] serialize(T t) throws SerializationException
+    {
+        if (t == null)
+        {
+            return new byte[0];
+        }
+        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
+    }
+
+    @Override
+    public T deserialize(byte[] bytes) throws SerializationException
+    {
+        if (bytes == null || bytes.length <= 0)
+        {
+            return null;
+        }
+        String str = new String(bytes, DEFAULT_CHARSET);
+
+        return JSON.parseObject(str, clazz);
+    }
+
+    public void setObjectMapper(ObjectMapper objectMapper)
+    {
+        Assert.notNull(objectMapper, "'objectMapper' must not be null");
+        this.objectMapper = objectMapper;
+    }
+
+    protected JavaType getJavaType(Class<?> clazz)
+    {
+        return TypeFactory.defaultInstance().constructType(clazz);
+    }
+}

+ 0 - 57
720yun_local_manage/gis_common/src/main/java/com/gis/common/config/MyRedisConfig.java

@@ -1,57 +0,0 @@
-package com.gis.common.config;
-
-import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
-import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.redis.connection.RedisConnectionFactory;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
-import org.springframework.data.redis.serializer.StringRedisSerializer;
-
-import java.net.UnknownHostException;
-
-/**
- * Created by owen on 2021/7/16 0016 17:21
- *
- * redis 全局序列化
- * redis管理界面可以看到参数
- * 对象序列化有字段泛型字段值不丢失
- */
-
-@Configuration
-public class MyRedisConfig {
-
-
-
-        @Bean
-        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
-            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
-            redisTemplate.setConnectionFactory(connectionFactory);
-
-            // 使用Jackson2JsonRedisSerialize替换默认序列化
-            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
-
-            ObjectMapper objectMapper = new ObjectMapper();
-            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
-            objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
-
-            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
-
-            // 设置key和value的序列化规则
-            redisTemplate.setKeySerializer(new StringRedisSerializer());
-//            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
-            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
-            redisTemplate.setHashValueSerializer(new StringRedisSerializer());
-            redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
-
-            redisTemplate.afterPropertiesSet();
-
-            return redisTemplate;
-
-        }
-
-
-}

+ 79 - 0
720yun_local_manage/gis_common/src/main/java/com/gis/common/config/RedisConfig.java

@@ -0,0 +1,79 @@
+package com.gis.common.config;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
+import org.springframework.cache.annotation.CachingConfigurerSupport;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.script.DefaultRedisScript;
+import org.springframework.data.redis.serializer.StringRedisSerializer;
+
+/**
+ * redis配置
+ * 
+ * @author fdkk
+ */
+@Configuration
+@EnableCaching
+public class RedisConfig extends CachingConfigurerSupport
+{
+    @Bean
+    @SuppressWarnings(value = { "unchecked", "rawtypes" })
+    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
+    {
+        RedisTemplate<Object, Object> template = new RedisTemplate<>();
+        template.setConnectionFactory(connectionFactory);
+
+        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
+
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
+        serializer.setObjectMapper(mapper);
+
+        // 使用StringRedisSerializer来序列化和反序列化redis的key值
+        template.setKeySerializer(new StringRedisSerializer());
+        template.setValueSerializer(serializer);
+
+        // Hash的key也采用StringRedisSerializer的序列化方式
+        template.setHashKeySerializer(new StringRedisSerializer());
+        template.setHashValueSerializer(serializer);
+
+        template.afterPropertiesSet();
+        return template;
+    }
+
+    @Bean
+    public DefaultRedisScript<Long> limitScript()
+    {
+        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
+        redisScript.setScriptText(limitScriptText());
+        redisScript.setResultType(Long.class);
+        return redisScript;
+    }
+
+    /**
+     * 限流脚本
+     */
+    private String limitScriptText()
+    {
+        return "local key = KEYS[1]\n" +
+                "local count = tonumber(ARGV[1])\n" +
+                "local time = tonumber(ARGV[2])\n" +
+                "local current = redis.call('get', key);\n" +
+                "if current and tonumber(current) > count then\n" +
+                "    return tonumber(current);\n" +
+                "end\n" +
+                "current = redis.call('incr', key)\n" +
+                "if tonumber(current) == 1 then\n" +
+                "    redis.call('expire', key, time)\n" +
+                "end\n" +
+                "return tonumber(current);";
+    }
+}

파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 0 - 1187
720yun_local_manage/gis_common/src/main/java/com/gis/common/util/RedisCache.java


파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
+ 1123 - 109
720yun_local_manage/gis_common/src/main/java/com/gis/common/util/RedisUtil.java


+ 4 - 4
720yun_local_manage/gis_pano/src/main/java/com/gis/cms/service/impl/WorkServiceImpl.java

@@ -133,7 +133,7 @@ public class WorkServiceImpl extends ServiceImpl<WorkMapper, WorkEntity> impleme
             String now = LocalDate.now().minusMonths(1).toString();
             log.warn("执行删除: {} 月份之前的空作品数据", now);
             entityMapper.delByTime(now);
-            redisUtil.set(RedisConstant.WORK_DEL, now, 30, TimeUnit.DAYS);
+            redisUtil.setEx(RedisConstant.WORK_DEL, now, 30, TimeUnit.DAYS);
         }
     }
 
@@ -147,7 +147,7 @@ public class WorkServiceImpl extends ServiceImpl<WorkMapper, WorkEntity> impleme
         this.removeById(id);
 
         // 删除redis
-        redisUtil.del(RedisConstant.WORK_ID + id);
+        redisUtil.delete(RedisConstant.WORK_ID + id);
 
         // 删除无效作品数据
         delByTime();
@@ -191,7 +191,7 @@ public class WorkServiceImpl extends ServiceImpl<WorkMapper, WorkEntity> impleme
         log.info("userId: {}", userId);
         BaseRuntimeException.isHas(!userId.equals(entity.getCreatorId()), null, "当前无操作权限");
 
-        redisUtil.set(RedisConstant.WORK_ID + workId, entity, 30, TimeUnit.SECONDS);
+        redisUtil.setCacheObject(RedisConstant.WORK_ID + workId, entity, 30, TimeUnit.SECONDS);
 
         return Result.success();
 
@@ -210,7 +210,7 @@ public class WorkServiceImpl extends ServiceImpl<WorkMapper, WorkEntity> impleme
         }
 
         // 3秒内防止重复提交
-        redisUtil.set(editKey, param.toString(), 3, TimeUnit.SECONDS);
+        redisUtil.setEx(editKey, param.toString(), 3, TimeUnit.SECONDS);
 
         WorkEntity entity = getById(id);
         if (entity == null) {

+ 2 - 2
startJar.sh

@@ -49,7 +49,7 @@ start(){
     if [ $? -eq "0" ]; then    # [$? -eq "0"] 说明pid不等于空 说明服务正在运行中,将进程号打印出来
         echo "${APP_NAME} running. pid=${pid}"
     else
-        nohup java -jar -Xmx2048M -Xms512M ./$APP_NAME --spring.profiles.active=$1 --server.port=$APP_PORT > logs.log 2>error.log &  # 说明pid为空
+        nohup java -jar -Xmx3096M -Xms512M ./$APP_NAME --spring.profiles.active=$1 --server.port=$APP_PORT > logs.log 2>error.log &  # 说明pid为空
         # 执行java -jar 命令启动服务
         echo "${APP_NAME} started启动"
     fi
@@ -97,7 +97,7 @@ restart(){
         if [ $? -eq "0" ]; then    # [$? -eq "0"] 说明pid不等于空 说明服务正在运行中,将进程号打印出来
             echo "${APP_NAME} running. pid=${pid}"
         else
-            nohup java -jar -Xmx2048M -Xms512M ./$APP_NAME --spring.profiles.active=$1 --server.port=$APP_PORT > logs.log 2>error.log &  # 说明pid为空
+            nohup java -jar -Xmx3096M -Xms512M ./$APP_NAME --spring.profiles.active=$1 --server.port=$APP_PORT > logs.log 2>error.log &  # 说明pid为空
             echo "${APP_NAME} started启动"
         fi
 }