방법: Dapr에서 액터 재진입 활성화하고 사용하기 (How-to: Enable and use actor reentrancy in Dapr)
액터 재진입(actor reentrancy)에 대해 알아볼게요.
출처: Dapr 문서
본문
가상 액터 패턴의 핵심 원칙 중 하나는 액터 실행의 단일 스레드 특성이에요. 재진입이 없다면 Dapr 런타임은 모든 액터 요청에 락을 겁니다. 두 번째 요청은 첫 번째 요청이 완료될 때까지 시작할 수 없어요. 이는 액터가 같은 호출 체인의 일부라 해도 자신을 호출하거나 다른 액터가 자신을 호출할 수 없다는 뜻입니다.
재진입은 같은 체인 또는 컨텍스트의 요청이 이미 락이 걸린 액터에 다시 진입할 수 있게 해 이 문제를 해결해요. 이는 다음 시나리오에서 유용합니다:
- 액터가 자신에 메서드를 호출하고 싶은 경우
- 액터가 워크플로에서 작업을 수행한 다음 조정 액터에 다시 콜백하는 경우
재진입이 허용하는 체인의 예시는 아래와 같습니다:
Actor A -> Actor A
ActorA -> Actor B -> Actor A
재진입을 사용하면 가상 액터의 단일 스레드 동작을 희생하지 않고 더 복잡한 액터 호출을 수행할 수 있어요.
maxStackDepth 파라미터는 같은 액터에 수행할 수 있는 재진입 호출 수를 제어하는 값을 설정합니다. 기본값은 32로, 대부분의 경우 충분히 넘칩니다.
재진입을 활성화하도록 액터 런타임 구성 (Configure the actor runtime to enable reentrancy)
재진입 액터는 적절한 구성을 제공해야 합니다. 이는 다른 액터 구성 요소와 마찬가지로 액터의 GET /dapr/config 엔드포인트로 수행됩니다.
- .NET
- JavaScript
- Python
- Java
- Go
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<BankService>();
services.AddActors(options =>
{
options.Actors.RegisterActor<DemoActor>();
options.ReentrancyConfig = new Dapr.Actors.ActorReentrancyConfig()
{
Enabled = true,
MaxStackDepth = 32,
};
});
}
}
import { CommunicationProtocolEnum, DaprClient, DaprServer } from "@dapr/dapr";
// Configure the actor runtime with the DaprClientOptions.
const clientOptions = {
actor: {
reentrancy: {
enabled: true,
maxStackDepth: 32,
},
},
};
from fastapi import FastAPI
from dapr.ext.fastapi import DaprActor
from dapr.actor.runtime.config import ActorRuntimeConfig, ActorReentrancyConfig
from dapr.actor.runtime.runtime import ActorRuntime
from demo_actor import DemoActor
reentrancyConfig = ActorReentrancyConfig(enabled=True)
config = ActorRuntimeConfig(reentrancy=reentrancyConfig)
ActorRuntime.set_actor_config(config)
app = FastAPI(title=f'{DemoActor.__name__}Service')
actor = DaprActor(app)
@app.on_event("startup")
async def startup_event():
await actor.register_actor(DemoActor)
@app.get("/MakeExampleReentrantCall")
def do_something_reentrant():
return
다음은 HTTP API를 통해 재진입 구성을 제공하는 Golang으로 작성된 액터의 코드 조각입니다. 재진입은 아직 Go SDK에 포함되지 않았어요.
type daprConfig struct {
Entities []string `json:"entities,omitempty"`
ActorIdleTimeout string `json:"actorIdleTimeout,omitempty"`
ActorScanInterval string `json:"actorScanInterval,omitempty"`
DrainOngoingCallTimeout string `json:"drainOngoingCallTimeout,omitempty"`
DrainRebalancedActors bool `json:"drainRebalancedActors,omitempty"`
Reentrancy config.ReentrancyConfig `json:"reentrancy,omitempty"`
}
var daprConfigResponse = daprConfig{
[]string{defaultActorType},
actorIdleTimeout,
actorScanInterval,
drainOngoingCallTimeout,
drainRebalancedActors,
config.ReentrancyConfig{Enabled: true, MaxStackDepth: &maxStackDepth},
}
func configHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(daprConfigResponse)
}
재진입 요청 처리 (Handle reentrant requests)
재진입 요청의 핵심은 Dapr-Reentrancy-Id 헤더입니다. 이 헤더의 값은 요청을 호출 체인에 매칭하고 액터의 락을 우회하도록 허용하는 데 사용됩니다.
이 헤더는 재진입 구성이 지정된 어떤 액터 요청에 대해서도 Dapr 런타임이 생성합니다. 생성되면 액터를 락하는 데 사용되며 모든 향후 요청에 전달되어야 합니다. 아래는 재진입 요청을 처리하는 액터의 예시입니다:
func reentrantCallHandler(w http.ResponseWriter, r *http.Request) {
/*
* Omitted.
*/
req, _ := http.NewRequest("PUT", url, bytes.NewReader(nextBody))
reentrancyID := r.Header.Get("Dapr-Reentrancy-Id")
req.Header.Add("Dapr-Reentrancy-Id", reentrancyID)
client := http.Client{}
resp, err := client.Do(req)
/*
* Omitted.
*/
}
데모 (Demo)
액터 재진입을 사용하는 방법에 대한 이 비디오를 시청해 보세요.
다음 단계 (Next steps)
Dapr SDK의 액터
관련 링크 (Related links)
- Actors API 참조
- Actors 개요