需求: 一个函数接口具有记录日志的功能,日志记录登录失败者的ip地址,但是这个接口在短时间内会多次被调用,会重复记录地址同一个地址,为了避免短时间内重复记录日志怎么解决?
1. 使用时间戳和缓存机制
可以维护一个缓存(全局变量),记录每个IP地址的最近记录时间。当有新的登录失败事件发生时,检查缓存中该IP地址的最后记录时间。如果距离上次记录时间过短(例如几秒钟内),就跳过本次日志记录。
伪代码示例:
#include <stdio.h>
#include <time.h>
#include <string.h>
#define LOG_INTERVAL 10 // 10秒钟内不重复记录
typedef struct {
char ip[16]; // 假设IP地址为IPv4格式
time_t last_log_time;
} IpLog;
IpLog ip_log_cache[100]; // 存储IP和最后记录时间的缓存
int find_ip_in_cache(const char *ip) {
for (int i = 0; i < 100; i++) {
if (strcmp(ip_log_cache[i].ip, ip) == 0) {
return i; // 找到缓存中的IP地址
}
}
return -1; // 没有找到
}
void log_failed_login(const char *ip) {
time_t curren