1. 分布式锁功能
1.1. 在分布式场景中, 我们为了保证数据的一致性, 经常在程序运行的某一个点需要进行同步操作。Java提供的synchronized或者Reentrantlock等, 是同一个应用程序的多个线程的高并发, 并不是多个服务器(分布式)写同一数据的并发, 这个时候再使用Java提供的锁, 就会出现分布式不同步的问题。我们使用Curator基于ZooKeeper的特性提供的分布式锁来处理分布式场景的数据一致性。
2. 分布式锁实例
2.1. 新建一个名为CuratorDistributed的Java项目, 拷入相关jar

2.2. Java的ReentrantLock锁
package com.fj.zkcurator;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class Look {
public static final ReentrantLock rl = new ReentrantLock();
public static void main(String[] args) {
try {
rl.lock();
db();
} catch (Exception e) {
e.printStackTrace();
} finally {
rl.unlock();
}
}
public static void db() throws Exception {
// 1.获取连接对象
Connection conn = JDBCUtil.getConn();
// 2.创建statement, 跟数据库打交道, 一定需要这个对象
Statement st = conn.createStatement();
// 3.执行查询sql, 获取ResultSet结果集
ResultSet rs = st.executeQuery("select * from product where id = 2");
// 4.使用ResultSet结果集遍历, 下标从1开始
List<Product> products = new ArrayList<Product>();
while(rs.next()) {
products.add(new Product(rs.getInt(1), rs.getString(2), rs.getInt(3)));
}
// 5.查询id为2的商品的数量
int number = products.get(0).getNumber();
File file = new File("Look.txt");
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file, true);
fos.write((System.currentTimeMillis() + ", number = " + number + "\r\n").getBytes());
fos.close();
if(number > 0) {
// 6.执行查询sql
st.executeUpdate("update product set number = " + (--number) + " where id = 2");
}
// 7.释放资源
JDBCUtil.release(conn, st);
}
}
2.3. 在src目录下创建jdbc.properties

2.4. 数据库product表

2.5. Product.java
package com.fj.zkcurator;
import java.io.Serializable;
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer number;
public Product() {
}
public Product(Integer id, String name, Integer number) {
this.id = id;
this.name = name;
this.number = number;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", number=" + number + "]";
}
}
2.6. JDBCUtil.java
package com.fj.zkcurator;
import java.io.IOExcept

本文详细介绍了如何使用ZooKeeper的Curator库实现分布式锁,以确保数据一致性,以及分布式计数器和屏障在多应用并发场景中的应用。通过实例展示了如何在Java中使用Curator的InterProcessMutex、DistributedAtomicInteger和DistributedBarrier进行同步和协调任务。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



