이벤트 기반의 이해
첵 “마이크로서비스 아키텍처 구축” 을 살펴보던 중 이벤트 기반(Event Driven)에 대해서 언급이 나왔다. 읽기만 해서는 이해가 되지 않아 코드를 작성해보았다. 물론 아직도 이해가 잘 안된다.
오케스트레이션(Orchestration)
중앙에서 이벤트를 모두 관리 및 처리
class Customrer():
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
class CustomerService():
def signup(self, customrer):
# 계좌 개설
BankService().create_account(customrer)
# 환영 메일 발송
MailService().send(customrer.email)
# 가입 패키지 발송
PostService().send(customrer.address)
class BankService():
def create_account(self, customrer):
print("Service Name: %s, Customrer Name: %s" %(self.__class__.__name__, customrer.name))
class MailService():
def send(self, to):
print("Service Name: %s, To: %s" % (self.__class__.__name__, to))
class PostService():
def send(self, to):
print("Service Name: %s, Address: %s" % (self.__class__.__name__, to))
if __name__ == '__main__':
customer = Customrer(name='SELO', address='Seoul, Korea', email='rochan87@gmail.com')
CustomerService().signup(customer)
코레오그래피(Choreography)
발행/구독 패턴을 통한 느슨한 결합
class Customrer():
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
EventBook = {
# example
'main_event': {
'events': ['dependent_event', ],
}
}
def register_event(pub_event_name, sub_event):
try:
pub_event = EventBook[pub_event]
pub_event.append(sub_event)
except KeyError:
EventBook[pub_event] = [sub_event]
def pub(event_name):
def add(func):
def __wrapper(*args, **kwargs):
_r = func(*args, **kwargs)
sub_events = EventBook[event_name]
for sub_event in sub_events:
sub_event(*args, **kwargs)
return _r
if event_name not in EventBook:
EventBook[event_name] = []
return __wrapper
return add
def sub(event_name):
def register(func):
def __wrapper(*args, **kwargs):
return func(*args, **kwargs)
if event_name not in EventBook:
EventBook[event_name] = []
EventBook[event_name].append(__wrapper)
return __wrapper
return register
SIGNUP = 'signup'
UPDATE = 'update'
class CustomerService:
@pub(SIGNUP)
def signup(self, customrer):
print("SignUp\n")
@pub(UPDATE)
def update(self, customrer):
print("Update\n")
class BankService:
@sub(SIGNUP)
def create_account(self, customrer):
print("Service Name: %s, Customrer Name: %s" %(self.__class__.__name__, customrer.name))
class MailService:
# 아래와 같이 구독하고 싶은 이벤트만 추가해서 원하는 동작을 수행한다.
@sub(SIGNUP)
@sub(UPDATE)
def send(self, customrer):
print("Service Name: %s, To: %s" % (self.__class__.__name__, customrer.email))
class PostService:
@sub(SIGNUP)
def send(self, customrer):
print("Service Name: %s, Address: %s" % (self.__class__.__name__, customrer.address))
if __name__ == '__main__':
customer = Customrer(name='SELO', address='Seoul, Korea', email='rochan87@gmail.com')
CustomerService().signup(customer)
CustomerService().update(customer)
MSA MicroserviceArchitecture EventDriven