Elegantly solve the problem of data inconsistency caused by the return of the Long type in the background and the loss of the foreground accuracy

Environment: SpringBoot 2.x

The problem is: JavaScript does not support the Long type returned in the background . The value range of JavaScript's number type is -2^53~2^53 (not including the boundary). Therefore, for numbers greater than 9007199254740991, there will be accuracy problems in the conversion of the hexadecimal system, and the snowflake ID The generated value is too large, causing JavaScript to fail to store normally.

[Note] It is recommended that snowflake IDs be stored in the database using bigint instead of varchar; this can increase the speed of such a database, and reduce the operation of converting strings into numbers when using indexes.

Solution: Write a JSON configuration class to automatically convert the Long type to String type when serializing it to JSON.

@Configuration
public class JacksonConfiguration {

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            // Long 会自定转换成 String
            builder.serializerByType(Long.class, ToStringSerializer.instance);
        };
    }
}

【recommend】

1.  Elegantly solve the problem of SpringBoot's LocalDateTime (de)serialization in JDK8

Guess you like

Origin blog.csdn.net/peng2hui1314/article/details/104610819