优化:基于阿里巴巴 Java 开发手册(黄山版)优化 Jackson 超大整数配置

1.编程规约>前后端规约>第6条:
【强制】对于需要使用超大整数的场景,服务端一律使用 String 字符串类型返回,禁止使用 Long 类型。
说明:Java 服务端如果直接返回 Long 整型数据给前端,Javascript 会自动转换为 Number 类型(注:此类型为双精度浮点数,表示原理与取值范围等同于 Java 中的 Double)。Long 类型能表示的最大值是 263-1,在取值范围之内,超过 253(9007199254740992)的数值转化为Javascript 的 Number 时,有些数值会产生精度损失。
扩展说明,在 Long 取值范围内,任何 2 的指数次的整数都是绝对不会存在精度损失的,所以说精度损失是一个概率问题。若浮点数尾数位与指数位空间不限,则可以精确表示任何整数,但很不幸,双精度浮点数的尾数位只有 52 位。
反例:通常在订单号或交易号大于等于 16 位,大概率会出现前后端订单数据不一致的情况。比如,后端传输的 "orderId":362909601374617692,前端拿到的值却是:362909601374617660
This commit is contained in:
Charles7c 2023-03-05 19:31:02 +08:00
parent 95784e5c7d
commit 8823211fd9
14 changed files with 57 additions and 112 deletions

View File

@ -1,55 +0,0 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.cnadmin.common.config.jackson;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
/**
* 大数值序列化器针对数值超出 JS 最大或最小值的情况将其转换为字符串
*
* @author Charles7c
* @since 2022/12/11 13:22
*/
@JacksonStdImpl
public class BigNumberSerializer extends NumberSerializer {
/** 静态实例 */
public static final BigNumberSerializer SERIALIZER_INSTANCE = new BigNumberSerializer(Number.class);
/** JSNumber.MAX_SAFE_INTEGER */
private static final long MAX_SAFE_INTEGER = 9007199254740991L;
/** JSNumber.MIN_SAFE_INTEGER */
private static final long MIN_SAFE_INTEGER = -9007199254740991L;
public BigNumberSerializer(Class<? extends Number> rawType) {
super(rawType);
}
@Override
public void serialize(Number value, JsonGenerator generator, SerializerProvider provider) throws IOException {
// 序列化为字符串
if (value.longValue() > MIN_SAFE_INTEGER && value.longValue() < MAX_SAFE_INTEGER) {
super.serialize(value, generator, provider);
} else {
generator.writeString(value.toString());
}
}
}

View File

@ -61,11 +61,11 @@ public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
// 针对数值类型LongBigIntegerBigDecimal 的序列化和反序列化
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(Long.class, BigNumberSerializer.SERIALIZER_INSTANCE);
javaTimeModule.addSerializer(Long.TYPE, BigNumberSerializer.SERIALIZER_INSTANCE);
javaTimeModule.addSerializer(BigInteger.class, BigNumberSerializer.SERIALIZER_INSTANCE);
// 针对数值类型LongBigIntegerBigDecimal 的序列化
javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance);
javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
javaTimeModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
javaTimeModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
// 针对时间类型LocalDateTimeLocalDateLocalTime 的序列化和反序列化
@ -80,9 +80,9 @@ public class JacksonConfiguration {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(StringConsts.NORM_TIME_PATTERN);
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(timeFormatter));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(timeFormatter));
builder.modules(javaTimeModule);
builder.timeZone(TimeZone.getDefault());
log.info(">>>初始化 Jackson 配置<<<");
builder.modules(javaTimeModule);
log.info(">>>初始化 Jackson 序列化配置<<<");
};
}

View File

@ -4,7 +4,7 @@ import qs from 'query-string';
const BASE_URL = '/monitor/log';
export interface LogRecord {
logId?: number;
logId?: string;
clientIp: string;
location: string;
browser: string;
@ -65,7 +65,7 @@ export interface OperationLogParam extends Partial<OperationLogRecord> {
page: number;
size: number;
sort: Array<string>;
uid?: number;
uid?: string;
}
export interface OperationLogListRes {
@ -102,6 +102,6 @@ export function listSystemLog(params: SystemLogParam) {
});
}
export function getSystemLog(logId: number) {
return axios.get<SystemLogDetailRecord>(`${BASE_URL}/system/${logId}`);
export function getSystemLog(id: string) {
return axios.get<SystemLogDetailRecord>(`${BASE_URL}/system/${id}`);
}

View File

@ -4,9 +4,9 @@ import qs from 'query-string';
const BASE_URL = '/system/dept';
export interface DeptRecord {
deptId?: number;
deptId?: string;
deptName: string;
parentId?: number;
parentId?: string;
description?: string;
deptSort: number;
status?: number;
@ -32,7 +32,7 @@ export function listDept(params: DeptParam) {
});
}
export function getDept(id: number) {
export function getDept(id: string) {
return axios.get<DeptRecord>(`${BASE_URL}/${id}`);
}
@ -44,6 +44,6 @@ export function updateDept(req: DeptRecord) {
return axios.put(BASE_URL, req);
}
export function deleteDept(ids: number | Array<number>) {
export function deleteDept(ids: string | Array<string>) {
return axios.delete(`${BASE_URL}/${ids}`);
}

View File

@ -4,9 +4,9 @@ import qs from 'query-string';
const BASE_URL = '/system/menu';
export interface MenuRecord {
menuId?: number;
menuId?: string;
menuName: string;
parentId?: number;
parentId?: string;
menuType: number;
path?: string;
name?: string;
@ -40,7 +40,7 @@ export function listMenu(params: MenuParam) {
});
}
export function getMenu(id: number) {
export function getMenu(id: string) {
return axios.get<MenuRecord>(`${BASE_URL}/${id}`);
}
@ -52,6 +52,6 @@ export function updateMenu(req: MenuRecord) {
return axios.put(BASE_URL, req);
}
export function deleteMenu(ids: number | Array<number>) {
export function deleteMenu(ids: string | Array<string>) {
return axios.delete(`${BASE_URL}/${ids}`);
}

View File

@ -4,14 +4,14 @@ import qs from 'query-string';
const BASE_URL = '/system/role';
export interface RoleRecord {
roleId?: number;
roleId?: string;
roleName: string;
roleCode?: string;
roleSort?: number;
description?: string;
menuIds?: Array<number>;
menuIds?: Array<string>;
dataScope: number;
deptIds?: Array<number>;
deptIds?: Array<string>;
status?: number;
createUserString?: string;
createTime?: string;
@ -42,7 +42,7 @@ export function listRole(params: RoleParam) {
});
}
export function getRole(id: number) {
export function getRole(id: string) {
return axios.get<RoleRecord>(`${BASE_URL}/${id}`);
}
@ -54,6 +54,6 @@ export function updateRole(req: RoleRecord) {
return axios.put(BASE_URL, req);
}
export function deleteRole(ids: number | Array<number>) {
export function deleteRole(ids: string | Array<string>) {
return axios.delete(`${BASE_URL}/${ids}`);
}

View File

@ -4,7 +4,7 @@ import qs from 'query-string';
const BASE_URL = '/system/user';
export interface UserRecord {
userId?: number;
userId?: string;
username: string;
nickname: string;
gender: number;
@ -17,9 +17,9 @@ export interface UserRecord {
createTime?: string;
updateUserString?: string;
updateTime?: string;
deptId?: number;
deptId?: string;
deptName?: string;
roleIds?: Array<number>;
roleIds?: Array<string>;
roleNames?: Array<string>;
disabled?: boolean;
}
@ -47,7 +47,7 @@ export function listUser(params: UserParam) {
});
}
export function getUser(id: number) {
export function getUser(id: string) {
return axios.get<UserRecord>(`${BASE_URL}/${id}`);
}
@ -59,18 +59,18 @@ export function updateUser(req: UserRecord) {
return axios.put(BASE_URL, req);
}
export function deleteUser(ids: number | Array<number>) {
export function deleteUser(ids: string | Array<string>) {
return axios.delete(`${BASE_URL}/${ids}`);
}
export function resetPassword(id: number) {
export function resetPassword(id: string) {
return axios.patch(`${BASE_URL}/${id}/password`);
}
export interface UpdateUserRoleReq {
roleIds?: Array<number>;
roleIds?: Array<string>;
}
export function updateUserRole(req: UpdateUserRoleReq, id: number) {
export function updateUserRole(req: UpdateUserRoleReq, id: string) {
return axios.patch(`${BASE_URL}/${id}/role`, req);
}

View File

@ -13,7 +13,7 @@ import useAppStore from '../app';
const useLoginStore = defineStore('user', {
state: (): UserState => ({
userId: 0,
userId: '',
username: '',
nickname: '',
gender: 0,
@ -23,7 +23,7 @@ const useLoginStore = defineStore('user', {
description: undefined,
pwdResetTime: undefined,
registrationDate: undefined,
deptId: 0,
deptId: '',
deptName: '',
permissions: [],
roles: [],

View File

@ -1,5 +1,5 @@
export interface UserState {
userId: number;
userId: string;
username: string;
nickname: string;
gender: number;
@ -9,7 +9,7 @@ export interface UserState {
description?: string;
pwdResetTime?: string;
registrationDate?: string;
deptId?: number;
deptId?: string;
deptName?: string;
permissions: Array<string>;
roles: Array<string>;

View File

@ -299,7 +299,7 @@
*
* @param id ID
*/
const toDetail = async (id: number) => {
const toDetail = async (id: string) => {
visible.value = true;
loading.value = true;
getSystemLog(id).then((res) => {

View File

@ -318,7 +318,7 @@
updateTime: '',
parentName: '',
});
const ids = ref<Array<number>>([]);
const ids = ref<Array<string>>([]);
const title = ref('');
const single = ref(true);
const multiple = ref(true);
@ -384,7 +384,7 @@
*
* @param id ID
*/
const toUpdate = (id: number) => {
const toUpdate = (id: string) => {
reset();
listDeptTree({}).then((res) => {
treeData.value = res.data;
@ -448,7 +448,7 @@
*
* @param id ID
*/
const toDetail = async (id: number) => {
const toDetail = async (id: string) => {
if (detailLoading.value) return;
detailLoading.value = true;
detailVisible.value = true;
@ -493,7 +493,7 @@
*
* @param ids ID 列表
*/
const handleDelete = (ids: Array<number>) => {
const handleDelete = (ids: Array<string>) => {
deleteDept(ids).then((res) => {
proxy.$message.success(res.msg);
getList();

View File

@ -360,7 +360,7 @@
const { DisEnableStatusEnum } = proxy.useDict('DisEnableStatusEnum');
const menuList = ref<MenuRecord[]>([]);
const ids = ref<Array<number>>([]);
const ids = ref<Array<string>>([]);
const title = ref('');
const single = ref(true);
const multiple = ref(true);
@ -427,7 +427,7 @@
*
* @param id ID
*/
const toUpdate = (id: number) => {
const toUpdate = (id: string) => {
reset();
listMenuTree({}).then((res) => {
treeData.value = res.data;
@ -519,7 +519,7 @@
*
* @param ids ID 列表
*/
const handleDelete = (ids: Array<number>) => {
const handleDelete = (ids: Array<string>) => {
deleteMenu(ids).then((res) => {
proxy.$message.success(res.msg);
getList();

View File

@ -419,7 +419,7 @@
deptIds: undefined,
});
const total = ref(0);
const ids = ref<Array<number>>([]);
const ids = ref<Array<string>>([]);
const title = ref('');
const single = ref(true);
const multiple = ref(true);
@ -494,7 +494,7 @@
*
* @param id ID
*/
const toUpdate = (id: number) => {
const toUpdate = (id: string) => {
reset();
menuCheckStrictly.value = false;
deptCheckStrictly.value = false;
@ -644,7 +644,7 @@
*
* @param id ID
*/
const toDetail = async (id: number) => {
const toDetail = async (id: string) => {
if (detailLoading.value) return;
getMenuTree();
getDeptTree();
@ -690,7 +690,7 @@
*
* @param ids ID 列表
*/
const handleDelete = (ids: Array<number>) => {
const handleDelete = (ids: Array<string>) => {
deleteRole(ids).then((res) => {
proxy.$message.success(res.msg);
getList();

View File

@ -345,7 +345,7 @@
:mask-closable="false"
unmount-on-close
render-to-body
@ok="handleUpdateUserRole"
@ok="handleUpdateRole"
@cancel="handleCancel"
>
<a-form ref="userRoleFormRef" :model="form" :rules="rules" size="large">
@ -505,7 +505,7 @@
deptId: undefined,
});
const total = ref(0);
const ids = ref<Array<number>>([]);
const ids = ref<Array<string>>([]);
const title = ref('');
const single = ref(true);
const multiple = ref(true);
@ -598,7 +598,7 @@
*
* @param id ID
*/
const toUpdate = (id: number) => {
const toUpdate = (id: string) => {
reset();
getDeptOptions();
getRoleOptions();
@ -614,7 +614,7 @@
*
* @param id ID
*/
const toUpdateRole = (id: number) => {
const toUpdateRole = (id: string) => {
reset();
getRoleOptions();
getUser(id).then((res) => {
@ -665,7 +665,7 @@
description: '',
status: 1,
deptId: undefined,
roleIds: [] as Array<number>,
roleIds: [] as Array<string>,
};
proxy.$refs.formRef?.resetFields();
};
@ -704,9 +704,9 @@
};
/**
* 修改用户角色
* 修改角色
*/
const handleUpdateUserRole = () => {
const handleUpdateRole = () => {
proxy.$refs.userRoleFormRef.validate((valid: any) => {
if (!valid && form.value.userId !== undefined) {
updateUserRole({ roleIds: form.value.roleIds }, form.value.userId).then(
@ -725,7 +725,7 @@
*
* @param id ID
*/
const toDetail = async (id: number) => {
const toDetail = async (id: string) => {
if (detailLoading.value) return;
detailLoading.value = true;
detailVisible.value = true;
@ -769,7 +769,7 @@
*
* @param ids ID 列表
*/
const handleDelete = (ids: Array<number>) => {
const handleDelete = (ids: Array<string>) => {
deleteUser(ids).then((res) => {
proxy.$message.success(res.msg);
getList();
@ -781,7 +781,7 @@
*
* @param id ID
*/
const handleResetPassword = (id: number) => {
const handleResetPassword = (id: string) => {
resetPassword(id).then((res) => {
proxy.$message.success(res.msg);
});