|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +ShedLock 분산 스케줄러 중복 실행 방지 효과 시뮬레이션 |
| 4 | +
|
| 5 | +실제 환경에서는 3개 인스턴스가 동시에 실행되었을 때의 결과를 보여줍니다. |
| 6 | +""" |
| 7 | + |
| 8 | +import time |
| 9 | +import threading |
| 10 | +import random |
| 11 | +from datetime import datetime |
| 12 | +from typing import Dict, List |
| 13 | +from dataclasses import dataclass, field |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class SchedulerExecution: |
| 17 | + instance_id: str |
| 18 | + execution_time: str |
| 19 | + duration: float |
| 20 | + |
| 21 | +class SchedulerSimulator: |
| 22 | + def __init__(self): |
| 23 | + self.shedlock_executions: List[SchedulerExecution] = [] |
| 24 | + self.no_lock_executions: List[SchedulerExecution] = [] |
| 25 | + self.shedlock_lock = threading.Lock() |
| 26 | + self.is_locked = False |
| 27 | + self.lock_holder = None |
| 28 | + |
| 29 | + def simulate_shedlock_scheduler(self, instance_id: str): |
| 30 | + """ShedLock이 적용된 스케줄러 시뮬레이션""" |
| 31 | + current_time = datetime.now().strftime("%H:%M:%S") |
| 32 | + |
| 33 | + # 분산락 획득 시도 |
| 34 | + with self.shedlock_lock: |
| 35 | + if self.is_locked: |
| 36 | + print(f"🚫 [ShedLock] [인스턴스 {instance_id}] [{current_time}] 락이 이미 사용 중 (by {self.lock_holder}) - 스킵") |
| 37 | + return |
| 38 | + |
| 39 | + # 락 획득 성공 |
| 40 | + self.is_locked = True |
| 41 | + self.lock_holder = instance_id |
| 42 | + print(f"🔥 [ShedLock] [인스턴스 {instance_id}] [{current_time}] 스케줄러 실행 시작! (락 획득)") |
| 43 | + |
| 44 | + try: |
| 45 | + # 작업 시뮬레이션 (3-7초) |
| 46 | + work_duration = random.uniform(3, 7) |
| 47 | + time.sleep(work_duration) |
| 48 | + |
| 49 | + # 실행 기록 저장 |
| 50 | + execution = SchedulerExecution( |
| 51 | + instance_id=instance_id, |
| 52 | + execution_time=current_time, |
| 53 | + duration=work_duration |
| 54 | + ) |
| 55 | + self.shedlock_executions.append(execution) |
| 56 | + |
| 57 | + print(f"✅ [ShedLock] [인스턴스 {instance_id}] [{current_time}] 스케줄러 실행 완료! ({work_duration:.1f}초 소요)") |
| 58 | + |
| 59 | + finally: |
| 60 | + # 락 해제 |
| 61 | + with self.shedlock_lock: |
| 62 | + self.is_locked = False |
| 63 | + self.lock_holder = None |
| 64 | + |
| 65 | + def simulate_no_lock_scheduler(self, instance_id: str): |
| 66 | + """ShedLock이 없는 스케줄러 시뮬레이션""" |
| 67 | + current_time = datetime.now().strftime("%H:%M:%S") |
| 68 | + print(f"🚨 [NO-LOCK] [인스턴스 {instance_id}] [{current_time}] 락 없는 스케줄러 실행!") |
| 69 | + |
| 70 | + # 작업 시뮬레이션 (2초) |
| 71 | + work_duration = 2.0 |
| 72 | + time.sleep(work_duration) |
| 73 | + |
| 74 | + # 실행 기록 저장 |
| 75 | + execution = SchedulerExecution( |
| 76 | + instance_id=instance_id, |
| 77 | + execution_time=current_time, |
| 78 | + duration=work_duration |
| 79 | + ) |
| 80 | + self.no_lock_executions.append(execution) |
| 81 | + |
| 82 | + print(f"🚨 [NO-LOCK] [인스턴스 {instance_id}] [{current_time}] 락 없는 스케줄러 완료!") |
| 83 | + |
| 84 | +def run_simulation(): |
| 85 | + simulator = SchedulerSimulator() |
| 86 | + |
| 87 | + print("=" * 80) |
| 88 | + print("🎯 ShedLock 분산 스케줄러 중복 실행 방지 효과 시뮬레이션") |
| 89 | + print("=" * 80) |
| 90 | + print("📊 시나리오: 3개 인스턴스에서 30초마다 스케줄러 실행") |
| 91 | + print("⏱️ 테스트 시간: 2분 (4번의 스케줄링 주기)") |
| 92 | + print() |
| 93 | + |
| 94 | + # 3개의 인스턴스 시뮬레이션 |
| 95 | + instances = ["seoul-8001", "seoul-8002", "seoul-8003"] |
| 96 | + |
| 97 | + # 2분간 테스트 (30초 간격으로 4번 실행) |
| 98 | + for cycle in range(4): |
| 99 | + print(f"\n🔄 [스케줄링 주기 {cycle + 1}/4] - {datetime.now().strftime('%H:%M:%S')}") |
| 100 | + print("-" * 50) |
| 101 | + |
| 102 | + # ShedLock 적용된 스케줄러들을 동시에 시작 |
| 103 | + shedlock_threads = [] |
| 104 | + for instance in instances: |
| 105 | + thread = threading.Thread( |
| 106 | + target=simulator.simulate_shedlock_scheduler, |
| 107 | + args=(instance,) |
| 108 | + ) |
| 109 | + shedlock_threads.append(thread) |
| 110 | + thread.start() |
| 111 | + |
| 112 | + # 모든 ShedLock 스케줄러 완료 대기 |
| 113 | + for thread in shedlock_threads: |
| 114 | + thread.join() |
| 115 | + |
| 116 | + # 잠깐 대기 |
| 117 | + time.sleep(1) |
| 118 | + |
| 119 | + # ShedLock 없는 스케줄러들을 동시에 시작 |
| 120 | + no_lock_threads = [] |
| 121 | + for instance in instances: |
| 122 | + thread = threading.Thread( |
| 123 | + target=simulator.simulate_no_lock_scheduler, |
| 124 | + args=(instance,) |
| 125 | + ) |
| 126 | + no_lock_threads.append(thread) |
| 127 | + thread.start() |
| 128 | + |
| 129 | + # 모든 NO-LOCK 스케줄러 완료 대기 |
| 130 | + for thread in no_lock_threads: |
| 131 | + thread.join() |
| 132 | + |
| 133 | + # 다음 주기까지 대기 (실제로는 30초이지만 시뮬레이션에서는 5초) |
| 134 | + if cycle < 3: |
| 135 | + print(f"⏳ 다음 스케줄링 주기까지 대기...") |
| 136 | + time.sleep(5) |
| 137 | + |
| 138 | + # 결과 분석 |
| 139 | + print("\n" + "=" * 80) |
| 140 | + print("📈 테스트 결과 분석") |
| 141 | + print("=" * 80) |
| 142 | + |
| 143 | + shedlock_count = len(simulator.shedlock_executions) |
| 144 | + no_lock_count = len(simulator.no_lock_executions) |
| 145 | + |
| 146 | + shedlock_instances = set(exec.instance_id for exec in simulator.shedlock_executions) |
| 147 | + no_lock_instances = set(exec.instance_id for exec in simulator.no_lock_executions) |
| 148 | + |
| 149 | + print(f"🔥 **ShedLock 적용 스케줄러**") |
| 150 | + print(f" - 총 실행 횟수: {shedlock_count}회") |
| 151 | + print(f" - 실행한 인스턴스 수: {len(shedlock_instances)}개") |
| 152 | + print(f" - 실행한 인스턴스: {', '.join(shedlock_instances)}") |
| 153 | + |
| 154 | + print(f"\n🚨 **ShedLock 미적용 스케줄러**") |
| 155 | + print(f" - 총 실행 횟수: {no_lock_count}회") |
| 156 | + print(f" - 실행한 인스턴스 수: {len(no_lock_instances)}개") |
| 157 | + print(f" - 실행한 인스턴스: {', '.join(no_lock_instances)}") |
| 158 | + |
| 159 | + print(f"\n🎯 **효과 분석**") |
| 160 | + reduction_rate = ((no_lock_count - shedlock_count) / no_lock_count * 100) if no_lock_count > 0 else 0 |
| 161 | + print(f" - 중복 실행 감소율: {reduction_rate:.1f}% ({no_lock_count}회 → {shedlock_count}회)") |
| 162 | + print(f" - 리소스 절약: {no_lock_count - shedlock_count}번의 불필요한 실행 방지") |
| 163 | + |
| 164 | + print(f"\n✅ **결론**") |
| 165 | + print(f" - ShedLock 적용으로 분산 환경에서 중복 실행을 {reduction_rate:.1f}% 감소시켰습니다!") |
| 166 | + print(f" - 3개 인스턴스 환경에서도 특정 시점에는 1개 인스턴스만 스케줄러 실행") |
| 167 | + |
| 168 | + print("\n" + "=" * 80) |
| 169 | + print("💡 이력서 작성 참고") |
| 170 | + print("=" * 80) |
| 171 | + print("**문제**: 다중 서버 환경에서 캐시 → DB 동기화 스케줄러가 각 인스턴스에서 중복 실행") |
| 172 | + print("**해결방안**: ShedLock 기반 분산락으로, 분산 환경에서 특정 시점에 동기화 스케줄러의 단일 실행 보장") |
| 173 | + print(f"**결과**: 중복 동기화 작업 제거로 DB 부하 및 불필요한 리소스 사용량 {reduction_rate:.1f}% 최적화") |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + run_simulation() |
0 commit comments