如何利用线程池解决调用第三接口出现 429 too many requests问题?

做报表统计的时候,需要调用一个第三方接口根据IP或许该IP的实际地址。
我先写了一个接口,从数据库中取出每条的ip 再调用第三方接口进行查询,把查到的地址信息存入数据库。
测试的时候出现429 too many requests问题,于是按照同事的建议做了些优化,并添加了线程池,最后测试的时候,没有出现因为 429 too many requests 问题而直接报500的错,但是 更新数据库中的数据1500条数据,一共花了一个小时,控制台打印显示大概是,每更新二三十条数据(调用二三十次第三方接口)它就会因为
频繁请求等问题而停顿,尝试再次发起请求。



我主要想问的就是:



如何利用线程池解决调用第三接口出现 429 too many requests的问题



或者



不使用线程池的话有没有其他方法可以解决这个问题



第三方接口: http://ip-api.com/json/ip地址?lang=zh-CN



下面是线程池相关部分的代码

 RejectedExecutionHandler handler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                if(!executor.isShutdown()){
                    try{
                        executor.getQueue().put(r);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        };
//线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 50, 30*1000,TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(1000),handler);

for (ModuleQueryLogEntity moduleQueryLogEntity : moduleQueryLogDtos){
            pool.execute(() -> {
                try {
                    ModuleQueryUrlResponse response = new ModuleQueryUrlResponse();
                                        //传入ip地址调用第三方接口查询
                    response = getUrlResponse(moduleQueryLogEntity.getIp(), ModuleQueryUrlResponse.class);
                                        //如果查询成功,把查到的信息存入数据库
                    if(response.getStatus().equals(SUCCESS)){
                        moduleQueryLogEntity.setCity(response.getCity());
                        moduleQueryLogEntity.setCountry(response.getCountry());
                        moduleQueryLogRepository.save(moduleQueryLogEntity);
                    }
                                        //沉睡
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

//下面是调用第三方接口的代码
public <T> T getUrlResponse(String ip,Class<T> responseType){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Retry-After","100");
        StringBuilder url = new StringBuilder(FINE_IP);
        url.append(ip);
        url.append("?lang=zh-CN");
        log.info(url.toString());
        ResponseEntity<String> response = restTemplate.exchange(
                url.toString(),
                HttpMethod.GET,
                new HttpEntity<String>(headers),
                String.class);
        return JSON.parseObject(response.getBody(), responseType);
    }


要么服务器性能不行,要么服务器做了限制。你应该让服务器的开发者提供一个可以批量操作的接口,一条一条肯定慢了。

这个和你的程序没有关系,是对方服务器对单位时间内、同一ip的请求次数做了限制。
规范的429返回,会在响应头里添加Retry-After属性,告诉你多长时间之后,才允许你再次访问。
上面批量操作的接口,要是能得到是最好的。要是得不到,要么你按照对方的要求,礼貌的请求,要么伪装你的ip地址(参考面向监狱编程。。)

一瞬间你的请求太多了,给你打回了,建议请求分批,一次最好不要超过100个,分批来