V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
wolfie
V2EX  ›  分享创造

Request Log, HTTP 的请求日志,与重试补偿。

  •  2
     
  •   wolfie · 2022-09-26 10:13:03 +08:00 · 1465 次点击
    这是一个创建于 550 天前的主题,其中的信息可能已经有所发展或是发生改变。

    简介

    基于拦截 HTTP 请求的,日志记录与重试补偿的工具。



    特点

    • 上手快,学习成本低
    • 集成简单,代码侵入小
    • 可选重试补偿


    适用范围

    • RestTemplate
    • Feign
    • ServletRequest (被请求)


    简单示例

    @Resource
    private RestTemplate restTemplate;
    
    // 普通 RestTemplate 请求
    String result = restTemplate.exchange("url", HttpMethod.GET, null, String.class);
    
    // 使用 LogContext 包装后的 RestTemplate 请求
    String result2 = LogContext.log().execute(() -> {
        return restTemplate.exchange("url", HttpMethod.GET, null, String.class);
    });
    


    重试补偿

    // log() => retry() 以后,就会生成重试任务
    String result = LogContext.retry().execute(() -> {
        return restTemplate.exchange("url", HttpMethod.GET, null, String.class);
    });
    

    检查重试任务并分发示例



    其他

    1. spring-boot-demo 地址
    2. spring-boot-demo 依赖 H2 数据库,启动后可通过浏览器打开 http://localhost:12345/h2-console 访问数据库。
    3. 考虑到 H2 数据库,重试补偿任务调度。所以没有使用 Junit 等测试用例,使用 Controller 作为入口。


    项目地址: https://github.com/wolfiesonfire/request-log

    5 条回复    2022-09-26 14:12:31 +08:00
    heyleo
        1
    heyleo  
       2022-09-26 10:58:20 +08:00
    取了 request 的流之后,后面还能正常使用吗,可以分别试下 application/json 和 application/x-www-form-urlencoded 的流,在 controller 层还能正确取到参数吗
    wolfie
        2
    wolfie  
    OP
       2022-09-26 11:07:58 +08:00
    @heyleo
    你说的应该是 ServletRequest 场景。

    这里有判断,最外层的 ServletRequestWrapper 必须为可重复读取,不然不会读 Request Body

    https://github.com/wolfiesonfire/request-log/blob/master/request-log-core/src/main/java/com/wolfie/log/context/request/ServletRequestContext.java#L148~L150
    heyleo
        3
    heyleo  
       2022-09-26 11:18:54 +08:00
    @wolfie 嗯嗯,是这个,我现在也是这样写的,针对 application/json 的流可以正常使用,但是针对 application/x-www-form-urlencoded 的流,controller 层拿到参数之后都为空
    KevinBlandy
        4
    KevinBlandy  
       2022-09-26 12:35:23 +08:00
    wolfie
        5
    wolfie  
    OP
       2022-09-26 14:12:31 +08:00
    @heyleo
    spring-boot-demo 里是可以拿到 form-post 里的 body 。

    demo 里在 Filter 有对 ServletRequestWrapper 进行可重复读的包装。

    https://github.com/wolfiesonfire/request-log/blob/master/request-log-spring-boot-demo/src/main/java/com/wolfie/demo/aop/ContentCachingRequestFilter.java#L22
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3631 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:34 · PVG 12:34 · LAX 21:34 · JFK 00:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.