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

[ Java ] RequestLog, HTTP 请求日志与补偿工具

  •  2
     
  •   wolfie · 66 天前 · 1029 次点击
    这是一个创建于 66 天前的主题,其中的信息可能已经有所发展或是发生改变。

    腾讯云最新优惠活动来了:云产品限时1折,云服务器低至88元/年 ,点击这里立即抢购:9i0i.cn/qcloud,更有2860元代金券免费领取,付款直接抵现金用,点击这里立即领取:9i0i.cn/qcloudquan

    (福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

    简介

    基于 SpringBoot, 可以记录 Http 请求日志,根据日志可选重试补偿。
    特点:侵入小,集成简单。

    适用场景

    对外请求(第三方 API 、内部服务请求),或者被请求时( Servlet )
    记录日志分析,后续根据日志重试补偿。


    简单示例

    RestTemplate 为例支持其他( ApacheHttpClient 、OKHttp 、Feign )

    Maven 依赖


    <dependency>
        <groupId>io.github.requestlog</groupId>
        <artifactId>request-log-resttemplate-starter</artifactId>
        <version>1.0</version>
    </dependency>
    

    增强客户端


    @RequestLogEnhanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    

    定义一个持久化


    记录日志用,不定义默认加载一个 Slf4jRequestLogRepository

    @Component
    public class MyRequestLogRepository implements IRequestLogRepository {
        @Override
        public void saveRequestLog(RequestLog requestLog) {
            // save request log
        }
        @Override
        public void saveRequestLogAndRetryJob(RequestLog requestLog, RequestRetryJob requestRetryJob) {
            // save request log and retry job
        }
    }
    

    包装代码


    包装后的代码,出现 Exceptionhttp code2xx 就算失败,就会记录

    // 原始请求
    String result = restTemplate.getForObject("url", String.class);
    
    // 使用 LogContext 包装请求
    String result = LogContext.log().execute(() -> {
        return restTemplate.getForObject("url", String.class);
    });
    

    更详细的包装代码


    看个意思,如果感兴趣,看项目内详细文档吧。

    LogContext.retry()
            .retryWaitStrategy(RetryWaitStrategy.FIXED)
            .retryInterval(60)
            .ignoreException(RuntimeException.class, IOException.class, NumberFormatException.class)
            .ignoreException(exception -> exception instanceof ClassCastException)
            .successWhenResponse(requestContext -> {
                return requestContext.getResponseCode() == 200;
            })
            .execute(() -> {
                return restTemplate.getForObject("url", String.class);
            });
    

    其他


    已上传到中央仓库(阿里 mirror 可能还没有同步)
    欢迎体验、提意见、提需求

    项目地址:https://github.com/requestlog/request-log
    RestTemplate 使用方式
    ApacheHttpClient 使用方式
    OKHttp 使用方式
    Feign 使用方式
    Servlet 使用方式

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2215 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 02:09 · PVG 10:09 · LAX 19:09 · JFK 22:09
    Developed with CodeLauncher
    ? Do have faith in what you're doing.


    http://www.vxiaotou.com