Java:SpringBoot整合Hashids,实现数据ID加密隐藏

引入依赖

xml 复制代码
<dependency>
    <groupId>org.hashids</groupId>
    <artifactId>hashids</artifactId>
    <version>1.0.3</version>
</dependency>

步骤

1、自定义注解

java 复制代码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface JsonHashId {
}

1、定义序列化

java 复制代码
public class HashIdLongSerializer extends JsonSerializer<Long> implements ContextualSerializer {

    @Override
    public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(HashIdUtil.encoded(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider provider, BeanProperty property) throws JsonMappingException {
        JsonHashId annotation = property.getAnnotation(JsonHashId.class);

        if (annotation != null) {
            return this;
        } else{
            return new NumberSerializers.LongSerializer(Long.class);
        }
    }
}

3、定义反序列化

java 复制代码
public class HashIdLongDeserializer extends JsonDeserializer<Long> implements ContextualDeserializer {
    @Override
    public Long deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JacksonException {
        String value = jsonparser.getText();
        return HashIdUtil.decode(value);
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException {
        JsonHashId annotation = property.getAnnotation(JsonHashId.class);

        if (annotation != null) {
            return this;
        } else {
            return new NumberDeserializers.LongDeserializer(Long.class, null);
        }
    }
}

4、添加自定义序列化器和反序列化器

java 复制代码
public class JacksonObjectMapper extends ObjectMapper {

    public JacksonObjectMapper() {
        super();
        // 收到未知属性时不报异常
        this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 反序列化时,属性不存在的兼容处理
        this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        module..addDeserializer(Long.class, new HashIdLongDeserializer())
            .addSerializer(Long.class, new HashIdLongSerializer());

        // 注册功能模块 添加自定义序列化器和反序列化器
        this.registerModule(module);
    }
}

5、配置消息转换器

java 复制代码
/**
 * 配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 扩展消息转换器
     *
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 设置对象转换器
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 添加到mvc框架消息转换器中,优先使用自定义转换器
        converters.add(0, messageConverter);
    }
}

6、hashids工具类

java 复制代码
package com.springboot.api.util;

import org.hashids.Hashids;

/**
 * hashid
 */
public class HashIdUtil {

    public static Hashids getHashids() {
        return new Hashids("hashid", 8);
    }

    /**
     * 加密
     */
    public static String encoded(Long id) {
        Hashids hashids = getHashids();
        return hashids.encode(id);
    }

    /**
     * 解密
     */
    public static long decode(String uid) {
        Hashids hashids = getHashids();
        return hashids.decode(uid)[0];
    }
}

测试输出

复制代码
userId: 1,

加密后
"userId": "ZxWD0W68",

方式二

定义转换器,将序列化器和反序列化器写在一起

java 复制代码
public class HashIdConverter {

    public static class HashIdLongDeserializer extends JsonDeserializer<Long> {
        @Override
        public Long deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException, JacksonException {
            return HashIdUtil.decode(jsonparser.getText());
        }
    }


    public static class HashIdLongSerializer extends JsonSerializer<Long> {

        @Override
        public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(HashIdUtil.encoded(value));
        }
    }
}

配置内省器

java 复制代码
public class HashIdFieldAnnotationIntrospector extends NopAnnotationIntrospector {
    @Override
    public Object findSerializer(Annotated annotated) {
        TableId annotation = annotated.getAnnotation(TableId.class);
        if(annotation != null){
            return HashIdConverter.HashIdLongSerializer.class;
        } else{
            return super.findSerializer(annotated);
        }
    }

    @Override
    public Object findDeserializer(Annotated annotated) {
        TableId annotation = annotated.getAnnotation(TableId.class);
        if(annotation != null){
            return HashIdConverter.HashIdLongDeserializer.class;
        } else{
            return super.findDeserializer(annotated);
        }
    }
}

配置

java 复制代码
public class JacksonObjectMapper extends ObjectMapper {

 
    public JacksonObjectMapper() {
        super();

        // 将自定义注解內省器加入到Jackson注解内省器集合里,AnnotationIntrospector是双向链表结构
        AnnotationIntrospector annotationIntrospector = this.getSerializationConfig().getAnnotationIntrospector();
        AnnotationIntrospector pair = AnnotationIntrospectorPair.pair(annotationIntrospector, new HashIdFieldAnnotationIntrospector());
        this.setAnnotationIntrospector(pair);

    }
}

参考
SpringBoot中Jackson序列化处理自定义注解

相关推荐
ruleslol6 分钟前
SpringBoot13-小细节
spring boot·mybatis
掘金者阿豪11 分钟前
金仓数据库KingbaseES与MyBatis-Plus整合实践:电商系统开发实战
java·后端
csbysj202022 分钟前
XSLT Apply:深入解析XSLT在XML转换中的应用
开发语言
不会kao代码的小王39 分钟前
突破机房围墙:openEuler设备的公网管理实战指南
开发语言·数据库·笔记
CodeCraft Studio41 分钟前
CAD文件处理控件Aspose.CAD教程:在 Python 中将 SVG 转换为 PDF
开发语言·python·pdf·svg·cad·aspose·aspose.cad
不会写代码的加加41 分钟前
告别重构噩梦:基于 Oinone 实现单体到微服务的平滑演进
spring boot·分布式
消失的旧时光-19431 小时前
人脸跟随 ( Channel 实现(缓存5条数据 + 2度过滤 + 平滑移动))
android·java·开发语言·kotlin
默默coding的程序猿1 小时前
1.单例模式有哪几种常见的实现方式?
java·开发语言·spring boot·spring·单例模式·设计模式·idea
编程岁月1 小时前
java面试-0136-BIO、NIO、AIO区别?
java·面试·nio
春生野草1 小时前
部署项目到Tomcat
java·tomcat