在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()
無論使用多線程還是多進程,都可以實現并發調用接口,加快執行速度。需要注意的是,并發調用接口可能會對接口服務器造成較大負擔,所以在實際使用中需要根據接口服務器的性能和需求做出合理的調整。