springboot记录接口所接收参数到日志数据库

核心流程:

  • AOP 拦截接口请求,获取参数和上下文信息。
  • 异步服务层 将数据安全、高效地写入数据库。
  • 自定义注解 提供灵活的开关控制。

注:可根据实际需求选择存储粒度(如仅存储关键数据)、添加过滤逻辑或扩展存储维度(如调用结果、响应时间)。

1. 核心依赖与插件

(1) Spring AOP

用于拦截接口请求并提取数据:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
(3) JSON序列化库(可选)

若需将请求参数序列化为字符串存储,推荐使用Jackson或Gson:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

2. 数据库表设计

设计一个表来存储请求数据,示例表结构:

CREATE TABLE api_log (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    interface_name VARCHAR(255),
    request_params TEXT,
    request_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    user_id VARCHAR(100),  -- 可选:用户ID等上下文信息
    ip_address VARCHAR(50)
);

3. 实体类与Repository

(1) 创建日志实体类(JPA示例)
@Entity
public class ApiLog {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String interfaceName;
    private String requestParams;
    private LocalDateTime requestTime;
    private String userId;
    private String ipAddress;

    // 构造函数、Getter/Setter
}
(2) 创建Repository接口
 
public interface ApiLogRepository extends JpaRepository<ApiLog, Long> {
}


4. 异步保存服务层

将AOP捕捉的数据异步保存到数据库,避免影响接口性能:

@Service
public class LogService {
    
    @Autowired
    private ApiLogRepository apiLogRepository;

    @Async  // 标记为异步方法
    public void saveLog(ApiLog log) {
        apiLogRepository.save(log);
    }
}

在启动类或配置类中启用异步支持:

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    // 可选:配置线程池
    @Bean
    public Executor taskExecutor() {
        return Executors.newFixedThreadPool(10);
    }
}

5. AOP切面逻辑

(1) 自定义注解(可选,提升灵活性)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogToDatabase {
    String value() default "";
}
(2) 切面类实现
@Aspect
@Component
public class LogAspect {
    
    @Autowired
    private LogService logService;

    @Pointcut("@annotation(log) && @annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void loggableMethod(LogToDatabase log) {}

    @Around("loggableMethod(log)")
    public Object logExecution(@annotation.LogToDatabase log, ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        // 提取请求参数、用户信息、IP等
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String params = new ObjectMapper().writeValueAsString(request.getParameterMap());
        String ip = request.getRemoteAddr();
        String userId = ""; // 从 SecurityContext 或其他上下文中获取
        
        // 执行目标方法
        Object result = joinPoint.proceed();
        
        // 保存日志(异步)
        ApiLog logEntry = new ApiLog();
        logEntry.setInterfaceName(log.value());
        logEntry.setRequestParams(params);
        logEntry.setRequestTime(LocalDateTime.now());
        logEntry.setUserId(userId);
        logEntry.setIpAddress(ip);
        
        logService.saveLog(logEntry);

        return result;
    }
}

6. 接口使用示例

在需要记录的接口方法上添加注解:

@Aspect
@Component
public class LogAspect {
    
    @Autowired
    private LogService logService;

    @Pointcut("@annotation(log) && @annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void loggableMethod(LogToDatabase log) {}

    @Around("loggableMethod(log)")
    public Object logExecution(@annotation.LogToDatabase log, ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        // 提取请求参数、用户信息、IP等
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String params = new ObjectMapper().writeValueAsString(request.getParameterMap());
        String ip = request.getRemoteAddr();
        String userId = ""; // 从 SecurityContext 或其他上下文中获取
        
        // 执行目标方法
        Object result = joinPoint.proceed();
        
        // 保存日志(异步)
        ApiLog logEntry = new ApiLog();
        logEntry.setInterfaceName(log.value());
        logEntry.setRequestParams(params);
        logEntry.setRequestTime(LocalDateTime.now());
        logEntry.setUserId(userId);
        logEntry.setIpAddress(ip);
        
        logService.saveLog(logEntry);

        return result;
    }
}

关键点与注意事项

(1) 异步处理
  • 数据库写入操作通过@Async异步执行,避免阻塞主线程。
  • 分页、倾斜或消息队列(如Kafka)可在高并发场景下进一步优化。
(2) 敏感数据过滤
  • 在保存数据前,过滤敏感字段(如密码、Token):
    // 示例:排除password字段
    Map<String, String[]> filteredParams = new HashMap<>();
    for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
        if (!"password".equals(entry.getKey())) {
            filteredParams.put(entry.getKey(), entry.getValue());
        }
    }
    params = new ObjectMapper().writeValueAsString(filteredParams);
(3) 性能优化
  • 批量插入:在接口方法结束后,将日志数据暂存到内存队列,定期批量提交。
  • 参数压缩:对超大JSON参数进行Base64编码或压缩后存储。
(4) 事务管理
  • 如果日志记录必须与业务操作强一致,可将切面方法标记为@Transactional,但需权衡性能。
(5) 日志数据查询
  • 可通过Spring Data JPA的查询方法或自定义SQL提供日志查询接口:
    public interface ApiLogRepository extends JpaRepository<ApiLog, Long> {
        List<ApiLog> findByInterfaceNameAndRequestTimeBetween(String interfaceName, LocalDateTime start, LocalDateTime end);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值