在Python中,可以使用多线程或者多进程来实现并发调用接口。
- 使用多线程实现并发调用接口:
import threading import requests def call_api(url): response = requests.get(url) print(response.json()) urls = ["http://api.example.com/endpoint1", "http://api.example.com/endpoint2", "http://api.example.com/endpoint3"] threads = [] for url in urls: t = threading.Thread(target=call_api, args=(url,)) t.start() threads.append(t) for t in threads: t.join()
- 使用多进程实现并发调用接口:
import multiprocessing import requests def call_api(url): response = requests.get(url) print(response.json()) urls = ["http://api.example.com/endpoint1", "http://api.example.com/endpoint2", "http://api.example.com/endpoint3"] processes = [] for url in urls: p = multiprocessing.Process(target=call_api, args=(url,)) p.start() processes.append(p) for p in processes: p.join()
无论使用多线程还是多进程,都可以实现并发调用接口,加快执行速度。需要注意的是,并发调用接口可能会对接口服务器造成较大负担,所以在实际使用中需要根据接口服务器的性能和需求做出合理的调整。