13693261870
13 小时以前 80247f1b5e00fab2ce6c9e8474cfeceefb902d95
解决Redis键乱码
已重命名2个文件
已添加2个文件
已修改8个文件
302 ■■■■ 文件已修改
se-common/pom.xml 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/aspect/LogAspect.java 18 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/config/RedisConfig.java 27 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/config/WebConfig.java 125 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/entity/all/FastJson2JsonRedisSerializer.java 44 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/entity/lf/TokenPo.java 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/entity/lf/UserPo.java 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/interceptor/AuthInterceptor.java 40 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/mapper/CommonMapper.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/java/com/terra/common/service/CommonService.java 10 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-system/src/main/java/com/terra/system/config/WebConfig.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/pom.xml
@@ -35,6 +35,12 @@
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2-extension-spring5</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <!--servlet-->
se-common/src/main/java/com/terra/common/aspect/LogAspect.java
@@ -2,9 +2,10 @@
import com.terra.common.annotation.SysLog;
import com.terra.common.entity.lf.OperatePo;
import com.terra.common.service.TokenHelper;
import com.terra.common.entity.lf.UserPo;
import com.terra.common.service.CommonService;
import com.terra.common.helper.WebHelper;
import com.terra.common.mapper.OperatePoMapper;
import com.terra.common.mapper.CommonMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -27,7 +28,10 @@
@Component
public class LogAspect {
    @Resource
    OperatePoMapper operatePoMapper;
    CommonMapper commonMapper;
    @Resource
    CommonService commonService;
    private final static String SELECT = "select";
@@ -85,7 +89,11 @@
            po.setUrl(req.getServletPath());
            po.setIp(WebHelper.getIpAddress(req));
            po.setExec(time);
            po.setUserid(TokenHelper.getCurrentUserId(req));
            UserPo user = commonService.getCurrentUser(req);
            if (null != user) {
                po.setUserid(user.getId());
            }
            // è®¾ç½®æ¨¡å—
            Tag tag = clazz.getAnnotation(Tag.class);
@@ -105,7 +113,7 @@
                po.setBak(sysLog.value());
            }
            operatePoMapper.insert(po);
            commonMapper.insert(po);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
se-common/src/main/java/com/terra/common/config/RedisConfig.java
@@ -3,7 +3,9 @@
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.terra.common.entity.all.FastJson2JsonRedisSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
@@ -23,31 +25,24 @@
 * @author WWW
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
@SuppressWarnings("ALL")
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * é…ç½®è‡ªå®šä¹‰redisTemplate
     */
    @SuppressWarnings("deprecation")
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setConnectionFactory(factory);
        // ä½¿ç”¨Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        //Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        //template.setValueSerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
se-common/src/main/java/com/terra/common/config/WebConfig.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,125 @@
package com.terra.common.config;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import com.terra.common.interceptor.AuthInterceptor;
import com.terra.common.service.CommonService;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
/**
 * WebConfig:通过实现该接口并重写方法来‌扩展‌Spring MVC配置,不会覆盖默认配置。
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Resource
    CommonService commonService;
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // è®¾ç½®è®¿é—®è·¯å¾„为 â€œ/” è·³è½¬åˆ°æŒ‡å®šé¡µé¢
        registry.addViewController("/").setViewName("redirect:/sign/toIndex");
        // è®¾ç½®ä¸ºæœ€é«˜ä¼˜å…ˆçº§
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }
    /**
     * èŽ·å–æ‹¦æˆªå™¨å¯¹è±¡
     */
    public AuthInterceptor getAuthBean() {
        return new AuthInterceptor(commonService);
    }
    /**
     * swagger控制
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        //registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/druid/**").addResourceLocations("classpath:/META-INF/resources/druid/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }
    /**
     * å¿½ç•¥url地址大小写
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher matcher = new AntPathMatcher();
        matcher.setCaseSensitive(false);
        configurer.setPathMatcher(matcher);
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getAuthBean())
                //.excludePathPatterns("/v3/api-docs")
                .addPathPatterns("/**");
    }
    /**
     * å¤„理json格式,值null的转换为""
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter() {
            @Override
            protected void writeInternal(Object object, org.springframework.http.HttpOutputMessage outputMessage)
                    throws IOException, org.springframework.http.converter.HttpMessageNotWritableException {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    String requestURI = attributes.getRequest().getRequestURI();
                    if ("/v3/api-docs".equals(requestURI)) { // æŽ’除 /v3/api-docs è·¯å¾„
                        // ä½¿ç”¨é»˜è®¤çš„ JSON åºåˆ—化(如 Jackson),这里需要手动处理,不能直接调用 super.writeInternal
                        outputMessage.getBody().write(String.valueOf(object).getBytes());
                        return;
                    }
                }
                super.writeInternal(object, outputMessage); // å…¶ä»–路径使用 Fastjson2 å¤„理
            }
        };
        converter.setFastJsonConfig(getFastJsonConfig());
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setSupportedMediaTypes(Collections.singletonList(
                MediaType.APPLICATION_JSON
        ));
        converters.add(0, converter);
    }
    private static FastJsonConfig getFastJsonConfig() {
        FastJsonConfig config = new FastJsonConfig();
        // é…ç½®åºåˆ—化特征
        config.setWriterFeatures(
                JSONWriter.Feature.WriteNullListAsEmpty,
                //JSONWriter.Feature.WriteNullBooleanAsFalse,
                //JSONWriter.Feature.WriteNullNumberAsZero,
                //JSONWriter.Feature.PrettyFormat, // æ ¼å¼åŒ–输出
                JSONWriter.Feature.WriteMapNullValue // è¾“出空字段
        );
        // ååºåˆ—化特性配置
        config.setReaderFeatures(
                JSONReader.Feature.FieldBased,
                JSONReader.Feature.SupportArrayToBean
        );
        return config;
    }
}
se-common/src/main/java/com/terra/common/entity/all/FastJson2JsonRedisSerializer.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,44 @@
package com.terra.common.entity.all;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
    public static final String[] JSON_WHITELIST_STR = { "org.springframework", "com.terra" };
    static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(JSON_WHITELIST_STR);
    private final Class<T> clazz;
    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, JSONWriter.Feature.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, AUTO_TYPE_FILTER);
    }
}
se-common/src/main/java/com/terra/common/entity/lf/TokenPo.java
@@ -6,6 +6,7 @@
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.sql.Timestamp;
/**
@@ -17,7 +18,9 @@
@AllArgsConstructor
@TableName("lf.sys_token")
@EqualsAndHashCode(callSuper = false)
public class TokenPo {
public class TokenPo implements Serializable {
    private static final long serialVersionUID = 4743559455078257191L;
    private Integer id;
    private String uname;
se-common/src/main/java/com/terra/common/entity/lf/UserPo.java
@@ -6,6 +6,7 @@
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.sql.Timestamp;
/**
@@ -17,7 +18,9 @@
@AllArgsConstructor
@TableName("lf.sys_user")
@EqualsAndHashCode(callSuper = false)
public class UserPo {
public class UserPo implements Serializable {
    private static final long serialVersionUID = 2246505129003195572L;
    private Integer id;
    private Integer depid;
se-common/src/main/java/com/terra/common/interceptor/AuthInterceptor.java
@@ -7,12 +7,14 @@
import com.terra.common.entity.lf.UserPo;
import com.terra.common.helper.StringHelper;
import com.terra.common.helper.WebHelper;
import com.terra.common.service.CommonService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@@ -23,6 +25,8 @@
 */
@Configuration
public class AuthInterceptor implements HandlerInterceptor {
    private CommonService commonService;
    private static final Log log = LogFactory.getLog(AuthInterceptor.class);
    private static final String NO_TOKEN = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.TOKEN_ERROR, "找不到令牌"));
@@ -39,9 +43,9 @@
    private static final String ILLEGAL_TOKEN = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.UNAUTHORIZED, "令牌来源非法"));
    //public AuthInterceptor(SysService sysService) {
    //    this.sysService = sysService;
    //}
    public AuthInterceptor(CommonService commonService) {
        this.commonService = commonService;
    }
    /**
     * Controller执行之前执行,如果返回值是true则代表放行,返回false则拦截
@@ -62,8 +66,8 @@
            }
            // 3.获取用户令牌
            UserPo ue = new UserPo(); //sysService.tokenService.getUserByToken(token);
            if (ue == null) {
            UserPo ue = commonService.getUserByToken(token); //new UserPo(); //sysService.tokenService.getUserByToken(token);
            if (null == ue) {
                return WebHelper.writeStr2Page(response, NO_LOGIN);
            }
@@ -126,19 +130,21 @@
     * æ£€æŸ¥æƒé™
     */
    private boolean checkPerms(UserPo ue, HttpServletRequest request) {
        List<String> list = null; //sysService.permsService.selectPerms(ue.getUid());
        if (list == null || list.size() == 0) {
            return false;
        }
        return true;
        String url = request.getRequestURI();
        for (String perm : list) {
            if (url.contains(perm)) {
                return true;
            }
        }
        return false;
//        List<String> list = null; //sysService.permsService.selectPerms(ue.getUid());
//        if (list == null || list.size() == 0) {
//            return false;
//        }
//
//        String url = request.getRequestURI();
//        for (String perm : list) {
//            if (url.contains(perm)) {
//                return true;
//            }
//        }
//
//        return false;
    }
    /**
se-common/src/main/java/com/terra/common/mapper/CommonMapper.java
ÎļþÃû´Ó se-common/src/main/java/com/terra/common/mapper/OperatePoMapper.java ÐÞ¸Ä
@@ -13,7 +13,7 @@
@Mapper
@Repository
public interface OperatePoMapper extends BaseMapper<OperatePo> {
public interface CommonMapper extends BaseMapper<OperatePo> {
    @Insert("INSERT INTO lf.sys_operate(url, ip, exec, clazz, type, userid, bak, modular1, modular2) VALUES (#{url}, #{ip}, #{exec}, #{clazz}, #{type}, #{userid}, #{bak}, #{modular1}, #{modular2})")
    int insertOperate(Map<String, Object> map);
se-common/src/main/java/com/terra/common/service/CommonService.java
ÎļþÃû´Ó se-common/src/main/java/com/terra/common/service/TokenHelper.java ÐÞ¸Ä
@@ -5,7 +5,7 @@
import com.terra.common.entity.lf.UserPo;
import com.terra.common.helper.StringHelper;
import com.terra.common.helper.WebHelper;
import com.terra.common.mapper.OperatePoMapper;
import com.terra.common.mapper.CommonMapper;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@@ -17,17 +17,17 @@
 * @author WWW
 */
@Component
public class TokenHelper {
public class CommonService {
    @Resource
    RedisService redisService;
    @Resource
    OperatePoMapper mapper;
    CommonMapper mapper;
    public static Integer getCurrentUserId(HttpServletRequest req) {
    public UserPo getCurrentUser(HttpServletRequest req) {
        String token = WebHelper.getToken(req);
        return null;
        return getUserByToken(token);
    }
    public UserPo getUserByToken(String token) {
se-common/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -1,3 +1,12 @@
# æœåŠ¡
com.terra.common.service.RedisService
com.terra.common.service.CommonService
# åˆ‡é¢
com.terra.common.aspect.LogAspect
# æ‹¦æˆªå™¨
com.terra.common.interceptor.AuthInterceptor
# é…ç½®
com.terra.common.config.SpringDocAutoConfiguration
com.terra.common.config.MybatisPlusConfig
com.terra.common.aspect.LogAspect
com.terra.common.config.RedisConfig
com.terra.common.config.WebConfig
se-system/src/main/java/com/terra/system/config/WebConfig.java
@@ -4,7 +4,8 @@
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson2.JSON;
import com.terra.system.interceptor.AuthInterceptor;
import com.terra.common.interceptor.AuthInterceptor;
import com.terra.common.service.CommonService;
import com.terra.system.service.all.SysService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -29,10 +30,10 @@
 * Web配置类
 * @author WWW
 */
@Configuration
//@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Resource
    private SysService sysService;
    CommonService commonService;
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
@@ -48,7 +49,7 @@
     * @return
     */
    public AuthInterceptor getAuthBean() {
        return new AuthInterceptor(sysService);
        return new AuthInterceptor(commonService);
    }
    /**