package com.bcxin.Infrastructure.messages.components;

import com.bcxin.Infrastructures.components.LockProvider;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

public class DistributedLockProviderImpl implements LockProvider {
    private final RedissonClient redissonClient;

    public DistributedLockProviderImpl(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @Override
    public void execute(String key, Runnable runnable) {
        String wrappedKey = getDistributedLockedKey(key);
        RLock lock = this.redissonClient.getLock(wrappedKey);
        try {
            lock.lock();
            runnable.run();
        } finally {
            lock.unlock();
        }
    }

    private static String getDistributedLockedKey(String key) {
        return String.format("res_dis_%s", key);
    }
}
