예제
예제로 배우기.
핵심 개념, HTTP 라우팅, 인증, 영속성, 관측성, 프로토콜 어댑터를 다루는 분류별 예제를 탐색하세요. 각 카드는 GitHub 리포지토리의 전체 소스로 연결됩니다.
학습 경로
초급에서 고급까지 단계별 가이드를 따라가세요.
빠른 시작
초급30분 안에 첫 번째 Axon 워크플로우를 구축하세요.
HTTP 서비스
중급라우팅, 인증, 실시간 기능을 갖춘 프로덕션 HTTP API를 구축하세요.
고급 패턴
고급장애 복원력, 영속성, 엔터프라이즈 패턴을 마스터하세요.
인증 & 보안
중급Guard 노드, JWT 인증, 역할 기반 접근 제어로 API를 보호하세요.
전체 예제
Hello World
최소 Flat API 예제 — 트랜지션을 체이닝하여 인사말 생성 및 변환.
#[transition]
async fn greet(input: String) -> Outcome<String, String> {
Outcome::Next(format!("Hello, {input}!"))
}타입 안전 상태 트리
Axon, Transition, Outcome을 사용한 타입 안전 의사결정 흐름.
let flow = Axon::new("flow")
.then(validate)
.then(process);기본 스케매틱
디버깅 및 문서화를 위한 스케매틱 추출을 통한 Axon 흐름 시각화.
의사결정 트리 라우팅
Outcome::Branch를 사용한 접두사 기반 경로 라우팅 및 중첩 의사결정 트리.
주문 처리 워크플로우
도메인 주도 워크플로우: 검증, 결제, 재고 예약, 배송 처리.
Axon::new("order")
.then(validate_order)
.then(process_payment)
.then(reserve_inventory)
.then(arrange_shipping)Bus 접근 제어 시스템
@transition bus 속성을 통한 선언적 허용/거부 접근 제어.
#[transition(bus_allow = "db,cache")]
async fn fetch(input: Req) -> Outcome<Resp, String> { .. }라우트 파라미터
HTTP 핸들러에서 경로, 쿼리, 바디 파라미터의 타입 안전 추출.
Flat API 패턴
@transition과 @ranvier_router 매크로를 사용한 간결한 라우트 정의.
#[ranvier_router]
fn routes() -> Router {
route!(GET "/users" => list_users);
route!(POST "/users" => create_user);
}세션 패턴
고급 세션 생명주기 패턴: 생성, 검증, 만료, 정리.
멀티파트 업로드
multipart/form-data 추출 및 검증을 통한 파일 업로드 처리.
WebSocket 인그레스
이벤트 기반 메시징 및 세션 컨텍스트를 갖춘 WebSocket 연결.
WebSocket 에코 루프
에코 루프와 연결 생명주기를 갖춘 양방향 WebSocket 통신.
SSE 스트리밍
클라이언트에 대한 실시간 스트리밍 응답을 위한 Server-Sent Events.
OpenAPI 문서 생성
schemars를 통한 스키마 검증과 자동 생성 OpenAPI/Swagger 문서.
정적 파일 서빙
설정 가능한 디렉토리에서 정적 파일 및 빌드 자산 제공.
SPA 호스팅
폴백 라우팅과 자산 제공을 갖춘 싱글 페이지 애플리케이션 호스팅.
Guard 파이프라인
CorsGuard, RateLimitGuard, SecurityHeadersGuard, IpFilterGuard를 시각적 Transition 노드로 사용하는 HTTP 보안 파이프라인.
Axon::new("Guarded API")
.then(CorsGuard::new(cors_config))
.then(RateLimitGuard::new(100, 60_000))
.then(SecurityHeadersGuard::new(policy))
.then(IpFilterGuard::allow_list(["127.0.0.1"]))
.then(HelloHandler)JWT 역할 기반 인증
HS256 JWT를 사용한 IamVerifier 구현, IamPolicy::RequireRole, Axon::with_iam() 경계 검증.
let admin_circuit = Axon::new("admin-dashboard")
.with_iam(
IamPolicy::RequireRole("admin".into()),
JwtVerifier,
)
.then(AdminDashboard);장애 복구 & 영속성
워크플로우 장애 복구, 체크포인팅, 보상 훅.
Axon::new("resilient")
.then(step_a)
.then(step_b)
.with_persistence(store)
.with_compensation(rollback);Redis 통합
비동기 ConnectionManager를 사용한 세션 저장소 및 캐시용 Redis.
SeaORM 통합
마이그레이션 및 액티브 모델을 사용한 Sea ORM 데이터베이스 작업.
SQLx 데이터베이스 통합
Bus를 통한 SQLx 풀 주입과 인메모리 SQLite를 사용한 Transition 기반 쿼리.
let db = DbPool(pool);
let insert_axon = Axon::new("insert-user")
.then(InsertUser);
insert_axon.execute(req, &db, &mut bus).await;Traced 래퍼
Traced 래퍼와 ConnectionBus를 사용한 트랜지션의 자동 스팬 생성.
Synapse 외부 서비스 통합
타입 안전한 외부 서비스 호출(DB, API, 메시징)을 위한 코어 Synapse 트레이트.
프로덕션 설정
ranvier.toml 설정, 환경변수 오버라이드, 프로파일, 구조화 로깅, 그레이스풀 셧다운.
표준 라이브러리
내장 트랜지션: FilterNode, SwitchNode, LogNode 파이프라인 조합.
멀티테넌시
Bus 주입 TenantId와 범위 지정 데이터 접근을 통한 테넌트 격리 패턴.
테스팅 패턴
Transition 및 Axon 체인을 위한 단위 및 통합 테스트 전략.
커스텀 에러 타입
타입 안전 에러 처리를 위한 thiserror 기반 도메인별 에러 enum.
재시도 & 데드레터 큐
지수 백오프를 갖춘 DLQ 재시도, 타임아웃 패턴, 서킷 브레이커.
let axon = Axon::new("payment")
.then(gateway)
.with_dlq_policy(DlqPolicy::RetryThenDlq {
max_attempts: 5,
backoff_ms: 100,
})
.with_dlq_sink(dlq);상태 영속성 & 복구
장애 복구, 체크포인팅, 보상을 갖춘 내구성 워크플로우 실행.
LLM 콘텐츠 모더레이션
3단계 LLM 파이프라인: 콘텐츠 추출, AI 분류, 정책 적용.
// ExtractContent → ModerateContent → ApplyPolicy
Axon::new("moderate")
.then(extract_content)
.then(moderate_content)
.then(apply_policy)레퍼런스 이커머스 주문
보상 처리, 감사 추적, 멀티테넌시, RFC 7807 에러를 갖춘 완전한 Saga 파이프라인.
// Saga: CreateOrder → ProcessPayment → ReserveInventory → ScheduleShipping
// ↓ (comp) ↓ (comp)
// RefundPayment ReleaseInventory레퍼런스 채팅 서버
JWT 인증, REST + WS 하이브리드 라우팅, 메시지 영속성을 갖춘 멀티룸 WebSocket 채팅.
레퍼런스 Todo API
JWT 인증, Bus 의존성 주입, HTTP 라우팅, 컬렉션 기반 테스트를 갖춘 완전한 CRUD 애플리케이션.
// Single-transition Axon circuits per endpoint
POST /login -> [login] -> JWT token
GET /todos -> [list_todos] -> Vec<Todo>
POST /todos -> [create_todo] -> Todo
PUT /todos/:id -> [update_todo] -> Todo
DELETE /todos/:id -> [delete_todo] -> { deleted }cargo run -p <package>로 실행하세요.