Is it possible to create @Around Aspect for feign.Client

https://github.com/spring-cloud/spring-cloud-openfeign/issues/59

看到github 有人问这个问题,做了个示例:

import org.apache.commons.io.IOUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient;
import org.springframework.stereotype.Component;
import feign.Request;
import feign.Response;

import java.io.StringWriter;

@Aspect
@Component
public class FeignClientAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(FeignClientAspect.class);

    @Pointcut("execution(* org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.*(..))")
    public void feignClientPointcut() {
    }

    @org.aspectj.lang.annotation.Around("feignClientPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        LOGGER.info("feignclient begin");
        long start = System.currentTimeMillis();
        Object object = joinPoint.getTarget();

        if (!(object instanceof LoadBalancerFeignClient)) {
            LOGGER.info("feignclient not LoadBalancerFeignClient");
            return joinPoint.proceed();
        }
        Object[] args = joinPoint.getArgs();
        for (Object obj : args) {
            if (obj instanceof Request) {
                Request request = (Request) obj;
                LOGGER.info("feignclient request url:{}", request.url());
            }
        }
        Object result = joinPoint.proceed();
        if (result instanceof Response) {
            Response response = (Response) result;

            StringWriter writer = new StringWriter();
            IOUtils.copy(response.body().asInputStream(), writer, "UTF-8");
            String theString = writer.toString();

            LOGGER.info("feignclient response body:{}", theString);
        }
        LOGGER.info("feignclient end ,耗时:{}", (System.currentTimeMillis() - start));
        return result;
    }
}

通过Aspect ,我们能拿到 FeignClient 请求和响应信息,可以做性能、异常上报。

 

https://www.cnblogs.com/zhangjianbin/p/9245023.html

posted @ 2018-11-23 19:29  zzhi.wang  阅读(676)  评论(0编辑  收藏  举报