文章目录
业务场景
记录请求第三方接口的情况。@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;
}