面试平台基于注解的反爬虫机制实现

定义一个注解 @LimitCheck,用于标记需要进行反爬虫检测的方法。

@Target(ElementType.METHOD)
复制代码
@Retention(RetentionPolicy.RUNTIME) public @interface LimitCheck { }

创建一个切面类 LimitAspect,在该类中实现反爬虫逻辑。 并且实现了将爬虫用户的ip更新到nacos配置的ip黑名单中。

@Aspect
复制代码
@Component public class LimitAspect { @Resource private CounterManager counterManager; @Resource private UserService userService; @Before("@annotation(limitCheck)") public void beforeMethod(LimitCheck limitCheck){ RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); // 显式获取当前登录用户 User loginUser = userService.getLoginUser(request); if (loginUser == null) { throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR); } String ip = IpUtils.getClientIp(request); crawlerDetect(loginUser.getId(), ip); } private void crawlerDetect(long loginUserId, String ip) { final int WARN_COUNT = 10; final int BAN_COUNT = 20; String key = String.format("user:access:%s", loginUserId); //计数 long count = counterManager.incrAndGetCounter(key); if (count > BAN_COUNT) { //踢下线 StpUtil.kickout(loginUserId); //更新ip黑名单 updateNacosBlackList(ip); throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "访问太频繁,已被封号"); } if (count == WARN_COUNT) { throw new BusinessException(110, "警告访问太频繁"); } } @Value("${nacos.config.data-id}") private String dataId; @Value("${nacos.config.server-addr}") private String serverAddr; @Value("${nacos.config.group}") private String group; private void updateNacosBlackList(String ip){ Properties properties = new Properties(); properties.put("serverAddr", serverAddr); try { ConfigService configService = NacosFactory.createConfigService(properties); String content = configService.getConfig(dataId, group, 5000); Yaml yaml = new Yaml(); Map<String, Object> yamlMap = yaml.load(content); List<String> blacklist = (List<String>) yamlMap.get("blackIpList"); if (!blacklist.contains(ip)) { blacklist.add(ip); } String updatedContent = yaml.dump(yamlMap); boolean isPublishOk = configService.publishConfig(dataId, group, updatedContent); if (isPublishOk) { System.out.println("配置更新成功"); } else { System.out.println("配置更新失败"); } } catch (NacosException e) { e.printStackTrace(); } } }
{B835F61A-DEF8-49D3-920C-0245EDE242DC}.png {46157015-5C85-4FF5-A2D5-0807F584BD59}.png 访问超10次,警告 image.png 访问超20次,踢下线并封号。 image.png ip已经更新到黑名单 image.png image.png
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP