Redis 분산락 구현하기

dev_hwan·2023년 10월 18일
0

사용 기술스택
redis(redisson)
java 11
Spring 2.7.x

RedissonConfig.java

@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    private static final String REDISSON_HOST_PREFIX = "redis://";

    @Bean
    public RedissonClient redissonClient() {
        RedissonClient redisson = null;
        Config config = new Config();
        config.useSingleServer().setAddress(REDISSON_HOST_PREFIX + redisHost + ":" + redisPort);
        redisson = Redisson.create(config);

        return redisson;
    }

}

SetttlementFace.java

@Service
@RequiredArgsConstructor
public class SettlementFacade {

    private final RedissonClient redissonClient;
    private final SettlementService settlementService;

    public void completeSettlement(Long userId, SettlementCompleteDTO dto) {
        // Redisson 분산 락 이름 정의 ("settlementLock_" + settlementRequestId)
        String lockKey = "settlementLock_" + dto.getSettlementRecipientId();
        // Redisson 락 객체 획득
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // 분산 락 시도. 최대 5초 기다린 후, 1초 동안 락 유지
            if (lock.tryLock(5, 1, TimeUnit.SECONDS)) {
                settlementService.completeSettlement(userId, dto);
            }
        } catch (InterruptedException e) {
            // 락 대기 중 인터럽트 발생 시 처리
            throw new CustomException(ErrorCode.INTERNAL_SERVER_ERROR);
        } finally {
            // 락이 현재 쓰레드에 의해 보유되고 있으면 해제
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
profile
내맘대로 주제잡고 재미로 글쓰는 개발일지 블로그 👨‍💻

0개의 댓글

관련 채용 정보