Selaa lähdekoodia

更新redisConfig

wuweihao 3 vuotta sitten
vanhempi
commit
1b1732a07d

+ 1 - 1
gis_admin/src/main/java/com/gis/admin/controller/WxLoginController.java

@@ -113,7 +113,7 @@ public class WxLoginController {
      * 保存用户信息
      */
     private WxUserEntity getWxUser(String openId){
-        WxUserEntity entity = wxUserService.findByOpenId(openId);
+        WxUserEntity entity = wxUserService.cacheByOpenId(openId);
         if (entity == null){
             entity = new WxUserEntity();
             entity.setOpenId(openId);

+ 2 - 0
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 cacheByUserName(String userName);
+
 }

+ 3 - 1
gis_admin/src/main/java/com/gis/admin/service/WxUserService.java

@@ -21,5 +21,7 @@ public interface WxUserService extends IService<WxUserEntity> {
 
     Result checkToken();
 
-    public WxUserEntity cacheWxUserById(Long userId);
+    WxUserEntity cacheWxUserById(Long userId);
+
+    WxUserEntity cacheByOpenId(String openId);
 }

+ 22 - 14
gis_admin/src/main/java/com/gis/admin/service/impl/SysUserServiceImpl.java

@@ -1,6 +1,7 @@
 package com.gis.admin.service.impl;
 
 import cn.hutool.core.util.RandomUtil;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -14,6 +15,7 @@ import com.gis.common.base.entity.po.LogEntity;
 import com.gis.common.base.exception.BaseRuntimeException;
 //import com.gis.common.base.service.LogService;
 //import com.gis.common.base.service.impl.MyBaseServiceImpl;
+import com.gis.common.constant.TypeCode;
 import com.gis.common.util.*;
 import com.gis.admin.entity.dto.PasswordDto;
 import com.gis.admin.entity.dto.UserDto;
@@ -33,6 +35,7 @@ import java.time.LocalDateTime;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 
 /**
@@ -48,6 +51,9 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity
     @Autowired
     HttpServletRequest request;
 
+    @Autowired
+    RedisUtil redisUtil;
+
 
     /**重置密码redis key*/
     final static String RESET_PASSWORD_KEY = "reset:password:";
@@ -59,6 +65,22 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity
     }
 
     @Override
+    public SysUserEntity cacheByUserName(String userName) {
+        String userKey = TypeCode.USER_KEY + userName;
+        SysUserEntity entity;
+        if (redisUtil.hasKey(userKey)){
+            entity = redisUtil.getCacheObject(userKey);
+        } else {
+            entity = findByUserName(userName);
+            redisUtil.setCacheObject(userKey, entity, 1, TimeUnit.HOURS);
+        }
+        return entity;
+    }
+
+
+
+
+    @Override
     public Result saveEntity(UserDto param) {
         SysUserEntity entity ;
         Long id = param.getId();
@@ -135,20 +157,6 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity
     }
 
 
-    private void updatePassword(PasswordDto param) {
-//        SysUserEntity user = this.findByUserName(JwtUtil.getUsername(getToken()));
-//
-//        // 验证原密码
-//        Boolean isBoolean = PasswordUtils.decrypt(user.getPassword(), param.getOldPassword(), PasswordUtils.getStaticSalt());
-//        if (!isBoolean) {
-//            log.error("原始密码错误");
-//            throw new BaseRuntimeException("原始密码错误");
-//        }
-//
-//        user.setPassword(PasswordUtils.encrypt(user.getUserName(), param.getNewPassword(), PasswordUtils.getStaticSalt()));
-//        user.setUpdateTime(LocalDateTime.now());
-//        this.update(user);
-    }
 
     @Override
     public Result updatePwd(PasswordDto param) {

+ 19 - 3
gis_admin/src/main/java/com/gis/admin/service/impl/WxUserServiceImpl.java

@@ -40,7 +40,6 @@ public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUserEntity> i
     IBaseService iBaseService;
 
 
-
     @Override
     public WxUserEntity findByOpenId(String openId) {
         LambdaQueryWrapper<WxUserEntity> wrapper = new LambdaQueryWrapper<>();
@@ -49,6 +48,20 @@ public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUserEntity> i
     }
 
     @Override
+    public WxUserEntity cacheByOpenId(String openId) {
+        String wxUserKey = TypeCode.WX_USER_KEY + openId;
+        WxUserEntity userEntity;
+        if (redisUtil.hasKey(wxUserKey)){
+            userEntity = redisUtil.getCacheObject(wxUserKey);
+        } else {
+            userEntity = this.findByOpenId(openId);
+            // 1小时有效
+            redisUtil.setCacheObject(wxUserKey, userEntity, 1, TimeUnit.HOURS);
+        }
+        return userEntity;
+    }
+
+    @Override
     public Result saveEntity(WxUserDto param) {
         WxUserEntity entity = getById(param.getId());
         BeanUtils.copyProperties(param, entity);
@@ -72,6 +85,8 @@ public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUserEntity> i
         BaseRuntimeException.isTrue(!redisUtil.hasKey(redisWxTokenKey), ErrorEnum.FAILURE_CODE_3004.code(), ErrorEnum.FAILURE_CODE_3004.message());
 
         Long userId = iBaseService.getUserId();
+//        redisUtil.getCacheObject()
+
 
         return Result.success(this.cacheWxUserById(userId));
     }
@@ -81,8 +96,7 @@ public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUserEntity> i
         String wxUserKey = TypeCode.WX_USER_KEY + userId;
         WxUserEntity userEntity;
         if (redisUtil.hasKey(wxUserKey)){
-            JSONObject data = (JSONObject)redisUtil.get(wxUserKey);
-            userEntity = JSON.parseObject(data.toJSONString(), WxUserEntity.class);
+            userEntity = redisUtil.getCacheObject(wxUserKey);
         } else {
             userEntity = this.getById(userId);
             // 1小时有效
@@ -91,4 +105,6 @@ public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUserEntity> i
         return userEntity;
 
     }
+
+
 }

+ 3 - 2
gis_admin/src/main/java/com/gis/admin/shiro/ShiroRealm.java

@@ -112,6 +112,7 @@ public class ShiroRealm extends AuthorizingRealm {
      */
     @Override
     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
+        log.info("run doGetAuthenticationInfo");
         String token = (String) auth.getCredentials();
         if (token == null) {
             throw new JwtAuthenticationException(5001, "header token is null");
@@ -159,7 +160,7 @@ public class ShiroRealm extends AuthorizingRealm {
             throw new JwtAuthenticationException(5001, "token invalid");
         }
 
-        SysUserEntity userEntity = sysUserService.findByUserName(username);
+        SysUserEntity userEntity = sysUserService.cacheByUserName(username);
         if (userEntity == null) {
             log.error("error token userEntity");
             throw new JwtAuthenticationException(5001, "User didn't existed!");
@@ -204,7 +205,7 @@ public class ShiroRealm extends AuthorizingRealm {
             throw new JwtAuthenticationException(5001, "token invalid");
         }
 
-        WxUserEntity wxUserEntity = wxUserService.findByOpenId(wxOpenId);
+        WxUserEntity wxUserEntity = wxUserService.cacheByOpenId(wxOpenId);
         if (wxUserEntity == null) {
             log.error("error token userEntity");
             throw new JwtAuthenticationException(5001, "User didn't existed!");

+ 71 - 0
gis_common/src/main/java/com/gis/common/config/FastJson2JsonRedisSerializer.java

@@ -0,0 +1,71 @@
+package com.gis.common.config;
+
+import com.alibaba.fastjson.JSON;
+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 com.alibaba.fastjson.parser.ParserConfig;
+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);
+    }
+}

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

@@ -1,57 +1,57 @@
-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;
-
-        }
-
-
-}
+//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
gis_common/src/main/java/com/gis/common/config/RedisConfig.java

@@ -0,0 +1,79 @@
+package com.gis.common.config;
+
+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;
+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;
+
+/**
+ * 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);";
+    }
+}

+ 3 - 0
gis_common/src/main/java/com/gis/common/constant/TypeCode.java

@@ -22,6 +22,9 @@ public class TypeCode {
     /**redis wx用户 前缀*/
     public static  final String WX_USER_KEY = "wx:user_";
 
+    /**redis 用户 */
+    public static  final String USER_KEY = "user_";
+
 
 
 

+ 20 - 39
gis_common/src/main/java/com/gis/common/util/RedisUtil.java

@@ -1,6 +1,9 @@
 package com.gis.common.util;
 
 import cn.hutool.extra.spring.SpringUtil;
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import org.apache.poi.ss.formula.functions.T;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.connection.*;
 import org.springframework.data.redis.core.*;
@@ -377,6 +380,22 @@ public class RedisUtil {
     }
 
 
+//    /**
+//     * 获取java对象
+//     *
+//     * @param key
+//     * @return
+//     */
+//    public T getJavaObject(String key, Class<T> clazz) {
+//        JSONObject data =  (JSONObject)get(key);
+//        T t = JSON.parseObject(data.toJSONString(), clazz);
+//        return t;
+//    }
+
+
+
+
+
     /**
      * 返回 key 中字符串值的子字符
      *
@@ -437,45 +456,7 @@ public class RedisUtil {
     }
 
 
-//    /**
-//     * 普通缓存放入并设置时间
-//     *
-//     * @param key   键
-//     * @param value 值
-//     * @param timeout  时间(秒) time要大于0 如果time小于等于0 将设置无限期
-//     * @return true成功 false 失败
-//     */
-//    public boolean setExpire(String key, Object value, long timeout, TimeUnit unit) {
-//        try {
-//            if (timeout > 0) {
-//                redisTemplate.opsForValue().set(key, value, timeout, unit);
-//            } else {
-//                set(key, value);
-//            }
-//            return true;
-//        } catch (Exception e) {
-//            e.printStackTrace();
-//            return false;
-//        }
-//    }
-//
-//    /**
-//     * 普通缓存放入
-//     *
-//     * @param key   键
-//     * @param value 值
-//     * @return true成功 false失败
-//     */
-//    public boolean set(String key, Object value) {
-//        try {
-//            redisTemplate.opsForValue().set(key, value);
-//            return true;
-//        } catch (Exception e) {
-//            e.printStackTrace();
-//            return false;
-//        }
-//
-//    }
+
 
 
     /**

+ 1 - 0
pom.xml

@@ -37,6 +37,7 @@
     <poi.version>3.17</poi.version>
     <zxing.version>3.3.3</zxing.version>
     <lombok.version>1.18.2</lombok.version>
+    <!--<fastjson.version>1.2.79</fastjson.version>-->
     <fastjson.version>1.2.75</fastjson.version>
     <!-- 3.7 接入微信版本过低,需要升级到3.8; 微信自带此包-->
     <!--<lang3.version>3.7</lang3.version>-->