更新时间:2024-11-28 GMT+08:00
分享

Redisson Lock

Redisson是一个基于Redis的Java库,它提供了一系列的分布式对象和服务,其中包括分布式锁。

Redisson的分布式锁实现了可靠的分布式锁机制,可以在分布式环境下实现对共享资源的并发访问控制。

对接Redisson Lock命令参考如下。

import com.huawei.devspore.mas.redis.config.Constants;
import com.huawei.devspore.mas.redis.config.MasRedisConfiguration;
import com.huawei.devspore.mas.redis.config.RedisServerConfiguration;
import com.huawei.devspore.mas.redis.config.RedisType;
import com.huawei.devspore.mas.redis.core.MultiZoneClient;
import com.huawei.devspore.mas.redis.exception.DcsException;

import lombok.extern.slf4j.Slf4j;

import org.Redisson.Redisson;
import org.Redisson.api.RLock;
import org.Redisson.api.RedissonClient;
import org.Redisson.codec.JsonJacksonCodec;
import org.Redisson.config.Config;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RedissonClientStorage {
    // dcs的客户端
    private final MultiZoneClient client;

    // dc1和dc2的RedissonClient
    private final Map<String, RedissonClient> RedissonDcsMap = new HashMap<>();

    /**
     * @param client                MultiZoneClient用于获取active.
     * @param masRedisConfiguration 获取Redis配置
     * @return
     */
    public RedissonClientStorage(MultiZoneClient client, MasRedisConfiguration masRedisConfiguration) {
        this.client = client;
        if (masRedisConfiguration.getRedis().getServers().containsKey(Constants.DC_1)) {
            RedissonDcsMap.put(Constants.DC_1,
                create(masRedisConfiguration.getRedis().getServers().get(Constants.DC_1)));
        }
        if (masRedisConfiguration.getRedis().getServers().containsKey(Constants.DC_2)) {
            RedissonDcsMap.put(Constants.DC_2,
                create(masRedisConfiguration.getRedis().getServers().get(Constants.DC_2)));
        }
    }
    public static RedissonClient create(RedisServerConfiguration configuration) {
        if (RedisType.NORMAL.equals(configuration.getType())
            || RedisType.MASTER_SLAVE.equals(configuration.getType())) {
            Config config = new Config();
            config.useSingleServer()
                .setAddress(Constants.RedisSON_URI_PREFIX.concat(configuration.getHosts()))
                .setPassword(configuration.getPassword())
                .setDatabase(configuration.getDb());
            config.setCodec(new JsonJacksonCodec());
            return Redisson.create(config);
        } else if (RedisType.CLUSTER.equals(configuration.getType())) {
            Config config = new Config();
            config.useClusterServers()
                .setPassword(configuration.getPassword())
                .setNodeAddresses(Arrays.stream(configuration.getHosts().split(","))
                    .map(Constants.RedisSON_URI_PREFIX::concat)
                    .collect(Collectors.toList()));
            config.setCodec(new JsonJacksonCodec());
            return Redisson.create(config);
        } else {
            throw new DcsException(String.format("unknown redis type %s", configuration.getType()));
        }
    }
    /**
     * @return active的RedissonClient
     */
    public RedissonClient getActiveRedisson() {
        return RedissonDcsMap.get(client.getStrategyMode().getState().getActive());
    }
    // Redisson lock使用的demo
    public void lock() throws InterruptedException {
        RedissonClient activeRedisson = this.getActiveRedisson();
        RLock lock = activeRedisson.getLock("lock");
        try {
            if (lock.tryLock()) {
                log.info("lock success-{}", Thread.currentThread());
                Thread.sleep(30000);
            } else {
                log.info("lock fail-{}", Thread.currentThread());
            }
        } finally {
            lock.unlock();
            log.info("unlock success-{}", Thread.currentThread());
        }
    }
}

相关文档