使用AOP记录feign调用日志

业务场景

记录请求第三方接口的情况。@DockLog可以用在类上也可以用在方法上

使用

DemoClientFeign


import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * DemoClientFeign
 *
 * @since 2024-03-12
 */
@DockLog
@FeignClient(url = "http://127.0.0.1:9707/demo_api", name = "demoClientFeign",
        fallbackFactory = DemlFeignFallBack.class)
public interface DemoClientFeign {

    /**
     * 获取token
     */
    @PostMapping(value = "/auth/login", produces = {MediaType.APPLICATION_JSON_VALUE})
    String getToken(@RequestBody String body);
}

DemoFeignFallBack


import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DemlFeignFallBack implements FallbackFactory<DemoClientFeign> {

	@Override
    public DemlFeignFallBack create(Throwable throwable) {

        log.error("DemoClientFeign error", throwable);

        return new DemoClientFeign() {
            @Override
            public String getToken(String body) {
                return null;
            }
		}
	}
}

主要代码

DockLogAspect


import com.xxx.JacksonUtils;
import com.xxx.DockLogAddDTO;
import com.xxx.DockLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 三方feign请求-日志记录
 *
 * @since 2024/3/19 15:50
 */
@Aspect
@Component
@Slf4j
public class DockLogAspect {

    @Autowired
    private DockLogService dockLogService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    private final ThreadLocal<DockLogAddDTO> tl = new ThreadLocal<>();

    @Pointcut("@within(com.ccreate.cnpc.openapi.annotations.DockLog) || @annotation(com.ccreate.cnpc.openapi.annotations.DockLog)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        DockLogAddDTO addDTO = tl.get();
        if (addDTO == null) {
            addDTO = new DockLogAddDTO();
        }

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        PostMapping postMapping = method.getAnnotation(PostMapping.class);
        GetMapping getMapping = method.getAnnotation(GetMapping.class);
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

        if (postMapping == null && getMapping == null && requestMapping == null) {
            return;
        }

        String[] value = new String[]{};
        if (Objects.nonNull(postMapping)) {
            value = postMapping.value();
        }
        if (Objects.nonNull(getMapping)) {
            value = getMapping.value();
        }
        if (Objects.nonNull(requestMapping)) {
            value = requestMapping.value();
        }
        if (value.length == 0) {
            return;
        }

        Object[] args = joinPoint.getArgs();

        addDTO.setStartMillis(System.currentTimeMillis());
        addDTO.setRequest(JacksonUtils.toJson(args));
        addDTO.setUrl(joinUrl(value[0], methodSignature));

        tl.set(addDTO);
    }

    @AfterReturning(value = "pointcut()", returning = "obj")
    public void afterReturn(Object obj) {
        try {
            DockLogAddDTO addDTO = tl.get();
            if (Objects.isNull(addDTO)) {
                return;
            }

            // 异步保存
            CompletableFuture.runAsync(() -> {
                if (Objects.nonNull(obj)) {
                    addDTO.setSuccess(true);
                    addDTO.setResponse(JacksonUtils.toJson(obj));
                } else {
                    addDTO.setSuccess(false);
                }
                addDTO.setCompletedMillis(System.currentTimeMillis());
                // 保存
                dockLogService.add(addDTO);
            }, taskExecutor);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            tl.remove();
        }
    }

    @AfterThrowing(pointcut = "pointcut()", throwing = "t")
    public void afterThrowing(JoinPoint jp, Throwable t) {
        try {
            DockLogAddDTO addDTO = tl.get();
            if (Objects.isNull(addDTO)) {
                return;
            }

            // 异步保存
            CompletableFuture.runAsync(() -> {
                addDTO.setSuccess(false);
                addDTO.setResponse(ExceptionUtils.getStackTrace(t));
                addDTO.setCompletedMillis(System.currentTimeMillis());
                // 保存
                dockLogService.add(addDTO);
            }, taskExecutor);
        } catch (Exception e) {
            log.error("afterThrowing exception", e);
        } finally {
            tl.remove();
        }
    }

    /**
     * 拼接URL
     */
    public String joinUrl(String url, Signature signature) {
        FeignClient feignClient = AnnotationUtils.findAnnotation(signature.getDeclaringType(), FeignClient.class);
        if (Objects.isNull(feignClient)) {
            return url;
        }

        return feignClient.url() + url;
    }
}

DockLog


import java.lang.annotation.*;

/**
 * 日志记录
 *
 * @since 2024/3/19 15:49
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DockLog {

}

DockLogService


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 三方接口feign请求日志 自定义服务实现类
 */
@Slf4j
@Service
public class DockLogService {

    /**
     * 新增三方接口feign请求日志
     *
     * @param params 三方接口feign请求日志信息
     * @author pengjin 2024-03-19
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(DockLogAddDTO params) {

        // 参数转成实体PO
        DockLogPO dockLogPo = CommonUtils.copyProperties(params, DockLogPO.class);

        Long startMillis = params.getStartMillis();
        Long completedMillis = params.getCompletedMillis();
        if (ObjectUtils.allNotNull(startMillis, completedMillis)) {
            dockLogPo.setTimeConsuming(completedMillis - startMillis);
        }

        return iDockLogService.save(dockLogPo);
    }
}

DockLogAddDTO


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

/**
 * 三方接口feign请求日志
 */
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "三方接口feign请求日志新增参数对象", description = "三方接口feign请求日志")
public class DockLogAddDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "id")
    private Long id;

    @ApiModelProperty(value = "请求")
    private String url;

    @ApiModelProperty(value = "请求参数")
    private String request;

    @ApiModelProperty(value = "返回参数")
    private String response;

    @ApiModelProperty(value = "是否成功:1-成功,0-未成功")
    private Boolean success;

    @ApiModelProperty(value = "请求耗时:毫秒")
    private Long timeConsuming;

    @ApiModelProperty(value = "请求开始时间")
    private Long startMillis;

    @ApiModelProperty(value = "请求结束时间")
    private Long completedMillis;
}

JacksonUtils


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.json.JsonWriteFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * JacksonUtils
 *
 * @author pengjin 2022/9/5
 * @see com.alibaba.nacos.common.utils.JacksonUtils
 */
@Slf4j
public final class JacksonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 序列化配置,针对java8 时间
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        // 反序列化配置,针对java8 时间
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                .registerModules(javaTimeModule)
                .configure(JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature(), true);
    }

    /**
     * Object to json string
     */
    public static String toJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            log.error("toJson error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Json string deserialize to Jackson {@link JsonNode}.
     *
     * @param json json string
     * @return {@link JsonNode}
     */
    public static JsonNode toObj(String json) {
        try {
            return MAPPER.readTree(json);
        } catch (IOException e) {
            log.error("转JsonNode失败", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Json string deserialize to Object.
     *
     * @param json          json string
     * @param typeReference {@link TypeReference} of object
     * @param <T>           General type
     * @return object
     * @throws E if deserialize failed
     */
    public static <T> T toObj(String json, TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("toObj error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Json string deserialize to Object.
     *
     * @param json json string
     * @param type type of object
     * @param <T>  General type
     * @return object
     * @throws E if deserialize failed
     */
    public static <T> T toObj(String json, Class<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("toObj error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Parse object to Jackson {@link JsonNode}.
     */
    public static JsonNode transferToJsonNode(Object obj) {
        return MAPPER.valueToTree(obj);
    }

    /**
     * Parse object to Jackson {@link ObjectNode}.
     */
    public static ObjectNode transferToObjectNode(Object obj) {
        return transferToJsonNode(obj).deepCopy();
    }

    /**
     * Parse object to Jackson {@link ObjectNode}.
     */
    public static ObjectNode transferToObjectNode(String json) {
        return toObj(json).deepCopy();
    }

    private JacksonUtils() {

    }
}

  • 11
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值