> Java > java지도 시간 > 본문

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.

풀어 주다: 2023-07-25 17:52:41
앞으로
620명이 탐색했습니다.

온라인 사고 검토

얼마 전 동료가 밤에 온라인에 접속하기 전에 아주 간단한 기능을 추가했습니다.review코드를 검토하면서 회사의 가치인 노력과 진취성을 생각하고 일시적으로 추가했습니다. 로그 한 줄이 기본이라고 느꼈습니다. 문제는 없었지만, 온라인에 접속하자마자 알람이 많이 떴습니다. 빠르게 코드를 롤백하고, 문제를 발견하고, 추가용 코드를 삭제했습니다. 로그인하고 다시 온라인에 접속했습니다. review代码时想到公司拼搏进取的价值观临时他加一行 log 日志,觉得就一行简单的日志基本上没啥问题,结果刚上完线后一堆报警,赶紧回滚了代码,找到问题删除了添加日志的代码,重新上线完毕。

情景还原

定义了一个 CountryDTO

public class CountryDTO {
    private String country;

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return this.country;
    }

    public Boolean isChinaName() {
        return this.country.equals("中国");
    }
}
로그인 후 복사

定义测试类 FastJonTest

public class FastJonTest {
    @Test
    public void testSerialize() {
        CountryDTO countryDTO = new CountryDTO();
        String str = JSON.toJSONString(countryDTO);
        System.out.println(str);
    }
}
로그인 후 복사

运行时报空指针

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.

🎜시나리오 복원🎜🎜🎜
🎜

❝🎜

CountryDTO🎜

❞🎜🎜

public static List<FieldInfo> computeGetters(Class<?> clazz, //
                                                 JSONType jsonType, //
                                                 Map<String,String> aliasMap, //
                                                 Map<String,Field> fieldCacheMap, //
                                                 boolean sorted, //
                                                 PropertyNamingStrategy propertyNamingStrategy //
    ){
    //省略部分代码....
    Method[] methods = clazz.getMethods();
    for(Method method : methods){
        //省略部分代码...
        if(method.getReturnType().equals(Void.TYPE)){
            continue;
        }
        if(method.getParameterTypes().length != 0){
            continue;
        }
            //省略部分代码...
        JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
        //省略部分代码...
        if(annotation != null){
            if(!annotation.serialize()){
                continue;
            }
            if(annotation.name().length() != 0){
                //省略部分代码...
            }
        }
        if(methodName.startsWith("get")){
         //省略部分代码...
        }
        if(methodName.startsWith("is")){
         //省略部分代码...
        }
    }
}
로그인 후 복사
로그인 후 복사
🎜

❝🎜

테스트 클래스 정의FastJonTest🎜

❞🎜🎜

/**
 * case1: @JSONField(serialize = false)
 * case2: getXxx()返回值为void
 * case3: isXxx()返回值不等于布尔类型
 * case4: @JSONType(ignores = "xxx")
 */
@JSONType(ignores = "otherName")
public class CountryDTO {
    private String country;

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return this.country;
    }

    public static void queryCountryList() {
        System.out.println("queryCountryList()执行!!");
    }

    public Boolean isChinaName() {
        System.out.println("isChinaName()执行!!");
        return true;
    }

    public String getEnglishName() {
        System.out.println("getEnglishName()执行!!");
        return "lucy";
    }

    public String getOtherName() {
        System.out.println("getOtherName()执行!!");
        return "lucy";
    }

    /**
     * case1: @JSONField(serialize = false)
     */
    @JSONField(serialize = false)
    public String getEnglishName2() {
        System.out.println("getEnglishName2()执行!!");
        return "lucy";
    }

    /**
     * case2: getXxx()返回值为void
     */
    public void getEnglishName3() {
        System.out.println("getEnglishName3()执行!!");
    }

    /**
     * case3: isXxx()返回值不等于布尔类型
     */
    public String isChinaName2() {
        System.out.println("isChinaName2()执行!!");
        return "isChinaName2";
    }
}
로그인 후 복사
로그인 후 복사
🎜실행 시간Null 포인터 오류: 🎜🎜🎜널 포인터🎜

오류 메시지를 보면 직렬화 과정에서 isChinaName() 메소드, 현재 this.country 변수가 비어 있으면 문제가 발생합니다. isChinaName()方法,这时候this.country变量为空,那么问题来了:

  • 序列化为什么会执行isChinaName()呢?
  • 引申一下,序列化过程中会执行那些方法呢?

源码分析

通过 debug 观察调用链路的堆栈信息

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.

图片

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.

图片

调用链中的ASMSerializer_1_CountryDTO.writeFastJson使用asm技术动态生成了一个类ASMSerializer_1_CountryDTO

  • 직렬화가 수행되는 이유isChinaName()은 어떻습니까?
  • 또한 직렬화 프로세스 중에 어떤 메소드가 실행됩니까?

소스 코드 분석

디버그를 통해 호출 링크의 스택 정보를 관찰하세요🎜

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.🎜

사진

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.🎜<그림 데이터 -tool="mdnice editor" style="max-width:90%">

사진
🎜 ASMSerializer_1_CountryDTO.write</ 코드>는 <code style="font-size: 14px;overflow-wrap: break-word;padding: 2px 4px;border-radius: 4px;margin-right: 2px;margin-left: 2px; color: rgb(30)입니다. , 107, 184); 배경색: rgba(27, 31, 35, 0.05); 글꼴 계열: 'Operator Mono', Consolas, Monaco, Menlo, monospace; /code>는 <code style="font-size: 14px;overflow-wrap: break-word;padding: 2px 4px;border-radius: 4px;margin-right: 2px;margin-left: 2px ;color: rgb( 30, 107, 184);배경색: rgba(27, 31, 35, 0.05);글꼴 계열: 'Operator Mono', Consolas, Monaco, Menlo, monospace;단어 나누기: break-all;">asm 기술은 클래스ASMSerializer_1_CountryDTO. 🎜

asm技术其中一项使用场景就是通过到动态生成类用来代替java反射,从而避免重复执行时的反射开销

JavaBeanSerizlier序列化原理

通过下图看出序列化的过程中,主要是调用JavaBeanSerializer类的write()方法。

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.ObjectSerializer实现类JavaBeanSerializer

JavaBeanSerializer主要是通过getObjectWriter()方法获取,通过对getObjectWriter()执行过程的调试,找到比较关键的com.alibaba.fastjson.serializer.SerializeConfig#createJavaBeanSerializer方法,进而找到 com.alibaba.fastjson.util.TypeUtils#computeGetters

public static List<FieldInfo> computeGetters(Class<?> clazz, //
                                                 JSONType jsonType, //
                                                 Map<String,String> aliasMap, //
                                                 Map<String,Field> fieldCacheMap, //
                                                 boolean sorted, //
                                                 PropertyNamingStrategy propertyNamingStrategy //
    ){
    //省略部分代码....
    Method[] methods = clazz.getMethods();
    for(Method method : methods){
        //省略部分代码...
        if(method.getReturnType().equals(Void.TYPE)){
            continue;
        }
        if(method.getParameterTypes().length != 0){
            continue;
        }
            //省略部分代码...
        JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
        //省略部分代码...
        if(annotation != null){
            if(!annotation.serialize()){
                continue;
            }
            if(annotation.name().length() != 0){
                //省略部分代码...
            }
        }
        if(methodName.startsWith("get")){
         //省略部分代码...
        }
        if(methodName.startsWith("is")){
         //省略部分代码...
        }
    }
}
로그인 후 복사
로그인 후 복사

从代码中大致分为三种情况:

  • @JSONField(.serialize = false, name = "xxx")注解
  • getXxx() : get开头的方法
  • isXxx():is开头的方法

序列化流程图

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.序列化流程图

示例代码

/**
 * case1: @JSONField(serialize = false)
 * case2: getXxx()返回值为void
 * case3: isXxx()返回值不等于布尔类型
 * case4: @JSONType(ignores = "xxx")
 */
@JSONType(ignores = "otherName")
public class CountryDTO {
    private String country;

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return this.country;
    }

    public static void queryCountryList() {
        System.out.println("queryCountryList()执行!!");
    }

    public Boolean isChinaName() {
        System.out.println("isChinaName()执行!!");
        return true;
    }

    public String getEnglishName() {
        System.out.println("getEnglishName()执行!!");
        return "lucy";
    }

    public String getOtherName() {
        System.out.println("getOtherName()执行!!");
        return "lucy";
    }

    /**
     * case1: @JSONField(serialize = false)
     */
    @JSONField(serialize = false)
    public String getEnglishName2() {
        System.out.println("getEnglishName2()执行!!");
        return "lucy";
    }

    /**
     * case2: getXxx()返回值为void
     */
    public void getEnglishName3() {
        System.out.println("getEnglishName3()执行!!");
    }

    /**
     * case3: isXxx()返回值不等于布尔类型
     */
    public String isChinaName2() {
        System.out.println("isChinaName2()执行!!");
        return "isChinaName2";
    }
}
로그인 후 복사
로그인 후 복사

运行结果为:

isChinaName()执行!!
getEnglishName()执行!!
{"chinaName":true,"englishName":"lucy"}
로그인 후 복사

代码规范

可以看出来序列化的规则还是很多的,比如有时需要关注返回值,有时需要关注参数个数,有时需要关注@JSONType注解,有时需要关注@JSONField注解;当一个事物的判别方式有多种的时候,由于团队人员掌握知识点的程度不一样,这个方差很容易导致代码问题,所以尽量有一种推荐方案。

这里推荐使用@JSONField(serialize = false)来显式的标注方法不参与序列化,下面是使用@JSONField注解后的代码,是不是一眼就能看出来哪些方法不需要参与序列化了。

public class CountryDTO {
    private String country;

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return this.country;
    }

    @JSONField(serialize = false)
    public static void queryCountryList() {
        System.out.println("queryCountryList()执行!!");
    }

    public Boolean isChinaName() {
        System.out.println("isChinaName()执行!!");
        return true;
    }

    public String getEnglishName() {
        System.out.println("getEnglishName()执行!!");
        return "lucy";
    }

    @JSONField(serialize = false)
    public String getOtherName() {
        System.out.println("getOtherName()执行!!");
        return "lucy";
    }

    @JSONField(serialize = false)
    public String getEnglishName2() {
        System.out.println("getEnglishName2()执行!!");
        return "lucy";
    }

    @JSONField(serialize = false)
    public void getEnglishName3() {
        System.out.println("getEnglishName3()执行!!");
    }

    @JSONField(serialize = false)
    public String isChinaName2() {
        System.out.println("isChinaName2()执行!!");
        return "isChinaName2";
    }
}
로그인 후 복사

三个频率高的序列化的情况

한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.三个频率高的序列化的情况

以上流程基本遵循,发现问题 --> 原理分析 --> 解决问题 --> 升华(编程规范)。

  • 围绕业务上:解决问题 -> 如何选择一种好的额解决方案 -> 好的解决方式如何扩展 n 个系统应用;
  • 围绕技术上:解决单个问题,顺着单个问题掌握这条线上的原理。

但其实这段代码我并不满意,原因是和 FastJson 依赖太高了。我想要的效果是,不依赖任何特定的 JSON 序列化框架。当我需要替换掉它的时候,随时可以替换掉。

并且在写代码时,不要过于依赖日志。打日志只需要打紧要且关键的信息即可,不要什么日志都打,我曾见过一个系统,一个小时,把 128G 磁盘跑满的管理系统。几乎没啥并发,但几乎每个请求都输出几 M 的日志,这件事我后面会单独拿出来讲讲。

关于@JSONField@JSONType等特性注解,后面我会在团队内规范并给出新的解耦方案,把它们移除掉。

위 내용은 한 줄의 로그로 인해 P1의 온라인 사고가 발생했습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:Java学习指南
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!