본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

How-To: 상태 저장 서비스 구축하기

원문 보기 위키 갱신

확장·복제된 서비스로 상태 관리를 사용하는 방법을 알아볼게요.

이 문서에서는 선택(opt-in) 동시성 및 일관성 모델을 사용해 수평 확장할 수 있는 상태 저장 서비스를 만드는 방법을 배워요. 상태 관리 API를 사용하면 개발자가 어려운 상태 조정, 충돌 해결, 실패 처리를 하지 않아도 돼요.

출처: Dapr 문서

본문

상태 저장소 설정하기

상태 저장소 컴포넌트는 Dapr이 데이터베이스와 통신할 때 사용하는 리소스를 나타내요. 이 가이드에서는 기본 Redis 상태 저장소를 사용할게요.

Dapr CLI 사용

셀프 호스트 모드에서 dapr init을 실행하면 Dapr이 기본 Redis statestore.yaml을 만들고 로컬 머신에 Redis 상태 저장소를 실행해요. 위치는:

  • Windows의 경우 %UserProfile%\.dapr\components\statestore.yaml
  • Linux/MacOS의 경우 ~/.dapr/components/statestore.yaml

statestore.yaml 컴포넌트를 사용하면 애플리케이션 코드 변경 없이 기본 컴포넌트를 쉽게 교체할 수 있어요. 지원되는 상태 저장소 목록을 확인해 보세요.

Kubernetes

Kubernetes에서 다른 상태 저장소를 설정하는 방법을 확인해 보세요.

강한 일관성과 최종 일관성

강한 일관성(strong consistency)을 사용하면 Dapr이 기본 상태 저장소가 다음을 보장하게 해요.

  • 데이터가 모든 복제본에 기록된 후에 응답을 반환해요.
  • 상태를 쓰거나 삭제하기 전에 쿼럼(quorum)에서 ACK를 받아요.

get 요청의 경우 Dapr은 상태 API에 대한 요청에 달리 명시되지 않는 한, 저장소가 복제본 사이에서 가장 최신 데이터를 일관되게 반환하도록 해요. 기본값은 최종 일관성(eventual consistency)이에요.

다음 예시는 강한 일관성을 사용해 상태를 저장, 가져오기, 삭제하는 방법을 보여줘요. 예시는 Python으로 작성됐지만 모든 프로그래밍 언어에 적용할 수 있어요.

상태 저장

import requests
import json

store_name = "redis-store" # name of the state store as specified in state store component yaml file
dapr_state_url = "http://localhost:3500/v1.0/state/{}".format(store_name)
stateReq = '[{ "key": "k1", "value": "Some Data", "options": { "consistency": "strong" }}]'
response = requests.post(dapr_state_url, json=stateReq)

상태 가져오기

import requests
import json

store_name = "redis-store" # name of the state store as specified in state store component yaml file
dapr_state_url = "http://localhost:3500/v1.0/state/{}".format(store_name)
response = requests.get(dapr_state_url + "/key1", headers={"consistency":"strong"})
print(response.headers['ETag'])

상태 삭제

import requests
import json

store_name = "redis-store" # name of the state store as specified in state store component yaml file
dapr_state_url = "http://localhost:3500/v1.0/state/{}".format(store_name)
response = requests.delete(dapr_state_url + "/key1", headers={"consistency":"strong"})

concurrency 옵션을 지정하지 않으면 기본값은 last-write(마지막 쓰기) 동시성 모드예요.

First-write-wins와 last-write-wins

Dapr은 데이터 저장소 작업 시 두 가지 흔한 동시성 패턴을 개발자가 선택할 수 있게 해줘요.

  • First-write-wins: 애플리케이션 인스턴스가 여러 개 있고, 모두 같은 키에 동시에 쓰는 상황에서 유용해요.
  • Last-write-wins: Dapr의 기본 모드예요.

Dapr은 버전 번호를 사용해 특정 키가 업데이트됐는지 확인해요. 다음을 할 수 있어요.

  • 키에 대한 데이터를 읽을 때 버전 번호를 보관해요.
  • 쓰기와 삭제 같은 업데이트 시 버전 번호를 사용해요.

버전 번호를 가져온 이후 버전 정보가 변경되면 오류가 발생해서, 최신 버전 정보와 상태를 얻으려면 다시 읽어야 해요.

Dapr은 ETag를 활용해 상태의 버전 번호를 확인해요. ETag는 상태 요청에서 ETag 헤더로 반환돼요. ETag를 사용하면 애플리케이션이 리소스가 마지막 확인 이후 업데이트됐음을 ETag 불일치 시 오류로 알 수 있어요.

다음 예시는:

  • ETag를 가져오는 방법.
  • ETag로 상태를 저장하는 방법.
  • 상태를 삭제하는 방법.

을 보여줘요.

다음 예시는 Python으로 작성됐지만 모든 프로그래밍 언어에 적용할 수 있어요.

import requests
import json

store_name = "redis-store" # name of the state store as specified in state store component yaml file
dapr_state_url = "http://localhost:3500/v1.0/state/{}".format(store_name)
response = requests.get(dapr_state_url + "/key1", headers={"concurrency":"first-write"})
etag = response.headers['ETag']
newState = '[{ "key": "k1", "value": "New Data", "etag": {}, "options": { "concurrency": "first-write" }}]'.format(etag)

requests.post(dapr_state_url, json=newState)
response = requests.delete(dapr_state_url + "/key1", headers={"If-Match": "{}".format(etag)})

버전 불일치 실패 처리

다음 예시에서는 버전이 변경됐을 때 저장 상태 작업을 재시도하는 방법을 볼 수 있어요.

import requests
import json


def save_state(data):
    try:
        store_name = "redis-store" # name of the state store as specified in state store component yaml file
        dapr_state_url = "http://localhost:3500/v1.0/state/{}".format(store_name)
        response = requests.post(dapr_state_url, json=data)
        if response.status_code == 200:
            return True
    except:
        return False
    return False


def get_state(key):
    response = requests.get("http://localhost:3500/v1.0/state/<state_store_name>/{}".format(key), headers={"concurrency":"first-write"})
    return response


success = False
while success != True:
    response = get_state("key1")
    etag = response.headers['ETag']
    newState = '[{ "key": "key1", "value": "New Data", "etag": {}, "options": { "concurrency": "first-write" }}]'.format(etag)

    success = save_state(newState)

더 알아보기 (Learn more)