1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
| import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
// 📊 CAP理论中的一致性模型实现
enum ConsistencyLevel {
LINEARIZABLE("线性一致性", "最强一致性,实时同步"),
SEQUENTIAL("顺序一致性", "操作顺序一致,允许延迟"),
CAUSAL("因果一致性", "保证因果关系,性能较好"),
EVENTUAL("最终一致性", "最终同步,性能最佳"),
WEAK("弱一致性", "无一致性保证,最高性能");
private final String description;
private final String detail;
ConsistencyLevel(String description, String detail) {
this.description = description;
this.detail = detail;
}
public String getDescription() {
return description;
}
public String getDetail() {
return detail;
}
}
class DataEntry {
private String value;
private long timestamp;
private String writeId;
public DataEntry(String value, long timestamp, String writeId) {
this.value = value;
this.timestamp = timestamp;
this.writeId = writeId;
}
// Getters
public String getValue() { return value; }
public long getTimestamp() { return timestamp; }
public String getWriteId() { return writeId; }
}
class Replica {
private String id;
private Map<String, DataEntry> data;
private Map<String, Long> versionVector;
private boolean isAvailable;
private ReentrantLock lock;
public Replica(String replicaId) {
this.id = replicaId;
this.data = new ConcurrentHashMap<>();
this.versionVector = new ConcurrentHashMap<>();
this.isAvailable = true;
this.lock = new ReentrantLock();
}
/**
* 副本写操作
*/
public boolean write(String key, String value, long timestamp, String writeId) throws Exception {
if (!isAvailable) {
throw new Exception("副本 " + id + " 不可用");
}
lock.lock();
try {
DataEntry entry = new DataEntry(value, timestamp, writeId);
data.put(key, entry);
// 更新版本向量
versionVector.put(writeId, timestamp);
return true;
} finally {
lock.unlock();
}
}
/**
* 副本读操作
*/
public DataEntry read(String key) throws Exception {
if (!isAvailable) {
throw new Exception("副本 " + id + " 不可用");
}
return data.get(key);
}
public String getId() { return id; }
public ReentrantLock getLock() { return lock; }
}
public class DistributedDataStore {
private List<Replica> replicas;
private ConsistencyLevel consistencyLevel;
private Map<String, Long> versionVector;
private ExecutorService executor;
public DistributedDataStore(List<Replica> replicas, ConsistencyLevel consistencyLevel) {
this.replicas = replicas;
this.consistencyLevel = consistencyLevel;
this.versionVector = new ConcurrentHashMap<>();
this.executor = Executors.newCachedThreadPool();
}
/**
* 写操作实现不同一致性级别
*/
public boolean write(String key, String value, String clientId) {
long timestamp = System.currentTimeMillis();
String writeId = UUID.randomUUID().toString();
switch (consistencyLevel) {
case STRONG:
return strongConsistencyWrite(key, value, timestamp, writeId);
case EVENTUAL:
return eventualConsistencyWrite(key, value, timestamp, writeId);
case WEAK:
return weakConsistencyWrite(key, value, timestamp, writeId);
default:
return false;
}
}
/**
* 强一致性写操作 - 需要所有副本确认
*/
private boolean strongConsistencyWrite(String key, String value, long timestamp, String writeId) {
int successfulWrites = 0;
int requiredWrites = replicas.size();
for (Replica replica : replicas) {
try {
replica.getLock().lock();
try {
if (replica.write(key, value, timestamp, writeId)) {
successfulWrites++;
}
} finally {
replica.getLock().unlock();
}
} catch (Exception e) {
System.out.println("写入副本 " + replica.getId() + " 失败: " + e.getMessage());
}
}
if (successfulWrites == requiredWrites) {
System.out.println("强一致性写入成功: " + key + " = " + value);
return true;
} else {
// 回滚操作
rollbackWrite(key, writeId);
return false;
}
}
/**
* 最终一致性写操作 - 异步复制
*/
private boolean eventualConsistencyWrite(String key, String value, long timestamp, String writeId) {
if (replicas.isEmpty()) return false;
Replica primaryReplica = replicas.get(0);
// 主副本写入
try {
primaryReplica.getLock().lock();
try {
boolean success = primaryReplica.write(key, value, timestamp, writeId);
if (success) {
// 异步复制到其他副本
List<Replica> secondaryReplicas = replicas.subList(1, replicas.size());
asyncReplicate(key, value, timestamp, writeId, secondaryReplicas);
return true;
}
} finally {
primaryReplica.getLock().unlock();
}
} catch (Exception e) {
System.out.println("主副本写入失败: " + e.getMessage());
}
return false;
}
/**
* 弱一致性写操作
*/
private boolean weakConsistencyWrite(String key, String value, long timestamp, String writeId) {
// 简化实现:只写入一个副本
if (!replicas.isEmpty()) {
try {
return replicas.get(0).write(key, value, timestamp, writeId);
} catch (Exception e) {
System.out.println("弱一致性写入失败: " + e.getMessage());
}
}
return false;
}
/**
* 异步复制到副本
*/
private void asyncReplicate(String key, String value, long timestamp, String writeId,
List<Replica> replicasToUpdate) {
for (Replica replica : replicasToUpdate) {
executor.submit(() -> {
try {
Thread.sleep(100); // 模拟网络延迟
replica.getLock().lock();
try {
replica.write(key, value, timestamp, writeId);
System.out.println("异步复制到副本 " + replica.getId() + " 成功");
} finally {
replica.getLock().unlock();
}
} catch (Exception e) {
System.out.println("异步复制到副本 " + replica.getId() + " 失败: " + e.getMessage());
}
});
}
}
/**
* 回滚写操作
*/
private void rollbackWrite(String key, String writeId) {
System.out.println("正在回滚写操作: " + writeId);
// 简化实现,实际中需要复杂的回滚逻辑
}
public void shutdown() {
executor.shutdown();
}
// 使用示例
public static void main(String[] args) throws InterruptedException {
List<Replica> replicas = Arrays.asList(
new Replica("replica_0"),
new Replica("replica_1"),
new Replica("replica_2")
);
// 强一致性存储
DistributedDataStore strongStore = new DistributedDataStore(replicas, ConsistencyLevel.STRONG);
System.out.println("=== 强一致性测试 ===");
strongStore.write("user:1", "Alice", "client_1");
// 最终一致性存储
DistributedDataStore eventualStore = new DistributedDataStore(replicas, ConsistencyLevel.EVENTUAL);
System.out.println("\n=== 最终一致性测试 ===");
eventualStore.write("user:2", "Bob", "client_2");
Thread.sleep(1000); // 等待异步复制完成
strongStore.shutdown();
eventualStore.shutdown();
}
}
|