{"id":27255414,"url":"https://github.com/kyungjunnoh/spring-redis-lock-example","last_synced_at":"2026-05-05T12:31:32.355Z","repository":{"id":237459451,"uuid":"794016173","full_name":"KyungJunNoh/spring-redis-lock-example","owner":"KyungJunNoh","description":"redis 분산락을 이용한 동시성 제어 예제","archived":false,"fork":false,"pushed_at":"2024-05-01T08:04:44.000Z","size":52,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-11T02:30:16.203Z","etag":null,"topics":["distributed-lock","kotlin","redis","spring-boot"],"latest_commit_sha":null,"homepage":"","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/KyungJunNoh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-04-30T09:48:32.000Z","updated_at":"2024-05-01T08:05:28.000Z","dependencies_parsed_at":null,"dependency_job_id":"9ba0d7c7-8f45-4028-b0e5-d8c3d1153b52","html_url":"https://github.com/KyungJunNoh/spring-redis-lock-example","commit_stats":null,"previous_names":["kyungjunnoh/spring-redis-lock-example"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/KyungJunNoh/spring-redis-lock-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KyungJunNoh%2Fspring-redis-lock-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KyungJunNoh%2Fspring-redis-lock-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KyungJunNoh%2Fspring-redis-lock-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KyungJunNoh%2Fspring-redis-lock-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/KyungJunNoh","download_url":"https://codeload.github.com/KyungJunNoh/spring-redis-lock-example/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KyungJunNoh%2Fspring-redis-lock-example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32649515,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-05T11:29:49.557Z","status":"ssl_error","status_checked_at":"2026-05-05T11:29:48.587Z","response_time":54,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["distributed-lock","kotlin","redis","spring-boot"],"created_at":"2025-04-11T02:19:39.272Z","updated_at":"2026-05-05T12:31:32.347Z","avatar_url":"https://github.com/KyungJunNoh.png","language":"Kotlin","funding_links":[],"categories":[],"sub_categories":[],"readme":"# spring-redis-lock-example\n### 설명\n- redis 분산락(Distributed lock)을 이용하여 분산환경으로부터 공유된 자원을 보호하기 위한 예제입니다.\n- 예제는 게시판 서비스에서 게시글의 좋아요 count에 대한 정합성을 보장합니다.\n- Spring Integration 의 RedisLockRegistry의 분산 락을 Standard 하게 사용할 수 있게끔 구현했습니다. \n\n### 실행 전 준비\n- docker로 redis 실행\n```\ndocker run --name redis -p 6379:6379 -d redis\n```\n\n### 테스트\n- [BoardLikeTest.kt](src/test/kotlin/org/practice/lock/BoardLikeTest.kt)를 통해 게시글의 좋아요 count 정합성 테스트를 할 수 있습니다.\n\n### 주요 클래스\n- [RedisLockerComponent](src/main/kotlin/org/practice/lock/util/RedisLockerComponent.kt)\n```kotlin\n/**\n * RedisLockerService 클래스는 RedisLocker를 생성하는 컴포넌트\n *\n * @property redisLockRegistry [RedisLockRegistry] 인스턴스로, 락(lock)을 관리\n */\n@Component\nclass RedisLockerComponent(\n    private val redisLockRegistry: RedisLockRegistry,\n) {\n\n    fun createLocker(registryKey: String, defaultObtainLockWaitingTimeSec: Int = 5) =\n        RedisLocker(registryKey, defaultObtainLockWaitingTimeSec, redisLockRegistry)\n}\n```\n\n- [RedisLocker](src/main/kotlin/org/practice/lock/util/RedisLocker.kt)\n```kotlin\n/**\n * RedisLocker 클래스는 RedisLockRegistry를 사용하여 동시성 제어를 위한 락(lock)\n *\n * @property registryKeyPrefix Redis 레지스트리의 키(key)에 접두사(prefix)로 사용될 문자열\n * @property defaultObtainWaitingTimeSec 락 획득을 시도할 때 기본 대기 시간(초). default 5초\n * @property lockRegistry 락(lock)을 관리하는 RedisLockRegistry\n */\nclass RedisLocker(\n    private val registryKeyPrefix: String,\n    private val defaultObtainWaitingTimeSec: Int = 5,\n    private val lockRegistry: RedisLockRegistry,\n) {\n    private val logger = KotlinLogging.logger { }\n\n    /**\n     * 지정된 키(key)에 대한 락(lock)을 획득하고, 주어진 람다 함수를 실행\n     *\n     * @param key 락(lock)을 획득할 키(key)로 사용될 문자열\n     * @param obtainWaitingTimeSec 락을 획득하기 위해 대기할 최대 시간(초). default [defaultObtainWaitingTimeSec]\n     * @param runnable 락(lock)을 획득한 후 실행할 람다 함수. 실행 결과를 반환.\n     * @return 람다 함수의 실행 결과를 반환. 락 획득에 실패한 경우 null을 반환.\n     */\n    fun \u003cT\u003e lock(\n        key: String,\n        obtainWaitingTimeSec: Int = defaultObtainWaitingTimeSec,\n        runnable: () -\u003e T,\n    ): T? {\n        var t: T? = null\n        val lock = lockRegistry.obtain(\"$registryKeyPrefix:$key\")\n        if (lock.tryLock(obtainWaitingTimeSec.toLong(), TimeUnit.SECONDS)) {\n            try {\n                logger.trace { \"LockStart - $registryKeyPrefix:$key\" }\n                t = runnable()\n                logger.trace { \"LockEnd - $registryKeyPrefix:$key\" }\n            } finally {\n                lock.unlock()\n            }\n        } else {\n            logger.trace { \"LockFailed - $registryKeyPrefix:$key\" }\n        }\n        return t\n    }\n}\n```\n\n### ⚠️ 참고\n**RedisLockRegistryConfig.kt**\n```kotlin\n@Configuration\nclass RedisLockRegistryConfig(\n    private val redisConnectionFactory: RedisConnectionFactory\n) {\n    companion object {\n        const val REGISTRY_PREFIX = \"example:lock\"\n        const val REDIS_KEY_TTL_SEC = 60 // 장애 복구 시간을 고려한 시간으로 설정해야함.\n    }\n\n    @Bean\n    fun redisLockRegistry() = RedisLockRegistry(\n        redisConnectionFactory,\n        REGISTRY_PREFIX,\n        REDIS_KEY_TTL_SEC * 1000L\n    ).also {\n        it.setRedisLockType(RedisLockRegistry.RedisLockType.PUB_SUB_LOCK) // spring docs 에 따라 PUB_SUB_LOCK 으로 설정\n    }\n}\n```\n- key가 만료되었다는 것은 대부분 redis 장애와 연관되므로 장애 유연성에 따라 `REDIS_KEY_TTL_SEC` 의 시간을 설정해야함.\n- master/replica connection은 pub/sub방식의 `RedisLockType.PUB_SUB_LOCK`을 원활히 지원하지 않으므로, 상황에 따라 RedisLockType을 설정해야함. (Spring Doc 참고)\n\n### 레퍼런스\n- [Spring Integration - RedisLockRegistry](https://docs.spring.io/spring-integration/reference/redis.html#redis-lock-registry)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkyungjunnoh%2Fspring-redis-lock-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkyungjunnoh%2Fspring-redis-lock-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkyungjunnoh%2Fspring-redis-lock-example/lists"}