완전한 비동기 해법을 살펴보기 전에 한 가지 즉각적인 해법을 시도해보자. 데이터베이스에 결
과를 바로 넣을 필요가 없다면, 결과를 한 묶음
batch
으로 모아서 데이터베이스에 비동기적으로
한 번에 넣을 수 있다. 이를 위해
AsyncBatcher
라는 클래스를 만들어서 우리가 보낸 일괄 요
청을 사용해 비동기로 조금씩 몰아서 요청을 던지게 한다. 이렇게 해도 프로그램이
CPU
작업
을 수행하지 않고 멈춘 채
I
/
O
대기에 들어가지만, 이 시간 동안 한 번에 하나가 아니라 여러
요청을 보낼 수 있다.
import
asyncio
import
aiohttp
class
AsyncBatcher
(object):
def
__init__(self, batch_size):
self.batch_size = batch_size
self.batch = []
self.client_session = None
self.url = f
"
http://127.0.0.1:8080/add
"
def
__enter__(self):
return
self
def
__exit__(self, *args, **kwargs):
self.flush()
def
save(self, result):
self.batch.append(result)
if
len(self.batch) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.