更新时间:2024-10-23 GMT+08:00
分享

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());
        }
    }
}

相关文档