비동기 호출(Asynchronous Request) 250417
q1: 비동기 호출(Asynchronous Request)
a1:
비동기 호출(Asynchronous Request)이란, 네트워크 요청 중에도 다른 작업을 멈추지 않고 계속 실행할 수 있는 방식을 말합니다.
특히 Python에서는 aiohttp, asyncio 같은 모듈을 활용해 비동기적으로 API를 호출할 수 있습니다.
⸻
✅ 비동기 호출과 동기 호출의 차이
동기(Synchronous)
- API 응답을 받을 때까지 프로그램 실행이 멈춤
- requests 라이브러리
비동기(Asynchronous)
- API 응답을 기다리는 동안 다른 작업 수행 가능
- aiohttp, httpx, asyncio 등
⸻
✅ aiohttp 예시 코드 (Bearer Token 사용)
import aiohttp
import asyncio
async def fetch_loan_count(customer_id, token):
url = "https://api.example.com/loan/count"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
json_data = {
"customer_id": customer_id
}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=json_data, headers=headers) as response:
return await response.json()
# 여러 명 고객 정보 비동기로 조회
async def main():
token = "YOUR_ACCESS_TOKEN"
customer_ids = ["C123", "C456", "C789"]
tasks = [fetch_loan_count(cid, token) for cid in customer_ids]
results = await asyncio.gather(*tasks)
for res in results:
print(res)
# 실행
asyncio.run(main())
⸻
✅ 왜 비동기가 유용한가요?
• 동시에 수십 개의 API 호출을 빠르고 효율적으로 처리 가능
• 데이터 수집, 대량 처리, 마이크로서비스 연동 등에 최적
• 웹서버에서 트래픽 처리 효율이 향상됨 (예: FastAPI, Sanic, Starlette)
⸻
✅ 주요 비동기 라이브러리
aiohttp: HTTP 클라이언트/서버를 위한 비동기 지원
httpx: requests 스타일의 비동기 HTTP 라이브러리
FastAPI: aiohttp 기반의 비동기 REST API 서버 프레임워크
asyncio: Python 표준 비동기 프레임워크 (코루틴 관리)