Curator 实现分布式锁

Maven

<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.1</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
注意: 基于zk 3.x

@Configuration
public class CuratorConfig {
    @Bean(initMethod = "start")
    CuratorFramework curatorFrameworkFactory() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("ip:端口号", retryPolicy);
        return client;
    }
}
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: sjx
 * @description:
 */
@RestController
public class LockController {
    @Autowired
    private CuratorFramework curatorFramework;

    public void tets(String id) {
        InterProcessMutex multiLock = new InterProcessMutex(curatorFramework, "/" + id);
        try {
            multiLock.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                multiLock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容