1. 数据库乐观锁概述

数据库乐观锁是一种并发控制机制,它假设多个事务之间很少发生冲突,因此不会在读取数据时加锁,而是在更新数据时检查数据是否被其他事务修改过。如果发现数据已被修改,则更新失败,需要重新读取数据并重试。乐观锁通过版本号或时间戳来实现,能够有效解决并发更新问题,提高系统性能。本文将详细介绍数据库乐观锁的原理、实现方案、性能优化技巧以及在Java企业级应用中的最佳实践。

1.1 数据库乐观锁核心价值

  1. 并发控制: 解决多用户并发更新问题
  2. 性能优化: 避免长时间锁定资源
  3. 数据一致性: 保证数据更新的一致性
  4. 系统吞吐量: 提高系统整体吞吐量
  5. 用户体验: 减少用户等待时间

1.2 数据库乐观锁应用场景

  • 库存管理: 防止超卖问题
  • 账户余额: 防止重复扣款
  • 订单状态: 防止重复更新
  • 用户信息: 防止信息覆盖
  • 配置管理: 防止配置冲突

1.3 数据库乐观锁实现方案

  • 版本号机制: 使用version字段控制
  • 时间戳机制: 使用timestamp字段控制
  • 状态字段: 使用status字段控制
  • 自定义字段: 使用业务字段控制
  • 混合机制: 多种机制结合使用

2. 数据库乐观锁基础实现

2.1 数据库乐观锁配置类

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
/**
* 数据库乐观锁配置类
* @author Java实战
*/
@Configuration
@EnableConfigurationProperties(OptimisticLockProperties.class)
public class OptimisticLockConfig {

@Autowired
private OptimisticLockProperties properties;

/**
* 数据库乐观锁服务
* @return 数据库乐观锁服务
*/
@Bean
public OptimisticLockService optimisticLockService() {
return new OptimisticLockService();
}

/**
* 版本号乐观锁服务
* @return 版本号乐观锁服务
*/
@Bean
public VersionOptimisticLockService versionOptimisticLockService() {
return new VersionOptimisticLockService();
}

/**
* 时间戳乐观锁服务
* @return 时间戳乐观锁服务
*/
@Bean
public TimestampOptimisticLockService timestampOptimisticLockService() {
return new TimestampOptimisticLockService();
}

/**
* 状态字段乐观锁服务
* @return 状态字段乐观锁服务
*/
@Bean
public StatusOptimisticLockService statusOptimisticLockService() {
return new StatusOptimisticLockService();
}

/**
* 乐观锁监控服务
* @return 乐观锁监控服务
*/
@Bean
public OptimisticLockMonitorService optimisticLockMonitorService() {
return new OptimisticLockMonitorService();
}

/**
* 乐观锁重试服务
* @return 乐观锁重试服务
*/
@Bean
public OptimisticLockRetryService optimisticLockRetryService() {
return new OptimisticLockRetryService();
}

private static final Logger logger = LoggerFactory.getLogger(OptimisticLockConfig.class);
}

2.2 数据库乐观锁属性配置

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
/**
* 数据库乐观锁属性配置
* @author Java实战
*/
@Data
@ConfigurationProperties(prefix = "optimistic-lock")
public class OptimisticLockProperties {

/**
* 是否启用乐观锁
*/
private boolean enableOptimisticLock = true;

/**
* 版本号配置
*/
private VersionConfig version = new VersionConfig();

/**
* 时间戳配置
*/
private TimestampConfig timestamp = new TimestampConfig();

/**
* 状态字段配置
*/
private StatusConfig status = new StatusConfig();

/**
* 重试配置
*/
private RetryConfig retry = new RetryConfig();

/**
* 是否启用监控
*/
private boolean enableMonitoring = true;

/**
* 监控间隔(毫秒)
*/
private long monitorInterval = 30000;

/**
* 是否启用告警
*/
private boolean enableAlert = true;

/**
* 冲突率告警阈值
*/
private double conflictRateAlertThreshold = 0.1;

/**
* 重试次数告警阈值
*/
private int retryCountAlertThreshold = 5;

/**
* 版本号配置类
*/
@Data
public static class VersionConfig {
/**
* 版本号字段名
*/
private String versionField = "version";

/**
* 版本号初始值
*/
private Long initialVersion = 1L;

/**
* 版本号增量
*/
private Long versionIncrement = 1L;

/**
* 是否启用版本号
*/
private boolean enableVersion = true;

/**
* 版本号类型
*/
private String versionType = "BIGINT";
}

/**
* 时间戳配置类
*/
@Data
public static class TimestampConfig {
/**
* 时间戳字段名
*/
private String timestampField = "update_time";

/**
* 时间戳精度(毫秒)
*/
private int timestampPrecision = 3;

/**
* 是否启用时间戳
*/
private boolean enableTimestamp = false;

/**
* 时间戳类型
*/
private String timestampType = "TIMESTAMP";
}

/**
* 状态字段配置类
*/
@Data
public static class StatusConfig {
/**
* 状态字段名
*/
private String statusField = "status";

/**
* 初始状态
*/
private String initialStatus = "ACTIVE";

/**
* 是否启用状态字段
*/
private boolean enableStatus = false;

/**
* 状态类型
*/
private String statusType = "VARCHAR";
}

/**
* 重试配置类
*/
@Data
public static class RetryConfig {
/**
* 是否启用重试
*/
private boolean enableRetry = true;

/**
* 最大重试次数
*/
private int maxRetryCount = 3;

/**
* 重试间隔(毫秒)
*/
private long retryInterval = 100;

/**
* 重试间隔递增因子
*/
private double retryIntervalMultiplier = 1.5;

/**
* 最大重试间隔(毫秒)
*/
private long maxRetryInterval = 1000;

/**
* 是否启用指数退避
*/
private boolean enableExponentialBackoff = true;
}
}

2.3 数据库乐观锁数据模型类

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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/**
* 数据库乐观锁数据模型类
* @author Java实战
*/
@Data
@Table(name = "optimistic_lock_record")
public class OptimisticLockData {

/**
* 主键ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

/**
* 业务ID
*/
@Column(name = "business_id", length = 64)
private String businessId;

/**
* 业务类型
*/
@Column(name = "business_type", length = 32)
private String businessType;

/**
* 版本号
*/
@Column(name = "version")
private Long version;

/**
* 更新时间
*/
@Column(name = "update_time")
private LocalDateTime updateTime;

/**
* 状态
*/
@Column(name = "status", length = 20)
private String status;

/**
* 数据内容(JSON格式)
*/
@Column(name = "data_content", columnDefinition = "TEXT")
private String dataContent;

/**
* 创建时间
*/
@Column(name = "create_time")
@CreationTimestamp
private LocalDateTime createTime;

/**
* 乐观锁字段
*/
@Version
@Column(name = "optimistic_version")
private Long optimisticVersion;

public OptimisticLockData() {
this.version = 1L;
this.status = "ACTIVE";
this.updateTime = LocalDateTime.now();
}

public OptimisticLockData(String businessId, String businessType) {
this();
this.businessId = businessId;
this.businessType = businessType;
}

/**
* 验证乐观锁数据
* @return 是否有效
*/
public boolean validate() {
if (businessId == null || businessId.isEmpty()) {
return false;
}

if (businessType == null || businessType.isEmpty()) {
return false;
}

if (version == null || version <= 0) {
return false;
}

return true;
}

/**
* 增加版本号
*/
public void incrementVersion() {
this.version++;
this.updateTime = LocalDateTime.now();
}

/**
* 设置数据内容
* @param data 数据对象
*/
public void setDataContent(Object data) {
if (data != null) {
this.dataContent = JSON.toJSONString(data);
}
}

/**
* 获取数据内容
* @param clazz 数据类型
* @return 数据对象
*/
public <T> T getDataContent(Class<T> clazz) {
if (dataContent == null || dataContent.isEmpty()) {
return null;
}
try {
return JSON.parseObject(dataContent, clazz);
} catch (Exception e) {
return null;
}
}

/**
* 检查版本是否匹配
* @param expectedVersion 期望版本
* @return 是否匹配
*/
public boolean isVersionMatch(Long expectedVersion) {
return this.version.equals(expectedVersion);
}

/**
* 检查状态是否有效
* @return 是否有效
*/
public boolean isStatusValid() {
return "ACTIVE".equals(this.status);
}
}

/**
* 乐观锁操作结果类
* @author Java实战
*/
@Data
public class OptimisticLockResult {

private boolean success;
private String businessId;
private String businessType;
private Object result;
private String error;
private long startTime;
private long endTime;
private int retryCount;
private Long version;
private String conflictReason;

public OptimisticLockResult() {
this.success = false;
this.retryCount = 0;
}

public OptimisticLockResult(String businessId, String businessType) {
this();
this.businessId = businessId;
this.businessType = businessType;
}

/**
* 获取操作耗时
* @return 操作耗时(毫秒)
*/
public long getDuration() {
return endTime - startTime;
}

/**
* 是否成功
* @return 是否成功
*/
public boolean isSuccess() {
return success;
}

/**
* 是否发生冲突
* @return 是否发生冲突
*/
public boolean isConflict() {
return conflictReason != null && !conflictReason.isEmpty();
}

/**
* 增加重试次数
*/
public void incrementRetryCount() {
this.retryCount++;
}
}

/**
* 乐观锁状态信息类
* @author Java实战
*/
@Data
public class OptimisticLockStatus {

/**
* 总操作数
*/
private long totalOperations;

/**
* 成功操作数
*/
private long successOperations;

/**
* 失败操作数
*/
private long failureOperations;

/**
* 冲突操作数
*/
private long conflictOperations;

/**
* 重试操作数
*/
private long retryOperations;

/**
* 成功率
*/
private double successRate;

/**
* 冲突率
*/
private double conflictRate;

/**
* 重试率
*/
private double retryRate;

/**
* 平均重试次数
*/
private double averageRetryCount;

/**
* 平均响应时间(毫秒)
*/
private double averageResponseTime;

/**
* 最后检查时间
*/
private Long lastCheckTime;

/**
* 系统状态
*/
private String systemStatus;

public OptimisticLockStatus() {
this.lastCheckTime = System.currentTimeMillis();
this.systemStatus = "HEALTHY";
}

/**
* 计算成功率
* @return 成功率
*/
public double calculateSuccessRate() {
if (totalOperations > 0) {
return (double) successOperations / totalOperations;
}
return 0.0;
}

/**
* 计算冲突率
* @return 冲突率
*/
public double calculateConflictRate() {
if (totalOperations > 0) {
return (double) conflictOperations / totalOperations;
}
return 0.0;
}

/**
* 计算重试率
* @return 重试率
*/
public double calculateRetryRate() {
if (totalOperations > 0) {
return (double) retryOperations / totalOperations;
}
return 0.0;
}

/**
* 是否健康
* @return 是否健康
*/
public boolean isHealthy() {
return successRate >= 0.9 && conflictRate <= 0.2;
}
}

2.4 基础数据库乐观锁服务

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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/**
* 基础数据库乐观锁服务
* @author Java实战
*/
@Service
@Slf4j
public class OptimisticLockService {

@Autowired
private OptimisticLockProperties properties;

@Autowired
private VersionOptimisticLockService versionOptimisticLockService;

@Autowired
private TimestampOptimisticLockService timestampOptimisticLockService;

@Autowired
private StatusOptimisticLockService statusOptimisticLockService;

@Autowired
private OptimisticLockMonitorService optimisticLockMonitorService;

@Autowired
private OptimisticLockRetryService optimisticLockRetryService;

@Autowired
private OptimisticLockRepository optimisticLockRepository;

/**
* 执行乐观锁更新操作
* @param businessId 业务ID
* @param businessType 业务类型
* @param updateFunction 更新函数
* @return 操作结果
*/
public OptimisticLockResult executeOptimisticLockUpdate(String businessId, String businessType,
Function<OptimisticLockData, OptimisticLockData> updateFunction) {
return executeOptimisticLockUpdate(businessId, businessType, updateFunction, null);
}

/**
* 执行乐观锁更新操作(带重试)
* @param businessId 业务ID
* @param businessType 业务类型
* @param updateFunction 更新函数
* @param retryConfig 重试配置
* @return 操作结果
*/
public OptimisticLockResult executeOptimisticLockUpdate(String businessId, String businessType,
Function<OptimisticLockData, OptimisticLockData> updateFunction, RetryConfig retryConfig) {
log.info("执行乐观锁更新操作,业务ID: {}, 业务类型: {}", businessId, businessType);

OptimisticLockResult result = new OptimisticLockResult(businessId, businessType);
result.setStartTime(System.currentTimeMillis());

try {
// 参数验证
validateParameters(businessId, businessType, updateFunction, result);
if (!result.isSuccess()) {
return result;
}

// 使用重试机制
if (retryConfig == null) {
retryConfig = new RetryConfig();
retryConfig.setEnableRetry(properties.getRetry().isEnableRetry());
retryConfig.setMaxRetryCount(properties.getRetry().getMaxRetryCount());
retryConfig.setRetryInterval(properties.getRetry().getRetryInterval());
}

return optimisticLockRetryService.executeWithRetry(result, updateFunction, retryConfig);

} catch (Exception e) {
log.error("乐观锁更新操作执行异常,业务ID: {}, 业务类型: {}", businessId, businessType, e);

result.setSuccess(false);
result.setError("乐观锁更新操作执行异常: " + e.getMessage());
result.setEndTime(System.currentTimeMillis());

// 记录失败指标
optimisticLockMonitorService.recordFailureOperation();

return result;
}
}

/**
* 验证参数
*/
private void validateParameters(String businessId, String businessType,
Function<OptimisticLockData, OptimisticLockData> updateFunction, OptimisticLockResult result) {
if (businessId == null || businessId.isEmpty()) {
result.setSuccess(false);
result.setError("业务ID不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}

if (businessType == null || businessType.isEmpty()) {
result.setSuccess(false);
result.setError("业务类型不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}

if (updateFunction == null) {
result.setSuccess(false);
result.setError("更新函数不能为空");
result.setEndTime(System.currentTimeMillis());
return;
}
}

/**
* 执行单次乐观锁更新
* @param businessId 业务ID
* @param businessType 业务类型
* @param updateFunction 更新函数
* @return 操作结果
*/
public OptimisticLockResult executeSingleOptimisticLockUpdate(String businessId, String businessType,
Function<OptimisticLockData, OptimisticLockData> updateFunction) {
log.info("执行单次乐观锁更新,业务ID: {}, 业务类型: {}", businessId, businessType);

OptimisticLockResult result = new OptimisticLockResult(businessId, businessType);
result.setStartTime(System.currentTimeMillis());

try {
// 获取当前数据
OptimisticLockData currentData = optimisticLockRepository.findByBusinessIdAndBusinessType(businessId, businessType);

if (currentData == null) {
result.setSuccess(false);
result.setError("数据不存在");
result.setEndTime(System.currentTimeMillis());
return result;
}

// 检查数据状态
if (!currentData.isStatusValid()) {
result.setSuccess(false);
result.setError("数据状态无效");
result.setEndTime(System.currentTimeMillis());
return result;
}

// 执行更新函数
OptimisticLockData updatedData = updateFunction.apply(currentData);

if (updatedData == null) {
result.setSuccess(false);
result.setError("更新函数返回空数据");
result.setEndTime(System.currentTimeMillis());
return result;
}

// 增加版本号
updatedData.incrementVersion();

// 尝试更新数据库
boolean updateSuccess = updateWithOptimisticLock(updatedData);

if (updateSuccess) {
result.setSuccess(true);
result.setResult(updatedData);
result.setVersion(updatedData.getVersion());
result.setEndTime(System.currentTimeMillis());

// 记录成功指标
optimisticLockMonitorService.recordSuccessOperation();

log.info("乐观锁更新成功,业务ID: {}, 业务类型: {}, 版本: {}",
businessId, businessType, updatedData.getVersion());
} else {
result.setSuccess(false);
result.setConflictReason("版本冲突");
result.setEndTime(System.currentTimeMillis());

// 记录冲突指标
optimisticLockMonitorService.recordConflictOperation();

log.warn("乐观锁更新冲突,业务ID: {}, 业务类型: {}", businessId, businessType);
}

return result;

} catch (Exception e) {
log.error("单次乐观锁更新异常,业务ID: {}, 业务类型: {}", businessId, businessType, e);

result.setSuccess(false);
result.setError("单次乐观锁更新异常: " + e.getMessage());
result.setEndTime(System.currentTimeMillis());

// 记录失败指标
optimisticLockMonitorService.recordFailureOperation();

return result;
}
}

/**
* 使用乐观锁更新数据
* @param data 更新数据
* @return 是否成功
*/
private boolean updateWithOptimisticLock(OptimisticLockData data) {
try {
// 使用版本号进行乐观锁更新
if (properties.getVersion().isEnableVersion()) {
return versionOptimisticLockService.updateWithVersion(data);
}

// 使用时间戳进行乐观锁更新
if (properties.getTimestamp().isEnableTimestamp()) {
return timestampOptimisticLockService.updateWithTimestamp(data);
}

// 使用状态字段进行乐观锁更新
if (properties.getStatus().isEnableStatus()) {
return statusOptimisticLockService.updateWithStatus(data);
}

// 默认使用JPA的@Version注解
optimisticLockRepository.save(data);
return true;

} catch (OptimisticLockingFailureException e) {
log.warn("乐观锁更新失败,数据已被其他事务修改", e);
return false;
} catch (Exception e) {
log.error("乐观锁更新异常", e);
return false;
}
}

/**
* 获取乐观锁数据
* @param businessId 业务ID
* @param businessType 业务类型
* @return 乐观锁数据
*/
public OptimisticLockData getOptimisticLockData(String businessId, String businessType) {
log.info("获取乐观锁数据,业务ID: {}, 业务类型: {}", businessId, businessType);

try {
return optimisticLockRepository.findByBusinessIdAndBusinessType(businessId, businessType);
} catch (Exception e) {
log.error("获取乐观锁数据异常,业务ID: {}, 业务类型: {}", businessId, businessType, e);
return null;
}
}

/**
* 创建乐观锁数据
* @param businessId 业务ID
* @param businessType 业务类型
* @param dataContent 数据内容
* @return 是否成功
*/
public boolean createOptimisticLockData(String businessId, String businessType, Object dataContent) {
log.info("创建乐观锁数据,业务ID: {}, 业务类型: {}", businessId, businessType);

try {
OptimisticLockData data = new OptimisticLockData(businessId, businessType);
data.setDataContent(dataContent);

optimisticLockRepository.save(data);

log.info("乐观锁数据创建成功,业务ID: {}, 业务类型: {}", businessId, businessType);

return true;
} catch (Exception e) {
log.error("创建乐观锁数据异常,业务ID: {}, 业务类型: {}", businessId, businessType, e);
return false;
}
}

/**
* 删除乐观锁数据
* @param businessId 业务ID
* @param businessType 业务类型
* @return 是否成功
*/
public boolean deleteOptimisticLockData(String businessId, String businessType) {
log.info("删除乐观锁数据,业务ID: {}, 业务类型: {}", businessId, businessType);

try {
optimisticLockRepository.deleteByBusinessIdAndBusinessType(businessId, businessType);

log.info("乐观锁数据删除成功,业务ID: {}, 业务类型: {}", businessId, businessType);

return true;
} catch (Exception e) {
log.error("删除乐观锁数据异常,业务ID: {}, 业务类型: {}", businessId, businessType, e);
return false;
}
}

/**
* 获取乐观锁状态
* @return 乐观锁状态
*/
public OptimisticLockStatus getOptimisticLockStatus() {
log.info("获取乐观锁状态");

try {
return optimisticLockMonitorService.getStatus();
} catch (Exception e) {
log.error("获取乐观锁状态异常", e);
return null;
}
}

/**
* 批量更新乐观锁数据
* @param updateRequests 更新请求列表
* @return 更新结果列表
*/
public List<OptimisticLockResult> batchUpdateOptimisticLockData(List<OptimisticLockUpdateRequest> updateRequests) {
log.info("批量更新乐观锁数据,数量: {}", updateRequests.size());

List<OptimisticLockResult> results = new ArrayList<>();

try {
for (OptimisticLockUpdateRequest request : updateRequests) {
OptimisticLockResult result = executeOptimisticLockUpdate(
request.getBusinessId(),
request.getBusinessType(),
request.getUpdateFunction()
);
results.add(result);
}

log.info("批量更新乐观锁数据完成,成功数量: {}",
results.stream().mapToInt(r -> r.isSuccess() ? 1 : 0).sum());

} catch (Exception e) {
log.error("批量更新乐观锁数据异常", e);
}

return results;
}
}

/**
* 乐观锁更新请求类
* @author Java实战
*/
@Data
public class OptimisticLockUpdateRequest {

/**
* 业务ID
*/
private String businessId;

/**
* 业务类型
*/
private String businessType;

/**
* 更新函数
*/
@JsonIgnore
private Function<OptimisticLockData, OptimisticLockData> updateFunction;

/**
* 重试配置
*/
private RetryConfig retryConfig;

/**
* 扩展属性
*/
private Map<String, Object> extendedProperties;

public OptimisticLockUpdateRequest() {
this.extendedProperties = new HashMap<>();
}

public OptimisticLockUpdateRequest(String businessId, String businessType,
Function<OptimisticLockData, OptimisticLockData> updateFunction) {
this();
this.businessId = businessId;
this.businessType = businessType;
this.updateFunction = updateFunction;
}
}

/**
* 重试配置类
* @author Java实战
*/
@Data
public class RetryConfig {

/**
* 是否启用重试
*/
private boolean enableRetry = true;

/**
* 最大重试次数
*/
private int maxRetryCount = 3;

/**
* 重试间隔(毫秒)
*/
private long retryInterval = 100;

/**
* 重试间隔递增因子
*/
private double retryIntervalMultiplier = 1.5;

/**
* 最大重试间隔(毫秒)
*/
private long maxRetryInterval = 1000;

/**
* 是否启用指数退避
*/
private boolean enableExponentialBackoff = true;

/**
* 计算重试间隔
* @param retryCount 重试次数
* @return 重试间隔
*/
public long calculateRetryInterval(int retryCount) {
if (!enableExponentialBackoff) {
return retryInterval;
}

long interval = (long) (retryInterval * Math.pow(retryIntervalMultiplier, retryCount));
return Math.min(interval, maxRetryInterval);
}
}

3. 高级功能实现

3.1 版本号乐观锁服务

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
266
267
268
269
270
271
272
273
274
275
276
277
/**
* 版本号乐观锁服务
* @author Java实战
*/
@Service
@Slf4j
public class VersionOptimisticLockService {

@Autowired
private OptimisticLockProperties properties;

@Autowired
private OptimisticLockRepository optimisticLockRepository;

@Autowired
private JdbcTemplate jdbcTemplate;

/**
* 使用版本号更新数据
* @param data 更新数据
* @return 是否成功
*/
public boolean updateWithVersion(OptimisticLockData data) {
log.info("使用版本号更新数据,业务ID: {}, 版本: {}", data.getBusinessId(), data.getVersion());

try {
String sql = "UPDATE " + getTableName() +
" SET data_content = ?, version = ?, update_time = ?, status = ? " +
" WHERE business_id = ? AND business_type = ? AND version = ?";

int rows = jdbcTemplate.update(sql,
data.getDataContent(),
data.getVersion(),
data.getUpdateTime(),
data.getStatus(),
data.getBusinessId(),
data.getBusinessType(),
data.getVersion() - 1); // 期望的旧版本号

boolean success = rows > 0;

if (success) {
log.info("版本号更新成功,业务ID: {}, 版本: {}", data.getBusinessId(), data.getVersion());
} else {
log.warn("版本号更新失败,业务ID: {}, 版本: {}", data.getBusinessId(), data.getVersion());
}

return success;

} catch (Exception e) {
log.error("版本号更新异常,业务ID: {}, 版本: {}", data.getBusinessId(), data.getVersion(), e);
return false;
}
}

/**
* 使用版本号批量更新数据
* @param dataList 更新数据列表
* @return 更新成功的数量
*/
public int batchUpdateWithVersion(List<OptimisticLockData> dataList) {
log.info("使用版本号批量更新数据,数量: {}", dataList.size());

int successCount = 0;

try {
String sql = "UPDATE " + getTableName() +
" SET data_content = ?, version = ?, update_time = ?, status = ? " +
" WHERE business_id = ? AND business_type = ? AND version = ?";

List<Object[]> batchArgs = new ArrayList<>();

for (OptimisticLockData data : dataList) {
Object[] args = {
data.getDataContent(),
data.getVersion(),
data.getUpdateTime(),
data.getStatus(),
data.getBusinessId(),
data.getBusinessType(),
data.getVersion() - 1 // 期望的旧版本号
};
batchArgs.add(args);
}

int[] updateCounts = jdbcTemplate.batchUpdate(sql, batchArgs);

for (int count : updateCounts) {
if (count > 0) {
successCount++;
}
}

log.info("版本号批量更新完成,成功数量: {}", successCount);

} catch (Exception e) {
log.error("版本号批量更新异常", e);
}

return successCount;
}

/**
* 检查版本号是否匹配
* @param businessId 业务ID
* @param businessType 业务类型
* @param expectedVersion 期望版本
* @return 是否匹配
*/
public boolean checkVersionMatch(String businessId, String businessType, Long expectedVersion) {
log.info("检查版本号是否匹配,业务ID: {}, 期望版本: {}", businessId, expectedVersion);

try {
String sql = "SELECT version FROM " + getTableName() +
" WHERE business_id = ? AND business_type = ?";

Long currentVersion = jdbcTemplate.queryForObject(sql, Long.class, businessId, businessType);

boolean match = currentVersion != null && currentVersion.equals(expectedVersion);

log.info("版本号检查完成,业务ID: {}, 当前版本: {}, 期望版本: {}, 匹配: {}",
businessId, currentVersion, expectedVersion, match);

return match;

} catch (Exception e) {
log.error("检查版本号是否匹配异常,业务ID: {}", businessId, e);
return false;
}
}

/**
* 获取当前版本号
* @param businessId 业务ID
* @param businessType 业务类型
* @return 当前版本号
*/
public Long getCurrentVersion(String businessId, String businessType) {
log.info("获取当前版本号,业务ID: {}", businessId);

try {
String sql = "SELECT version FROM " + getTableName() +
" WHERE business_id = ? AND business_type = ?";

Long version = jdbcTemplate.queryForObject(sql, Long.class, businessId, businessType);

log.info("当前版本号获取成功,业务ID: {}, 版本: {}", businessId, version);

return version;

} catch (Exception e) {
log.error("获取当前版本号异常,业务ID: {}", businessId, e);
return null;
}
}

/**
* 增加版本号
* @param businessId 业务ID
* @param businessType 业务类型
* @return 是否成功
*/
public boolean incrementVersion(String businessId, String businessType) {
log.info("增加版本号,业务ID: {}", businessId);

try {
String sql = "UPDATE " + getTableName() +
" SET version = version + ?, update_time = ? " +
" WHERE business_id = ? AND business_type = ?";

int rows = jdbcTemplate.update(sql,
properties.getVersion().getVersionIncrement(),
LocalDateTime.now(),
businessId,
businessType);

boolean success = rows > 0;

if (success) {
log.info("版本号增加成功,业务ID: {}", businessId);
} else {
log.warn("版本号增加失败,业务ID: {}", businessId);
}

return success;

} catch (Exception e) {
log.error("增加版本号异常,业务ID: {}", businessId, e);
return false;
}
}

/**
* 重置版本号
* @param businessId 业务ID
* @param businessType 业务类型
* @param newVersion 新版本号
* @return 是否成功
*/
public boolean resetVersion(String businessId, String businessType, Long newVersion) {
log.info("重置版本号,业务ID: {}, 新版本: {}", businessId, newVersion);

try {
String sql = "UPDATE " + getTableName() +
" SET version = ?, update_time = ? " +
" WHERE business_id = ? AND business_type = ?";

int rows = jdbcTemplate.update(sql,
newVersion,
LocalDateTime.now(),
businessId,
businessType);

boolean success = rows > 0;

if (success) {
log.info("版本号重置成功,业务ID: {}, 新版本: {}", businessId, newVersion);
} else {
log.warn("版本号重置失败,业务ID: {}", businessId);
}

return success;

} catch (Exception e) {
log.error("重置版本号异常,业务ID: {}", businessId, e);
return false;
}
}

/**
* 获取版本号统计信息
* @return 统计信息
*/
public Map<String, Object> getVersionStatistics() {
log.info("获取版本号统计信息");

Map<String, Object> statistics = new HashMap<>();

try {
// 总记录数
String totalSql = "SELECT COUNT(*) FROM " + getTableName();
Long totalCount = jdbcTemplate.queryForObject(totalSql, Long.class);
statistics.put("totalCount", totalCount);

// 平均版本号
String avgVersionSql = "SELECT AVG(version) FROM " + getTableName();
Double avgVersion = jdbcTemplate.queryForObject(avgVersionSql, Double.class);
statistics.put("averageVersion", avgVersion);

// 最大版本号
String maxVersionSql = "SELECT MAX(version) FROM " + getTableName();
Long maxVersion = jdbcTemplate.queryForObject(maxVersionSql, Long.class);
statistics.put("maxVersion", maxVersion);

// 最小版本号
String minVersionSql = "SELECT MIN(version) FROM " + getTableName();
Long minVersion = jdbcTemplate.queryForObject(minVersionSql, Long.class);
statistics.put("minVersion", minVersion);

log.info("版本号统计信息获取成功,总记录数: {}, 平均版本: {}, 最大版本: {}, 最小版本: {}",
totalCount, avgVersion, maxVersion, minVersion);

} catch (Exception e) {
log.error("获取版本号统计信息异常", e);
}

return statistics;
}

/**
* 获取表名
* @return 表名
*/
private String getTableName() {
return "optimistic_lock_record";
}
}

3.2 时间戳乐观锁服务

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
/**
* 时间戳乐观锁服务
* @author Java实战
*/
@Service
@Slf4j
public class TimestampOptimisticLockService {

@Autowired
private OptimisticLockProperties properties;

@Autowired
private OptimisticLockRepository optimisticLockRepository;

@Autowired
private JdbcTemplate jdbcTemplate;

/**
* 使用时间戳更新数据
* @param data 更新数据
* @return 是否成功
*/
public boolean updateWithTimestamp(OptimisticLockData data) {
log.info("使用时间戳更新数据,业务ID: {}", data.getBusinessId());

try {
String sql = "UPDATE " + getTableName() +
" SET data_content = ?, version = ?, update_time = ?, status = ? " +
" WHERE business_id = ? AND business_type = ? AND update_time = ?";

int rows = jdbcTemplate.update(sql,
data.getDataContent(),
data.getVersion(),
data.getUpdateTime(),
data.getStatus(),
data.getBusinessId(),
data.getBusinessType(),
data.getUpdateTime().minusSeconds(1)); // 期望的旧时间戳

boolean success = rows > 0;

if (success) {
log.info("时间戳更新成功,业务ID: {}", data.getBusinessId());
} else {
log.warn("时间戳更新失败,业务ID: {}", data.getBusinessId());
}

return success;

} catch (Exception e) {
log.error("时间戳更新异常,业务ID: {}", data.getBusinessId(), e);
return false;
}
}

/**
* 使用时间戳批量更新数据
* @param dataList 更新数据列表
* @return 更新成功的数量
*/
public int batchUpdateWithTimestamp(List<OptimisticLockData> dataList) {
log.info("使用时间戳批量更新数据,数量: {}", dataList.size());

int successCount = 0;

try {
String sql = "UPDATE " + getTableName() +
" SET data_content = ?, version = ?, update_time = ?, status = ? " +
" WHERE business_id = ? AND business_type = ? AND update_time = ?";

List<Object[]> batchArgs = new ArrayList<>();

for (OptimisticLockData data : dataList) {
Object[] args = {
data.getDataContent(),
data.getVersion(),
data.getUpdateTime(),
data.getStatus(),
data.getBusinessId(),
data.getBusinessType(),
data.getUpdateTime().minusSeconds(1) // 期望的旧时间戳
};
batchArgs.add(args);
}

int[] updateCounts = jdbcTemplate.batchUpdate(sql, batchArgs);

for (int count : updateCounts) {
if (count > 0) {
successCount++;
}
}

log.info("时间戳批量更新完成,成功数量: {}", successCount);

} catch (Exception e) {
log.error("时间戳批量更新异常", e);
}

return successCount;
}

/**
* 检查时间戳是否匹配
* @param businessId 业务ID
* @param businessType 业务类型
* @param expectedTimestamp 期望时间戳
* @return 是否匹配
*/
public boolean checkTimestampMatch(String businessId, String businessType, LocalDateTime expectedTimestamp) {
log.info("检查时间戳是否匹配,业务ID: {}, 期望时间戳: {}", businessId, expectedTimestamp);

try {
String sql = "SELECT update_time FROM " + getTableName() +
" WHERE business_id = ? AND business_type = ?";

LocalDateTime currentTimestamp = jdbcTemplate.queryForObject(sql, LocalDateTime.class, businessId, businessType);

boolean match = currentTimestamp != null && currentTimestamp.equals(expectedTimestamp);

log.info("时间戳检查完成,业务ID: {}, 当前时间戳: {}, 期望时间戳: {}, 匹配: {}",
businessId, currentTimestamp, expectedTimestamp, match);

return match;

} catch (Exception e) {
log.error("检查时间戳是否匹配异常,业务ID: {}", businessId, e);
return false;
}
}

/**
* 获取当前时间戳
* @param businessId 业务ID
* @param businessType 业务类型
* @return 当前时间戳
*/
public LocalDateTime getCurrentTimestamp(String businessId, String businessType) {
log.info("获取当前时间戳,业务ID: {}", businessId);

try {
String sql = "SELECT update_time FROM " + getTableName() +
" WHERE business_id = ? AND business_type = ?";

LocalDateTime timestamp = jdbcTemplate.queryForObject(sql, LocalDateTime.class, businessId, businessType);

log.info("当前时间戳获取成功,业务ID: {}, 时间戳: {}", businessId, timestamp);

return timestamp;

} catch (Exception e) {
log.error("获取当前时间戳异常,业务ID: {}", businessId, e);
return null;
}
}

/**
* 更新时间戳
* @param businessId 业务ID
* @param businessType 业务类型
* @return 是否成功
*/
public boolean updateTimestamp(String businessId, String businessType) {
log.info("更新时间戳,业务ID: {}", businessId);

try {
String sql = "UPDATE " + getTableName() +
" SET update_time = ? " +
" WHERE business_id = ? AND business_type = ?";

int rows = jdbcTemplate.update(sql,
LocalDateTime.now(),
businessId,
businessType);

boolean success = rows > 0;

if (success) {
log.info("时间戳更新成功,业务ID: {}", businessId);
} else {
log.warn("时间戳更新失败,业务ID: {}", businessId);
}

return success;

} catch (Exception e) {
log.error("更新时间戳异常,业务ID: {}", businessId, e);
return false;
}
}

/**
* 获取时间戳统计信息
* @return 统计信息
*/
public Map<String, Object> getTimestampStatistics() {
log.info("获取时间戳统计信息");

Map<String, Object> statistics = new HashMap<>();

try {
// 总记录数
String totalSql = "SELECT COUNT(*) FROM " + getTableName();
Long totalCount = jdbcTemplate.queryForObject(totalSql, Long.class);
statistics.put("totalCount", totalCount);

// 最新时间戳
String latestTimestampSql = "SELECT MAX(update_time) FROM " + getTableName();
LocalDateTime latestTimestamp = jdbcTemplate.queryForObject(latestTimestampSql, LocalDateTime.class);
statistics.put("latestTimestamp", latestTimestamp);

// 最早时间戳
String earliestTimestampSql = "SELECT MIN(update_time) FROM " + getTableName();
LocalDateTime earliestTimestamp = jdbcTemplate.queryForObject(earliestTimestampSql, LocalDateTime.class);
statistics.put("earliestTimestamp", earliestTimestamp);

// 今日更新数量
LocalDate today = LocalDate.now();
LocalDateTime startOfDay = today.atStartOfDay();
LocalDateTime endOfDay = today.plusDays(1).atStartOfDay();

String todayUpdateSql = "SELECT COUNT(*) FROM " + getTableName() +
" WHERE update_time BETWEEN ? AND ?";
Long todayUpdateCount = jdbcTemplate.queryForObject(todayUpdateSql, Long.class, startOfDay, endOfDay);
statistics.put("todayUpdateCount", todayUpdateCount);

log.info("时间戳统计信息获取成功,总记录数: {}, 最新时间戳: {}, 最早时间戳: {}, 今日更新: {}",
totalCount, latestTimestamp, earliestTimestamp, todayUpdateCount);

} catch (Exception e) {
log.error("获取时间戳统计信息异常", e);
}

return statistics;
}

/**
* 获取表名
* @return 表名
*/
private String getTableName() {
return "optimistic_lock_record";
}
}

4. 数据库乐观锁控制器

4.1 数据库乐观锁REST控制器

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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* 数据库乐观锁REST控制器
* @author Java实战
*/
@RestController
@RequestMapping("/api/optimistic-lock")
@Slf4j
public class OptimisticLockController {

@Autowired
private OptimisticLockService optimisticLockService;

@Autowired
private OptimisticLockMonitorService optimisticLockMonitorService;

/**
* 执行乐观锁更新操作
* @param request 乐观锁更新请求
* @return 操作结果
*/
@PostMapping("/update")
public ResponseEntity<OptimisticLockResult> executeOptimisticLockUpdate(@RequestBody OptimisticLockUpdateRequest request) {
try {
log.info("接收到乐观锁更新请求,业务ID: {}", request.getBusinessId());

// 参数验证
if (request.getBusinessId() == null || request.getBusinessId().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getBusinessType() == null || request.getBusinessType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

OptimisticLockResult result = optimisticLockService.executeOptimisticLockUpdate(
request.getBusinessId(),
request.getBusinessType(),
request.getUpdateFunction(),
request.getRetryConfig()
);

return ResponseEntity.ok(result);

} catch (Exception e) {
log.error("乐观锁更新操作执行失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取乐观锁数据
* @param businessId 业务ID
* @param businessType 业务类型
* @return 乐观锁数据
*/
@GetMapping("/data")
public ResponseEntity<OptimisticLockData> getOptimisticLockData(
@RequestParam String businessId,
@RequestParam String businessType) {
try {
log.info("接收到获取乐观锁数据请求,业务ID: {}", businessId);

if (businessId == null || businessId.isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (businessType == null || businessType.isEmpty()) {
return ResponseEntity.badRequest().build();
}

OptimisticLockData data = optimisticLockService.getOptimisticLockData(businessId, businessType);

if (data != null) {
return ResponseEntity.ok(data);
} else {
return ResponseEntity.notFound().build();
}

} catch (Exception e) {
log.error("获取乐观锁数据失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 创建乐观锁数据
* @param request 创建请求
* @return 是否成功
*/
@PostMapping("/create")
public ResponseEntity<Boolean> createOptimisticLockData(@RequestBody OptimisticLockCreateRequest request) {
try {
log.info("接收到创建乐观锁数据请求,业务ID: {}", request.getBusinessId());

if (request.getBusinessId() == null || request.getBusinessId().isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (request.getBusinessType() == null || request.getBusinessType().isEmpty()) {
return ResponseEntity.badRequest().build();
}

boolean success = optimisticLockService.createOptimisticLockData(
request.getBusinessId(),
request.getBusinessType(),
request.getDataContent()
);

return ResponseEntity.ok(success);

} catch (Exception e) {
log.error("创建乐观锁数据失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 删除乐观锁数据
* @param businessId 业务ID
* @param businessType 业务类型
* @return 是否成功
*/
@DeleteMapping("/data")
public ResponseEntity<Boolean> deleteOptimisticLockData(
@RequestParam String businessId,
@RequestParam String businessType) {
try {
log.info("接收到删除乐观锁数据请求,业务ID: {}", businessId);

if (businessId == null || businessId.isEmpty()) {
return ResponseEntity.badRequest().build();
}

if (businessType == null || businessType.isEmpty()) {
return ResponseEntity.badRequest().build();
}

boolean success = optimisticLockService.deleteOptimisticLockData(businessId, businessType);

return ResponseEntity.ok(success);

} catch (Exception e) {
log.error("删除乐观锁数据失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 批量更新乐观锁数据
* @param request 批量更新请求
* @return 更新结果列表
*/
@PostMapping("/batch-update")
public ResponseEntity<List<OptimisticLockResult>> batchUpdateOptimisticLockData(@RequestBody BatchUpdateRequest request) {
try {
log.info("接收到批量更新乐观锁数据请求,数量: {}", request.getUpdateRequests().size());

if (request.getUpdateRequests() == null || request.getUpdateRequests().isEmpty()) {
return ResponseEntity.badRequest().build();
}

List<OptimisticLockResult> results = optimisticLockService.batchUpdateOptimisticLockData(request.getUpdateRequests());

return ResponseEntity.ok(results);

} catch (Exception e) {
log.error("批量更新乐观锁数据失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取乐观锁状态
* @return 乐观锁状态
*/
@GetMapping("/status")
public ResponseEntity<OptimisticLockStatus> getOptimisticLockStatus() {
try {
log.info("接收到获取乐观锁状态请求");

OptimisticLockStatus status = optimisticLockService.getOptimisticLockStatus();

return ResponseEntity.ok(status);

} catch (Exception e) {
log.error("获取乐观锁状态失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 获取乐观锁监控指标
* @return 监控指标
*/
@GetMapping("/metrics")
public ResponseEntity<OptimisticLockMetrics> getOptimisticLockMetrics() {
try {
OptimisticLockMetrics metrics = optimisticLockMonitorService.getMetrics();
return ResponseEntity.ok(metrics);
} catch (Exception e) {
log.error("获取乐观锁监控指标失败", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}

/**
* 健康检查
* @return 健康状态
*/
@GetMapping("/health")
public ResponseEntity<Map<String, Object>> healthCheck() {
try {
Map<String, Object> health = new HashMap<>();

OptimisticLockStatus status = optimisticLockService.getOptimisticLockStatus();

health.put("status", status != null && status.isHealthy() ? "UP" : "DOWN");
health.put("timestamp", System.currentTimeMillis());
health.put("details", status);

return ResponseEntity.ok(health);

} catch (Exception e) {
log.error("健康检查失败", e);

Map<String, Object> health = new HashMap<>();
health.put("status", "DOWN");
health.put("timestamp", System.currentTimeMillis());
health.put("error", e.getMessage());

return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(health);
}
}
}

/**
* 乐观锁创建请求类
* @author Java实战
*/
@Data
public class OptimisticLockCreateRequest {

/**
* 业务ID
*/
@NotBlank(message = "业务ID不能为空")
private String businessId;

/**
* 业务类型
*/
@NotBlank(message = "业务类型不能为空")
private String businessType;

/**
* 数据内容
*/
private Object dataContent;

/**
* 扩展属性
*/
private Map<String, Object> extendedProperties;

public OptimisticLockCreateRequest() {
this.extendedProperties = new HashMap<>();
}
}

/**
* 批量更新请求类
* @author Java实战
*/
@Data
public class BatchUpdateRequest {

/**
* 更新请求列表
*/
@NotEmpty(message = "更新请求列表不能为空")
@Size(max = 100, message = "批量更新数量不能超过100个")
private List<OptimisticLockUpdateRequest> updateRequests;

/**
* 扩展属性
*/
private Map<String, Object> extendedProperties;

public BatchUpdateRequest() {
this.extendedProperties = new HashMap<>();
}
}

5. 总结

5.1 数据库乐观锁最佳实践

  1. 合理选择锁机制: 根据业务场景选择合适的乐观锁实现
  2. 版本号管理: 合理设计版本号字段和更新策略
  3. 冲突处理: 建立完善的冲突检测和重试机制
  4. 性能优化: 优化数据库查询和更新操作
  5. 监控告警: 实时监控乐观锁状态和性能

5.2 性能优化建议

  • 索引优化: 为乐观锁字段建立合适的索引
  • 批量操作: 支持批量乐观锁更新
  • 连接池优化: 优化数据库连接池配置
  • 缓存策略: 合理使用缓存减少数据库访问
  • 异步处理: 异步处理非关键路径

5.3 运维管理要点

  • 实时监控: 监控乐观锁状态和性能
  • 冲突分析: 分析冲突原因和频率
  • 重试策略: 优化重试机制和参数
  • 日志管理: 完善日志记录和分析
  • 性能调优: 根据监控数据优化性能

通过本文的数据库乐观锁Java实战指南,您可以掌握乐观锁的原理、实现方案、性能优化技巧以及在企业级应用中的最佳实践,构建高效、可靠的数据库乐观锁系统!