Curator 实现分布式锁

Maven


org.apache.curator
curator-recipes
4.0.1


org.apache.zookeeper
zookeeper



注意: 基于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();
            }
        }

    }
}

你可能感兴趣的:(Curator 实现分布式锁)