redisLock和redission分布式锁

一、 redisson锁
1、 引入包:
compile “org.redisson:redisson:3.3.2”

@Autowired
RedissonClient redissonClient;
2、 Redisservice获取锁
public RLock getRedLock(String redLockKey) {
return redissonClient.getLock(redLockKey);
}
3、 RedissonClient的bean

@Component
public class RedisProvider {

@Autowired
private RedisProperties redisProperties;



@Bean
public RedissonClient redissonClient() {
    RedisProperties.Cluster cluster = redisProperties.getCluster();
    Config config = new Config();
    if (cluster != null) {
        List nodes = cluster.getNodes();
        Set nodeSet = new HashSet<>();
        for (String node : nodes) {
            nodeSet.add("redis://" + node);
        }
        //集群
        config.useClusterServers().setScanInterval(2000)
            .addNodeAddress(nodeSet.toArray(new String[nodeSet.size()]));
    } else {
        //单机
        final SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress(
                String.format("redis://%s:%s", redisProperties.getHost(), redisProperties.getPort()))
            .setDatabase(redisProperties.getDatabase());

        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            singleServerConfig.setPassword(redisProperties.getPassword());
        }
    }

    return Redisson.create(config);
}

二、 RedisLockRegistry锁
在知道RedisConnectionFactory下
1、 引包
implementation ‘org.springframework.boot:spring-boot-starter-integration’
implementation ‘org.springframework.integration:spring-integration-redis’

2、 RedisProvider.java
@Component
public class RedisProvider {

// @Autowired
// private RedisConnectionFactory factory;

@Bean
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory factory) {
    return new RedisLockRegistry(factory, "asdf");
}

}

3、 RedisService
@Autowired
private RedisLockRegistry redisLockRegistry;

@Override
public Lock getLock(String lockKey) {
return redisLockRegistry.obtain(lockKey);
}

参考:https://blog.csdn.net/qq_18244417/article/details/115987665

你可能感兴趣的:(分布式,redis,java)