1. 系统模型架构概述

系统模型是软件架构设计的核心基础,它通过抽象和建模的方式描述系统的结构、行为和交互。作为架构师,深入理解系统建模的原理、方法和实践,对于设计高质量、可维护、可扩展的企业级系统至关重要。本文从架构师的角度深入分析系统建模的实现原理、设计模式和最佳实践,为企业级应用提供完整的系统建模解决方案。

1.1 系统模型架构设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
┌─────────────────────────────────────────────────────────┐
│ 业务层 │
│ (领域模型、业务规则、用例模型) │
├─────────────────────────────────────────────────────────┤
│ 应用层 │
│ (应用服务、领域服务、工作流) │
├─────────────────────────────────────────────────────────┤
│ 领域层 │
│ (实体、值对象、聚合根、领域事件) │
├─────────────────────────────────────────────────────────┤
│ 基础设施层 │
│ (数据访问、外部服务、消息队列) │
├─────────────────────────────────────────────────────────┤
│ 技术层 │
│ (框架、中间件、工具库) │
└─────────────────────────────────────────────────────────┘

1.2 系统模型关键指标

  1. 完整性: 模型覆盖度、业务规则完整性
  2. 一致性: 模型内部一致性、跨模型一致性
  3. 可维护性: 模型复杂度、变更影响范围
  4. 可扩展性: 模型扩展能力、新需求适应性
  5. 可理解性: 模型清晰度、文档完整性

2. 领域建模深度实现

2.1 领域驱动设计(DDD)实现

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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/**
* 领域驱动设计核心组件
* 实现DDD的核心概念和模式
*/
public class DomainDrivenDesignFramework {

/**
* 聚合根基类
*/
public abstract class AggregateRoot<ID> {
private ID id;
private List<DomainEvent> domainEvents;
private int version;

public AggregateRoot(ID id) {
this.id = id;
this.domainEvents = new ArrayList<>();
this.version = 0;
}

protected void addDomainEvent(DomainEvent event) {
this.domainEvents.add(event);
}

public List<DomainEvent> getDomainEvents() {
return new ArrayList<>(domainEvents);
}

public void clearDomainEvents() {
this.domainEvents.clear();
}

public void incrementVersion() {
this.version++;
}

public int getVersion() {
return version;
}

public ID getId() {
return id;
}
}

/**
* 实体基类
*/
public abstract class Entity<ID> {
private ID id;

public Entity(ID id) {
this.id = id;
}

public ID getId() {
return id;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Entity<?> entity = (Entity<?>) obj;
return Objects.equals(id, entity.id);
}

@Override
public int hashCode() {
return Objects.hash(id);
}
}

/**
* 值对象基类
*/
public abstract class ValueObject {
@Override
public abstract boolean equals(Object obj);

@Override
public abstract int hashCode();
}

/**
* 领域事件
*/
public abstract class DomainEvent {
private String eventId;
private long timestamp;
private String aggregateId;
private int aggregateVersion;

public DomainEvent(String aggregateId) {
this.eventId = UUID.randomUUID().toString();
this.timestamp = System.currentTimeMillis();
this.aggregateId = aggregateId;
}

public String getEventId() { return eventId; }
public long getTimestamp() { return timestamp; }
public String getAggregateId() { return aggregateId; }
public int getAggregateVersion() { return aggregateVersion; }
public void setAggregateVersion(int aggregateVersion) { this.aggregateVersion = aggregateVersion; }
}

/**
* 领域服务接口
*/
public interface DomainService {
// 领域服务方法
}

/**
* 仓储接口
*/
public interface Repository<T extends AggregateRoot<ID>, ID> {
T findById(ID id);
void save(T aggregate);
void remove(T aggregate);
List<T> findAll();
}

/**
* 规格模式
*/
public interface Specification<T> {
boolean isSatisfiedBy(T candidate);
Specification<T> and(Specification<T> other);
Specification<T> or(Specification<T> other);
Specification<T> not();
}

/**
* 抽象规格类
*/
public abstract class AbstractSpecification<T> implements Specification<T> {
@Override
public Specification<T> and(Specification<T> other) {
return new AndSpecification<>(this, other);
}

@Override
public Specification<T> or(Specification<T> other) {
return new OrSpecification<>(this, other);
}

@Override
public Specification<T> not() {
return new NotSpecification<>(this);
}
}

/**
* 组合规格实现
*/
public class AndSpecification<T> extends AbstractSpecification<T> {
private Specification<T> left;
private Specification<T> right;

public AndSpecification(Specification<T> left, Specification<T> right) {
this.left = left;
this.right = right;
}

@Override
public boolean isSatisfiedBy(T candidate) {
return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate);
}
}

public class OrSpecification<T> extends AbstractSpecification<T> {
private Specification<T> left;
private Specification<T> right;

public OrSpecification(Specification<T> left, Specification<T> right) {
this.left = left;
this.right = right;
}

@Override
public boolean isSatisfiedBy(T candidate) {
return left.isSatisfiedBy(candidate) || right.isSatisfiedBy(candidate);
}
}

public class NotSpecification<T> extends AbstractSpecification<T> {
private Specification<T> specification;

public NotSpecification(Specification<T> specification) {
this.specification = specification;
}

@Override
public boolean isSatisfiedBy(T candidate) {
return !specification.isSatisfiedBy(candidate);
}
}
}

/**
* 用户聚合根示例
*/
public class User extends AggregateRoot<UserId> {
private String username;
private String email;
private UserStatus status;
private Profile profile;
private List<Role> roles;

public User(UserId id, String username, String email) {
super(id);
this.username = username;
this.email = email;
this.status = UserStatus.ACTIVE;
this.roles = new ArrayList<>();

// 发布领域事件
addDomainEvent(new UserCreatedEvent(id.getValue(), username, email));
}

public void changeEmail(String newEmail) {
if (isValidEmail(newEmail)) {
String oldEmail = this.email;
this.email = newEmail;
addDomainEvent(new UserEmailChangedEvent(getId().getValue(), oldEmail, newEmail));
} else {
throw new InvalidEmailException("Invalid email format: " + newEmail);
}
}

public void activate() {
if (this.status == UserStatus.INACTIVE) {
this.status = UserStatus.ACTIVE;
addDomainEvent(new UserActivatedEvent(getId().getValue()));
}
}

public void deactivate() {
if (this.status == UserStatus.ACTIVE) {
this.status = UserStatus.INACTIVE;
addDomainEvent(new UserDeactivatedEvent(getId().getValue()));
}
}

public void assignRole(Role role) {
if (!roles.contains(role)) {
roles.add(role);
addDomainEvent(new UserRoleAssignedEvent(getId().getValue(), role.getName()));
}
}

public void removeRole(Role role) {
if (roles.remove(role)) {
addDomainEvent(new UserRoleRemovedEvent(getId().getValue(), role.getName()));
}
}

private boolean isValidEmail(String email) {
return email != null && email.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
}

// getters
public String getUsername() { return username; }
public String getEmail() { return email; }
public UserStatus getStatus() { return status; }
public Profile getProfile() { return profile; }
public List<Role> getRoles() { return roles; }
}

/**
* 用户ID值对象
*/
public class UserId extends ValueObject {
private String value;

public UserId(String value) {
if (value == null || value.trim().isEmpty()) {
throw new IllegalArgumentException("User ID cannot be null or empty");
}
this.value = value;
}

public String getValue() {
return value;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
UserId userId = (UserId) obj;
return Objects.equals(value, userId.value);
}

@Override
public int hashCode() {
return Objects.hash(value);
}

@Override
public String toString() {
return value;
}
}

/**
* 用户状态枚举
*/
public enum UserStatus {
ACTIVE, INACTIVE, SUSPENDED, PENDING
}

/**
* 用户配置文件值对象
*/
public class Profile extends ValueObject {
private String firstName;
private String lastName;
private String phoneNumber;
private Address address;

public Profile(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public String getFullName() {
return firstName + " " + lastName;
}

// getters and setters
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getPhoneNumber() { return phoneNumber; }
public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address; }

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Profile profile = (Profile) obj;
return Objects.equals(firstName, profile.firstName) &&
Objects.equals(lastName, profile.lastName) &&
Objects.equals(phoneNumber, profile.phoneNumber) &&
Objects.equals(address, profile.address);
}

@Override
public int hashCode() {
return Objects.hash(firstName, lastName, phoneNumber, address);
}
}

/**
* 地址值对象
*/
public class Address extends ValueObject {
private String street;
private String city;
private String state;
private String zipCode;
private String country;

public Address(String street, String city, String state, String zipCode, String country) {
this.street = street;
this.city = city;
this.state = state;
this.zipCode = zipCode;
this.country = country;
}

// getters
public String getStreet() { return street; }
public String getCity() { return city; }
public String getState() { return state; }
public String getZipCode() { return zipCode; }
public String getCountry() { return country; }

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Address address = (Address) obj;
return Objects.equals(street, address.street) &&
Objects.equals(city, address.city) &&
Objects.equals(state, address.state) &&
Objects.equals(zipCode, address.zipCode) &&
Objects.equals(country, address.country);
}

@Override
public int hashCode() {
return Objects.hash(street, city, state, zipCode, country);
}
}

/**
* 角色实体
*/
public class Role extends Entity<RoleId> {
private String name;
private String description;
private Set<Permission> permissions;

public Role(RoleId id, String name, String description) {
super(id);
this.name = name;
this.description = description;
this.permissions = new HashSet<>();
}

public void addPermission(Permission permission) {
permissions.add(permission);
}

public void removePermission(Permission permission) {
permissions.remove(permission);
}

public boolean hasPermission(Permission permission) {
return permissions.contains(permission);
}

// getters
public String getName() { return name; }
public String getDescription() { return description; }
public Set<Permission> getPermissions() { return permissions; }
}

/**
* 角色ID值对象
*/
public class RoleId extends ValueObject {
private String value;

public RoleId(String value) {
this.value = value;
}

public String getValue() {
return value;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
RoleId roleId = (RoleId) obj;
return Objects.equals(value, roleId.value);
}

@Override
public int hashCode() {
return Objects.hash(value);
}
}

/**
* 权限枚举
*/
public enum Permission {
READ, WRITE, DELETE, ADMIN
}

/**
* 领域事件实现
*/
public class UserCreatedEvent extends DomainEvent {
private String username;
private String email;

public UserCreatedEvent(String aggregateId, String username, String email) {
super(aggregateId);
this.username = username;
this.email = email;
}

public String getUsername() { return username; }
public String getEmail() { return email; }
}

public class UserEmailChangedEvent extends DomainEvent {
private String oldEmail;
private String newEmail;

public UserEmailChangedEvent(String aggregateId, String oldEmail, String newEmail) {
super(aggregateId);
this.oldEmail = oldEmail;
this.newEmail = newEmail;
}

public String getOldEmail() { return oldEmail; }
public String getNewEmail() { return newEmail; }
}

public class UserActivatedEvent extends DomainEvent {
public UserActivatedEvent(String aggregateId) {
super(aggregateId);
}
}

public class UserDeactivatedEvent extends DomainEvent {
public UserDeactivatedEvent(String aggregateId) {
super(aggregateId);
}
}

public class UserRoleAssignedEvent extends DomainEvent {
private String roleName;

public UserRoleAssignedEvent(String aggregateId, String roleName) {
super(aggregateId);
this.roleName = roleName;
}

public String getRoleName() { return roleName; }
}

public class UserRoleRemovedEvent extends DomainEvent {
private String roleName;

public UserRoleRemovedEvent(String aggregateId, String roleName) {
super(aggregateId);
this.roleName = roleName;
}

public String getRoleName() { return roleName; }
}

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
/**
* 用户领域服务
*/
public class UserDomainService implements DomainService {
private final UserRepository userRepository;
private final EmailService emailService;

public UserDomainService(UserRepository userRepository, EmailService emailService) {
this.userRepository = userRepository;
this.emailService = emailService;
}

/**
* 检查用户名是否唯一
*/
public boolean isUsernameUnique(String username) {
return !userRepository.existsByUsername(username);
}

/**
* 检查邮箱是否唯一
*/
public boolean isEmailUnique(String email) {
return !userRepository.existsByEmail(email);
}

/**
* 创建用户
*/
public User createUser(String username, String email, String firstName, String lastName) {
// 业务规则验证
if (!isUsernameUnique(username)) {
throw new UsernameAlreadyExistsException("Username already exists: " + username);
}

if (!isEmailUnique(email)) {
throw new EmailAlreadyExistsException("Email already exists: " + email);
}

// 创建用户
UserId userId = new UserId(UUID.randomUUID().toString());
User user = new User(userId, username, email);

// 设置用户资料
Profile profile = new Profile(firstName, lastName);
user.setProfile(profile);

// 保存用户
userRepository.save(user);

// 发送欢迎邮件
emailService.sendWelcomeEmail(email, firstName);

return user;
}

/**
* 重置密码
*/
public void resetPassword(String email) {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UserNotFoundException("User not found with email: " + email);
}

// 生成重置令牌
String resetToken = generateResetToken();

// 保存重置令牌
user.setPasswordResetToken(resetToken);
user.setPasswordResetExpiry(System.currentTimeMillis() + 3600000); // 1小时

userRepository.save(user);

// 发送重置邮件
emailService.sendPasswordResetEmail(email, resetToken);
}

private String generateResetToken() {
return UUID.randomUUID().toString().replace("-", "");
}
}

/**
* 用户仓储接口
*/
public interface UserRepository extends Repository<User, UserId> {
User findByUsername(String username);
User findByEmail(String email);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
List<User> findByStatus(UserStatus status);
List<User> findByRole(Role role);
}

/**
* 规格实现示例
*/
public class UserSpecifications {

public static class ActiveUserSpecification extends AbstractSpecification<User> {
@Override
public boolean isSatisfiedBy(User candidate) {
return candidate.getStatus() == UserStatus.ACTIVE;
}
}

public static class UserWithRoleSpecification extends AbstractSpecification<User> {
private String roleName;

public UserWithRoleSpecification(String roleName) {
this.roleName = roleName;
}

@Override
public boolean isSatisfiedBy(User candidate) {
return candidate.getRoles().stream()
.anyMatch(role -> role.getName().equals(roleName));
}
}

public static class UserWithEmailDomainSpecification extends AbstractSpecification<User> {
private String domain;

public UserWithEmailDomainSpecification(String domain) {
this.domain = domain;
}

@Override
public boolean isSatisfiedBy(User candidate) {
return candidate.getEmail().endsWith("@" + domain);
}
}
}

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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/**
* 状态机框架
* 实现状态机的核心功能
*/
public class StateMachineFramework {

/**
* 状态接口
*/
public interface State {
String getName();
void onEnter(StateMachineContext context);
void onExit(StateMachineContext context);
void onEvent(StateMachineContext context, Event event);
}

/**
* 事件接口
*/
public interface Event {
String getName();
Object getData();
}

/**
* 状态机上下文
*/
public static class StateMachineContext {
private Object entity;
private Map<String, Object> variables;
private StateMachine stateMachine;

public StateMachineContext(Object entity, StateMachine stateMachine) {
this.entity = entity;
this.stateMachine = stateMachine;
this.variables = new HashMap<>();
}

public Object getEntity() { return entity; }
public StateMachine getStateMachine() { return stateMachine; }
public Map<String, Object> getVariables() { return variables; }
public void setVariable(String key, Object value) { variables.put(key, value); }
public Object getVariable(String key) { return variables.get(key); }
}

/**
* 状态机
*/
public static class StateMachine {
private Map<String, State> states;
private Map<String, Map<String, State>> transitions;
private State currentState;
private StateMachineContext context;

public StateMachine() {
this.states = new HashMap<>();
this.transitions = new HashMap<>();
}

public void addState(State state) {
states.put(state.getName(), state);
}

public void addTransition(String fromState, String event, String toState) {
transitions.computeIfAbsent(fromState, k -> new HashMap<>()).put(event, states.get(toState));
}

public void setInitialState(String stateName) {
this.currentState = states.get(stateName);
if (currentState != null) {
currentState.onEnter(context);
}
}

public void setContext(StateMachineContext context) {
this.context = context;
}

public boolean canTransition(String event) {
if (currentState == null) return false;
Map<String, State> stateTransitions = transitions.get(currentState.getName());
return stateTransitions != null && stateTransitions.containsKey(event);
}

public boolean transition(String event) {
if (!canTransition(event)) {
return false;
}

State nextState = transitions.get(currentState.getName()).get(event);
if (nextState != null) {
currentState.onExit(context);
currentState = nextState;
currentState.onEnter(context);
return true;
}

return false;
}

public void processEvent(Event event) {
if (currentState != null) {
currentState.onEvent(context, event);
}
}

public State getCurrentState() { return currentState; }
public String getCurrentStateName() { return currentState != null ? currentState.getName() : null; }
}
}

/**
* 订单状态机实现
*/
public class OrderStateMachine {

/**
* 订单状态枚举
*/
public enum OrderState {
PENDING("待处理"),
CONFIRMED("已确认"),
PAID("已支付"),
SHIPPED("已发货"),
DELIVERED("已送达"),
CANCELLED("已取消"),
REFUNDED("已退款");

private final String description;

OrderState(String description) {
this.description = description;
}

public String getDescription() {
return description;
}
}

/**
* 订单事件枚举
*/
public enum OrderEvent {
CONFIRM("确认订单"),
PAY("支付"),
SHIP("发货"),
DELIVER("送达"),
CANCEL("取消"),
REFUND("退款");

private final String description;

OrderEvent(String description) {
this.description = description;
}

public String getDescription() {
return description;
}
}

/**
* 订单状态实现
*/
public static class OrderStateImpl implements StateMachineFramework.State {
private OrderState orderState;

public OrderStateImpl(OrderState orderState) {
this.orderState = orderState;
}

@Override
public String getName() {
return orderState.name();
}

@Override
public void onEnter(StateMachineFramework.StateMachineContext context) {
Order order = (Order) context.getEntity();
order.setState(orderState);
System.out.println("订单 " + order.getId() + " 进入状态: " + orderState.getDescription());
}

@Override
public void onExit(StateMachineFramework.StateMachineContext context) {
Order order = (Order) context.getEntity();
System.out.println("订单 " + order.getId() + " 离开状态: " + orderState.getDescription());
}

@Override
public void onEvent(StateMachineFramework.StateMachineContext context, StateMachineFramework.Event event) {
Order order = (Order) context.getEntity();
System.out.println("订单 " + order.getId() + " 在状态 " + orderState.getDescription() + " 处理事件: " + event.getName());
}
}

/**
* 订单事件实现
*/
public static class OrderEventImpl implements StateMachineFramework.Event {
private OrderEvent orderEvent;
private Object data;

public OrderEventImpl(OrderEvent orderEvent, Object data) {
this.orderEvent = orderEvent;
this.data = data;
}

@Override
public String getName() {
return orderEvent.name();
}

@Override
public Object getData() {
return data;
}
}

/**
* 订单状态机构建器
*/
public static class OrderStateMachineBuilder {
private StateMachineFramework.StateMachine stateMachine;

public OrderStateMachineBuilder() {
this.stateMachine = new StateMachineFramework.StateMachine();
}

public OrderStateMachineBuilder addStates() {
// 添加所有状态
for (OrderState state : OrderState.values()) {
stateMachine.addState(new OrderStateImpl(state));
}
return this;
}

public OrderStateMachineBuilder addTransitions() {
// 定义状态转换规则
stateMachine.addTransition("PENDING", "CONFIRM", "CONFIRMED");
stateMachine.addTransition("PENDING", "CANCEL", "CANCELLED");

stateMachine.addTransition("CONFIRMED", "PAY", "PAID");
stateMachine.addTransition("CONFIRMED", "CANCEL", "CANCELLED");

stateMachine.addTransition("PAID", "SHIP", "SHIPPED");
stateMachine.addTransition("PAID", "REFUND", "REFUNDED");

stateMachine.addTransition("SHIPPED", "DELIVER", "DELIVERED");

stateMachine.addTransition("DELIVERED", "REFUND", "REFUNDED");

return this;
}

public StateMachineFramework.StateMachine build() {
return stateMachine;
}
}
}

/**
* 订单实体
*/
public class Order extends Entity<OrderId> {
private OrderState state;
private String customerId;
private List<OrderItem> items;
private Money totalAmount;
private Address shippingAddress;
private PaymentInfo paymentInfo;
private StateMachineFramework.StateMachine stateMachine;

public Order(OrderId id, String customerId, List<OrderItem> items, Address shippingAddress) {
super(id);
this.customerId = customerId;
this.items = items;
this.shippingAddress = shippingAddress;
this.state = OrderState.PENDING;
this.totalAmount = calculateTotalAmount();

// 初始化状态机
initializeStateMachine();
}

private void initializeStateMachine() {
this.stateMachine = new OrderStateMachine.OrderStateMachineBuilder()
.addStates()
.addTransitions()
.build();

StateMachineFramework.StateMachineContext context =
new StateMachineFramework.StateMachineContext(this, stateMachine);
stateMachine.setContext(context);
stateMachine.setInitialState("PENDING");
}

public void confirm() {
if (stateMachine.canTransition("CONFIRM")) {
stateMachine.transition("CONFIRM");
} else {
throw new InvalidStateTransitionException("Cannot confirm order in current state: " + state);
}
}

public void pay(PaymentInfo paymentInfo) {
if (stateMachine.canTransition("PAY")) {
this.paymentInfo = paymentInfo;
stateMachine.transition("PAY");
} else {
throw new InvalidStateTransitionException("Cannot pay order in current state: " + state);
}
}

public void ship(String trackingNumber) {
if (stateMachine.canTransition("SHIP")) {
stateMachine.setVariable("trackingNumber", trackingNumber);
stateMachine.transition("SHIP");
} else {
throw new InvalidStateTransitionException("Cannot ship order in current state: " + state);
}
}

public void deliver() {
if (stateMachine.canTransition("DELIVER")) {
stateMachine.transition("DELIVER");
} else {
throw new InvalidStateTransitionException("Cannot deliver order in current state: " + state);
}
}

public void cancel(String reason) {
if (stateMachine.canTransition("CANCEL")) {
stateMachine.setVariable("cancelReason", reason);
stateMachine.transition("CANCEL");
} else {
throw new InvalidStateTransitionException("Cannot cancel order in current state: " + state);
}
}

public void refund(String reason) {
if (stateMachine.canTransition("REFUND")) {
stateMachine.setVariable("refundReason", reason);
stateMachine.transition("REFUND");
} else {
throw new InvalidStateTransitionException("Cannot refund order in current state: " + state);
}
}

private Money calculateTotalAmount() {
return items.stream()
.map(OrderItem::getSubtotal)
.reduce(Money.ZERO, Money::add);
}

// getters
public OrderState getState() { return state; }
public void setState(OrderState state) { this.state = state; }
public String getCustomerId() { return customerId; }
public List<OrderItem> getItems() { return items; }
public Money getTotalAmount() { return totalAmount; }
public Address getShippingAddress() { return shippingAddress; }
public PaymentInfo getPaymentInfo() { return paymentInfo; }
}

/**
* 订单ID值对象
*/
public class OrderId extends ValueObject {
private String value;

public OrderId(String value) {
this.value = value;
}

public String getValue() {
return value;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
OrderId orderId = (OrderId) obj;
return Objects.equals(value, orderId.value);
}

@Override
public int hashCode() {
return Objects.hash(value);
}
}

/**
* 订单项实体
*/
public class OrderItem extends Entity<OrderItemId> {
private String productId;
private String productName;
private int quantity;
private Money unitPrice;

public OrderItem(OrderItemId id, String productId, String productName, int quantity, Money unitPrice) {
super(id);
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.unitPrice = unitPrice;
}

public Money getSubtotal() {
return unitPrice.multiply(quantity);
}

// getters
public String getProductId() { return productId; }
public String getProductName() { return productName; }
public int getQuantity() { return quantity; }
public Money getUnitPrice() { return unitPrice; }
}

/**
* 订单项ID值对象
*/
public class OrderItemId extends ValueObject {
private String value;

public OrderItemId(String value) {
this.value = value;
}

public String getValue() {
return value;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
OrderItemId orderItemId = (OrderItemId) obj;
return Objects.equals(value, orderItemId.value);
}

@Override
public int hashCode() {
return Objects.hash(value);
}
}

/**
* 金额值对象
*/
public class Money extends ValueObject {
public static final Money ZERO = new Money(0, "CNY");

private long amount; // 以分为单位
private String currency;

public Money(long amount, String currency) {
this.amount = amount;
this.currency = currency;
}

public Money add(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException("Cannot add different currencies");
}
return new Money(amount + other.amount, currency);
}

public Money subtract(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException("Cannot subtract different currencies");
}
return new Money(amount - other.amount, currency);
}

public Money multiply(int multiplier) {
return new Money(amount * multiplier, currency);
}

public double getAmount() {
return amount / 100.0;
}

public String getCurrency() {
return currency;
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Money money = (Money) obj;
return amount == money.amount && Objects.equals(currency, money.currency);
}

@Override
public int hashCode() {
return Objects.hash(amount, currency);
}

@Override
public String toString() {
return String.format("%.2f %s", getAmount(), currency);
}
}

/**
* 支付信息值对象
*/
public class PaymentInfo extends ValueObject {
private String paymentMethod;
private String transactionId;
private Money amount;
private long timestamp;

public PaymentInfo(String paymentMethod, String transactionId, Money amount) {
this.paymentMethod = paymentMethod;
this.transactionId = transactionId;
this.amount = amount;
this.timestamp = System.currentTimeMillis();
}

// getters
public String getPaymentMethod() { return paymentMethod; }
public String getTransactionId() { return transactionId; }
public Money getAmount() { return amount; }
public long getTimestamp() { return timestamp; }

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
PaymentInfo that = (PaymentInfo) obj;
return timestamp == that.timestamp &&
Objects.equals(paymentMethod, that.paymentMethod) &&
Objects.equals(transactionId, that.transactionId) &&
Objects.equals(amount, that.amount);
}

@Override
public int hashCode() {
return Objects.hash(paymentMethod, transactionId, amount, timestamp);
}
}

4. 事件驱动架构

4.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
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
/**
* 事件总线
* 实现事件驱动的核心机制
*/
public class EventBus {
private final Map<Class<?>, List<EventHandler<?>>> handlers;
private final ExecutorService executorService;
private final EventStore eventStore;

public EventBus(EventStore eventStore) {
this.handlers = new ConcurrentHashMap<>();
this.executorService = Executors.newCachedThreadPool();
this.eventStore = eventStore;
}

/**
* 注册事件处理器
*/
public <T> void registerHandler(Class<T> eventType, EventHandler<T> handler) {
handlers.computeIfAbsent(eventType, k -> new ArrayList<>()).add(handler);
}

/**
* 发布事件
*/
public void publish(Object event) {
// 存储事件
eventStore.store(event);

// 异步处理事件
executorService.submit(() -> {
List<EventHandler<?>> eventHandlers = handlers.get(event.getClass());
if (eventHandlers != null) {
for (EventHandler<?> handler : eventHandlers) {
try {
@SuppressWarnings("unchecked")
EventHandler<Object> typedHandler = (EventHandler<Object>) handler;
typedHandler.handle(event);
} catch (Exception e) {
System.err.println("Error handling event: " + e.getMessage());
e.printStackTrace();
}
}
}
});
}

/**
* 同步发布事件
*/
public void publishSync(Object event) {
// 存储事件
eventStore.store(event);

// 同步处理事件
List<EventHandler<?>> eventHandlers = handlers.get(event.getClass());
if (eventHandlers != null) {
for (EventHandler<?> handler : eventHandlers) {
try {
@SuppressWarnings("unchecked")
EventHandler<Object> typedHandler = (EventHandler<Object>) handler;
typedHandler.handle(event);
} catch (Exception e) {
System.err.println("Error handling event: " + e.getMessage());
e.printStackTrace();
}
}
}
}

/**
* 关闭事件总线
*/
public void shutdown() {
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
}

/**
* 事件处理器接口
*/
public interface EventHandler<T> {
void handle(T event);
}

/**
* 事件存储接口
*/
public interface EventStore {
void store(Object event);
List<Object> getEvents(String aggregateId);
List<Object> getEvents(String aggregateId, long fromVersion);
}

/**
* 内存事件存储实现
*/
public class InMemoryEventStore implements EventStore {
private final Map<String, List<StoredEvent>> events;
private final List<Object> allEvents;

public InMemoryEventStore() {
this.events = new ConcurrentHashMap<>();
this.allEvents = new ArrayList<>();
}

@Override
public void store(Object event) {
StoredEvent storedEvent = new StoredEvent(event);
allEvents.add(event);

if (event instanceof DomainEvent) {
DomainEvent domainEvent = (DomainEvent) event;
events.computeIfAbsent(domainEvent.getAggregateId(), k -> new ArrayList<>()).add(storedEvent);
}
}

@Override
public List<Object> getEvents(String aggregateId) {
List<StoredEvent> storedEvents = events.get(aggregateId);
if (storedEvents == null) {
return new ArrayList<>();
}

return storedEvents.stream()
.map(StoredEvent::getEvent)
.collect(Collectors.toList());
}

@Override
public List<Object> getEvents(String aggregateId, long fromVersion) {
List<StoredEvent> storedEvents = events.get(aggregateId);
if (storedEvents == null) {
return new ArrayList<>();
}

return storedEvents.stream()
.filter(se -> se.getVersion() >= fromVersion)
.map(StoredEvent::getEvent)
.collect(Collectors.toList());
}

public List<Object> getAllEvents() {
return new ArrayList<>(allEvents);
}
}

/**
* 存储的事件
*/
public class StoredEvent {
private Object event;
private long version;
private long timestamp;

public StoredEvent(Object event) {
this.event = event;
this.version = System.currentTimeMillis();
this.timestamp = System.currentTimeMillis();
}

public Object getEvent() { return event; }
public long getVersion() { return version; }
public long getTimestamp() { return timestamp; }
}

/**
* 用户事件处理器
*/
@Component
public class UserEventHandler {
private final EmailService emailService;
private final NotificationService notificationService;
private final AuditService auditService;

public UserEventHandler(EmailService emailService,
NotificationService notificationService,
AuditService auditService) {
this.emailService = emailService;
this.notificationService = notificationService;
this.auditService = auditService;
}

@EventHandler
public void handleUserCreated(UserCreatedEvent event) {
// 发送欢迎邮件
emailService.sendWelcomeEmail(event.getEmail(), "User");

// 发送通知
notificationService.sendNotification("user.created", event.getAggregateId());

// 记录审计日志
auditService.logEvent("USER_CREATED", event.getAggregateId(), event);
}

@EventHandler
public void handleUserEmailChanged(UserEmailChangedEvent event) {
// 发送邮件变更确认邮件
emailService.sendEmailChangeConfirmation(event.getNewEmail());

// 记录审计日志
auditService.logEvent("USER_EMAIL_CHANGED", event.getAggregateId(), event);
}

@EventHandler
public void handleUserActivated(UserActivatedEvent event) {
// 发送激活通知
notificationService.sendNotification("user.activated", event.getAggregateId());

// 记录审计日志
auditService.logEvent("USER_ACTIVATED", event.getAggregateId(), event);
}

@EventHandler
public void handleUserDeactivated(UserDeactivatedEvent event) {
// 发送停用通知
notificationService.sendNotification("user.deactivated", event.getAggregateId());

// 记录审计日志
auditService.logEvent("USER_DEACTIVATED", event.getAggregateId(), event);
}
}

/**
* 订单事件处理器
*/
@Component
public class OrderEventHandler {
private final InventoryService inventoryService;
private final PaymentService paymentService;
private final ShippingService shippingService;
private final NotificationService notificationService;

public OrderEventHandler(InventoryService inventoryService,
PaymentService paymentService,
ShippingService shippingService,
NotificationService notificationService) {
this.inventoryService = inventoryService;
this.paymentService = paymentService;
this.shippingService = shippingService;
this.notificationService = notificationService;
}

@EventHandler
public void handleOrderCreated(OrderCreatedEvent event) {
// 预留库存
inventoryService.reserveInventory(event.getProductId(), event.getQuantity());

// 发送订单确认通知
notificationService.sendNotification("order.created", event.getAggregateId());
}

@EventHandler
public void handleOrderConfirmed(OrderConfirmedEvent event) {
// 发送确认邮件
notificationService.sendOrderConfirmation(event.getAggregateId());
}

@EventHandler
public void handleOrderPaid(OrderPaidEvent event) {
// 处理支付
paymentService.processPayment(event.getPaymentInfo());

// 准备发货
shippingService.prepareShipment(event.getAggregateId());

// 发送支付确认通知
notificationService.sendNotification("order.paid", event.getAggregateId());
}

@EventHandler
public void handleOrderShipped(OrderShippedEvent event) {
// 更新库存
inventoryService.releaseReservedInventory(event.getProductId(), event.getQuantity());

// 发送发货通知
notificationService.sendShippingNotification(event.getAggregateId(), event.getTrackingNumber());
}

@EventHandler
public void handleOrderDelivered(OrderDeliveredEvent event) {
// 发送送达确认
notificationService.sendDeliveryConfirmation(event.getAggregateId());

// 触发评价流程
notificationService.sendReviewRequest(event.getAggregateId());
}

@EventHandler
public void handleOrderCancelled(OrderCancelledEvent event) {
// 释放库存
inventoryService.releaseReservedInventory(event.getProductId(), event.getQuantity());

// 处理退款
if (event.getPaymentInfo() != null) {
paymentService.processRefund(event.getPaymentInfo());
}

// 发送取消通知
notificationService.sendNotification("order.cancelled", event.getAggregateId());
}
}

/**
* 订单相关事件
*/
public class OrderCreatedEvent extends DomainEvent {
private String productId;
private int quantity;
private String customerId;

public OrderCreatedEvent(String aggregateId, String productId, int quantity, String customerId) {
super(aggregateId);
this.productId = productId;
this.quantity = quantity;
this.customerId = customerId;
}

public String getProductId() { return productId; }
public int getQuantity() { return quantity; }
public String getCustomerId() { return customerId; }
}

public class OrderConfirmedEvent extends DomainEvent {
public OrderConfirmedEvent(String aggregateId) {
super(aggregateId);
}
}

public class OrderPaidEvent extends DomainEvent {
private PaymentInfo paymentInfo;

public OrderPaidEvent(String aggregateId, PaymentInfo paymentInfo) {
super(aggregateId);
this.paymentInfo = paymentInfo;
}

public PaymentInfo getPaymentInfo() { return paymentInfo; }
}

public class OrderShippedEvent extends DomainEvent {
private String productId;
private int quantity;
private String trackingNumber;

public OrderShippedEvent(String aggregateId, String productId, int quantity, String trackingNumber) {
super(aggregateId);
this.productId = productId;
this.quantity = quantity;
this.trackingNumber = trackingNumber;
}

public String getProductId() { return productId; }
public int getQuantity() { return quantity; }
public String getTrackingNumber() { return trackingNumber; }
}

public class OrderDeliveredEvent extends DomainEvent {
public OrderDeliveredEvent(String aggregateId) {
super(aggregateId);
}
}

public class OrderCancelledEvent extends DomainEvent {
private String productId;
private int quantity;
private PaymentInfo paymentInfo;
private String reason;

public OrderCancelledEvent(String aggregateId, String productId, int quantity, PaymentInfo paymentInfo, String reason) {
super(aggregateId);
this.productId = productId;
this.quantity = quantity;
this.paymentInfo = paymentInfo;
this.reason = reason;
}

public String getProductId() { return productId; }
public int getQuantity() { return quantity; }
public PaymentInfo getPaymentInfo() { return paymentInfo; }
public String getReason() { return reason; }
}

5. 微服务设计模式

5.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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/**
* 微服务架构框架
* 实现微服务的核心组件和模式
*/
public class MicroserviceArchitectureFramework {

/**
* 服务注册中心
*/
public static class ServiceRegistry {
private final Map<String, ServiceInstance> services;
private final Map<String, List<ServiceInstance>> serviceInstances;

public ServiceRegistry() {
this.services = new ConcurrentHashMap<>();
this.serviceInstances = new ConcurrentHashMap<>();
}

public void register(ServiceInstance serviceInstance) {
services.put(serviceInstance.getId(), serviceInstance);
serviceInstances.computeIfAbsent(serviceInstance.getServiceName(), k -> new ArrayList<>()).add(serviceInstance);

System.out.println("Service registered: " + serviceInstance.getServiceName() + " at " + serviceInstance.getHost() + ":" + serviceInstance.getPort());
}

public void deregister(String serviceId) {
ServiceInstance serviceInstance = services.remove(serviceId);
if (serviceInstance != null) {
List<ServiceInstance> instances = serviceInstances.get(serviceInstance.getServiceName());
if (instances != null) {
instances.remove(serviceInstance);
}
System.out.println("Service deregistered: " + serviceInstance.getServiceName());
}
}

public List<ServiceInstance> getInstances(String serviceName) {
return serviceInstances.getOrDefault(serviceName, new ArrayList<>());
}

public ServiceInstance getInstance(String serviceId) {
return services.get(serviceId);
}

public List<ServiceInstance> getAllInstances() {
return new ArrayList<>(services.values());
}
}

/**
* 服务实例
*/
public static class ServiceInstance {
private String id;
private String serviceName;
private String host;
private int port;
private Map<String, String> metadata;
private long lastHeartbeat;
private ServiceStatus status;

public ServiceInstance(String id, String serviceName, String host, int port) {
this.id = id;
this.serviceName = serviceName;
this.host = host;
this.port = port;
this.metadata = new HashMap<>();
this.lastHeartbeat = System.currentTimeMillis();
this.status = ServiceStatus.UP;
}

public String getUrl() {
return "http://" + host + ":" + port;
}

public void updateHeartbeat() {
this.lastHeartbeat = System.currentTimeMillis();
}

public boolean isExpired(long timeout) {
return System.currentTimeMillis() - lastHeartbeat > timeout;
}

// getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getServiceName() { return serviceName; }
public void setServiceName(String serviceName) { this.serviceName = serviceName; }
public String getHost() { return host; }
public void setHost(String host) { this.host = host; }
public int getPort() { return port; }
public void setPort(int port) { this.port = port; }
public Map<String, String> getMetadata() { return metadata; }
public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; }
public long getLastHeartbeat() { return lastHeartbeat; }
public ServiceStatus getStatus() { return status; }
public void setStatus(ServiceStatus status) { this.status = status; }
}

/**
* 服务状态枚举
*/
public enum ServiceStatus {
UP, DOWN, OUT_OF_SERVICE
}

/**
* 负载均衡器
*/
public static class LoadBalancer {
private final ServiceRegistry serviceRegistry;
private final LoadBalancingStrategy strategy;

public LoadBalancer(ServiceRegistry serviceRegistry, LoadBalancingStrategy strategy) {
this.serviceRegistry = serviceRegistry;
this.strategy = strategy;
}

public ServiceInstance chooseInstance(String serviceName) {
List<ServiceInstance> instances = serviceRegistry.getInstances(serviceName);
if (instances.isEmpty()) {
throw new ServiceNotFoundException("No instances found for service: " + serviceName);
}

// 过滤健康的实例
List<ServiceInstance> healthyInstances = instances.stream()
.filter(instance -> instance.getStatus() == ServiceStatus.UP)
.collect(Collectors.toList());

if (healthyInstances.isEmpty()) {
throw new ServiceUnavailableException("No healthy instances found for service: " + serviceName);
}

return strategy.choose(healthyInstances);
}
}

/**
* 负载均衡策略接口
*/
public interface LoadBalancingStrategy {
ServiceInstance choose(List<ServiceInstance> instances);
}

/**
* 轮询策略
*/
public static class RoundRobinStrategy implements LoadBalancingStrategy {
private final AtomicInteger counter = new AtomicInteger(0);

@Override
public ServiceInstance choose(List<ServiceInstance> instances) {
int index = counter.getAndIncrement() % instances.size();
return instances.get(index);
}
}

/**
* 随机策略
*/
public static class RandomStrategy implements LoadBalancingStrategy {
private final Random random = new Random();

@Override
public ServiceInstance choose(List<ServiceInstance> instances) {
int index = random.nextInt(instances.size());
return instances.get(index);
}
}

/**
* 最少连接策略
*/
public static class LeastConnectionStrategy implements LoadBalancingStrategy {
@Override
public ServiceInstance choose(List<ServiceInstance> instances) {
return instances.stream()
.min(Comparator.comparing(ServiceInstance::getLastHeartbeat))
.orElse(instances.get(0));
}
}

/**
* 服务发现客户端
*/
public static class ServiceDiscoveryClient {
private final ServiceRegistry serviceRegistry;
private final LoadBalancer loadBalancer;
private final HttpClient httpClient;

public ServiceDiscoveryClient(ServiceRegistry serviceRegistry, LoadBalancer loadBalancer) {
this.serviceRegistry = serviceRegistry;
this.loadBalancer = loadBalancer;
this.httpClient = HttpClient.newHttpClient();
}

public <T> T callService(String serviceName, String path, Class<T> responseType) {
ServiceInstance instance = loadBalancer.chooseInstance(serviceName);
String url = instance.getUrl() + path;

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();

try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

if (response.statusCode() == 200) {
// 这里简化处理,实际应该使用JSON解析
return (T) response.body();
} else {
throw new ServiceCallException("Service call failed with status: " + response.statusCode());
}
} catch (Exception e) {
throw new ServiceCallException("Service call failed", e);
}
}

public <T> T callServiceWithFallback(String serviceName, String path, Class<T> responseType, T fallbackValue) {
try {
return callService(serviceName, path, responseType);
} catch (Exception e) {
System.err.println("Service call failed, using fallback: " + e.getMessage());
return fallbackValue;
}
}
}

/**
* 断路器
*/
public static class CircuitBreaker {
private final String serviceName;
private final int failureThreshold;
private final long timeout;

private CircuitState state;
private int failureCount;
private long lastFailureTime;

public CircuitBreaker(String serviceName, int failureThreshold, long timeout) {
this.serviceName = serviceName;
this.failureThreshold = failureThreshold;
this.timeout = timeout;
this.state = CircuitState.CLOSED;
this.failureCount = 0;
}

public <T> T execute(Supplier<T> operation, Supplier<T> fallback) {
if (state == CircuitState.OPEN) {
if (System.currentTimeMillis() - lastFailureTime > timeout) {
state = CircuitState.HALF_OPEN;
} else {
return fallback.get();
}
}

try {
T result = operation.get();
onSuccess();
return result;
} catch (Exception e) {
onFailure();
return fallback.get();
}
}

private void onSuccess() {
failureCount = 0;
state = CircuitState.CLOSED;
}

private void onFailure() {
failureCount++;
lastFailureTime = System.currentTimeMillis();

if (failureCount >= failureThreshold) {
state = CircuitState.OPEN;
}
}

public CircuitState getState() {
return state;
}
}

/**
* 断路器状态
*/
public enum CircuitState {
CLOSED, OPEN, HALF_OPEN
}

/**
* 微服务网关
*/
public static class MicroserviceGateway {
private final ServiceDiscoveryClient serviceDiscoveryClient;
private final Map<String, CircuitBreaker> circuitBreakers;
private final RateLimiter rateLimiter;

public MicroserviceGateway(ServiceDiscoveryClient serviceDiscoveryClient, RateLimiter rateLimiter) {
this.serviceDiscoveryClient = serviceDiscoveryClient;
this.circuitBreakers = new ConcurrentHashMap<>();
this.rateLimiter = rateLimiter;
}

public <T> T route(String serviceName, String path, Class<T> responseType) {
// 限流检查
if (!rateLimiter.allowRequest()) {
throw new RateLimitExceededException("Rate limit exceeded");
}

// 获取或创建断路器
CircuitBreaker circuitBreaker = circuitBreakers.computeIfAbsent(serviceName,
name -> new CircuitBreaker(name, 5, 60000)); // 5次失败,60秒超时

// 执行服务调用
return circuitBreaker.execute(
() -> serviceDiscoveryClient.callService(serviceName, path, responseType),
() -> getFallbackResponse(responseType)
);
}

@SuppressWarnings("unchecked")
private <T> T getFallbackResponse(Class<T> responseType) {
// 返回默认的fallback响应
if (responseType == String.class) {
return (T) "Service temporarily unavailable";
}
return null;
}
}

/**
* 限流器
*/
public static class RateLimiter {
private final int maxRequests;
private final long windowSize;
private final Queue<Long> requests;

public RateLimiter(int maxRequests, long windowSize) {
this.maxRequests = maxRequests;
this.windowSize = windowSize;
this.requests = new ConcurrentLinkedQueue<>();
}

public boolean allowRequest() {
long now = System.currentTimeMillis();

// 清理过期的请求
while (!requests.isEmpty() && requests.peek() < now - windowSize) {
requests.poll();
}

// 检查是否超过限制
if (requests.size() >= maxRequests) {
return false;
}

// 记录请求
requests.offer(now);
return true;
}
}
}

/**
* 用户微服务
*/
@RestController
@RequestMapping("/api/users")
public class UserMicroservice {
private final UserService userService;
private final EventBus eventBus;
private final ServiceRegistry serviceRegistry;

public UserMicroservice(UserService userService, EventBus eventBus, ServiceRegistry serviceRegistry) {
this.userService = userService;
this.eventBus = eventBus;
this.serviceRegistry = serviceRegistry;

// 注册服务
registerService();
}

private void registerService() {
ServiceInstance instance = new ServiceInstance(
UUID.randomUUID().toString(),
"user-service",
"localhost",
8081
);
serviceRegistry.register(instance);
}

@PostMapping
public ResponseEntity<UserDto> createUser(@RequestBody CreateUserRequest request) {
try {
User user = userService.createUser(
request.getUsername(),
request.getEmail(),
request.getFirstName(),
request.getLastName()
);

UserDto userDto = convertToDto(user);
return ResponseEntity.ok(userDto);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@GetMapping("/{id}")
public ResponseEntity<UserDto> getUser(@PathVariable String id) {
try {
User user = userService.findById(new UserId(id));
if (user != null) {
UserDto userDto = convertToDto(user);
return ResponseEntity.ok(userDto);
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@PutMapping("/{id}/email")
public ResponseEntity<Void> updateEmail(@PathVariable String id, @RequestBody UpdateEmailRequest request) {
try {
User user = userService.findById(new UserId(id));
if (user != null) {
user.changeEmail(request.getEmail());
userService.save(user);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@PostMapping("/{id}/activate")
public ResponseEntity<Void> activateUser(@PathVariable String id) {
try {
User user = userService.findById(new UserId(id));
if (user != null) {
user.activate();
userService.save(user);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@PostMapping("/{id}/deactivate")
public ResponseEntity<Void> deactivateUser(@PathVariable String id) {
try {
User user = userService.findById(new UserId(id));
if (user != null) {
user.deactivate();
userService.save(user);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@GetMapping("/health")
public ResponseEntity<Map<String, Object>> health() {
Map<String, Object> health = new HashMap<>();
health.put("status", "UP");
health.put("service", "user-service");
health.put("timestamp", System.currentTimeMillis());
return ResponseEntity.ok(health);
}

private UserDto convertToDto(User user) {
UserDto dto = new UserDto();
dto.setId(user.getId().getValue());
dto.setUsername(user.getUsername());
dto.setEmail(user.getEmail());
dto.setStatus(user.getStatus().name());
return dto;
}
}

/**
* 订单微服务
*/
@RestController
@RequestMapping("/api/orders")
public class OrderMicroservice {
private final OrderService orderService;
private final EventBus eventBus;
private final ServiceRegistry serviceRegistry;

public OrderMicroservice(OrderService orderService, EventBus eventBus, ServiceRegistry serviceRegistry) {
this.orderService = orderService;
this.eventBus = eventBus;
this.serviceRegistry = serviceRegistry;

// 注册服务
registerService();
}

private void registerService() {
ServiceInstance instance = new ServiceInstance(
UUID.randomUUID().toString(),
"order-service",
"localhost",
8082
);
serviceRegistry.register(instance);
}

@PostMapping
public ResponseEntity<OrderDto> createOrder(@RequestBody CreateOrderRequest request) {
try {
Order order = orderService.createOrder(
request.getCustomerId(),
request.getItems(),
request.getShippingAddress()
);

OrderDto orderDto = convertToDto(order);
return ResponseEntity.ok(orderDto);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@PostMapping("/{id}/confirm")
public ResponseEntity<Void> confirmOrder(@PathVariable String id) {
try {
Order order = orderService.findById(new OrderId(id));
if (order != null) {
order.confirm();
orderService.save(order);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@PostMapping("/{id}/pay")
public ResponseEntity<Void> payOrder(@PathVariable String id, @RequestBody PaymentRequest request) {
try {
Order order = orderService.findById(new OrderId(id));
if (order != null) {
PaymentInfo paymentInfo = new PaymentInfo(
request.getPaymentMethod(),
request.getTransactionId(),
new Money(request.getAmount(), "CNY")
);
order.pay(paymentInfo);
orderService.save(order);
return ResponseEntity.ok().build();
} else {
return ResponseEntity.notFound().build();
}
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}

@GetMapping("/health")
public ResponseEntity<Map<String, Object>> health() {
Map<String, Object> health = new HashMap<>();
health.put("status", "UP");
health.put("service", "order-service");
health.put("timestamp", System.currentTimeMillis());
return ResponseEntity.ok(health);
}

private OrderDto convertToDto(Order order) {
OrderDto dto = new OrderDto();
dto.setId(order.getId().getValue());
dto.setCustomerId(order.getCustomerId());
dto.setState(order.getState().name());
dto.setTotalAmount(order.getTotalAmount().getAmount());
return dto;
}
}

/**
* DTO类
*/
public class UserDto {
private String id;
private String username;
private String email;
private String status;

// getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
}

public class OrderDto {
private String id;
private String customerId;
private String state;
private double totalAmount;

// getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getCustomerId() { return customerId; }
public void setCustomerId(String customerId) { this.customerId = customerId; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public double getTotalAmount() { return totalAmount; }
public void setTotalAmount(double totalAmount) { this.totalAmount = totalAmount; }
}

public class CreateUserRequest {
private String username;
private String email;
private String firstName;
private String lastName;

// getters and setters
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
}

public class UpdateEmailRequest {
private String email;

public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}

public class CreateOrderRequest {
private String customerId;
private List<OrderItem> items;
private Address shippingAddress;

// getters and setters
public String getCustomerId() { return customerId; }
public void setCustomerId(String customerId) { this.customerId = customerId; }
public List<OrderItem> getItems() { return items; }
public void setItems(List<OrderItem> items) { this.items = items; }
public Address getShippingAddress() { return shippingAddress; }
public void setShippingAddress(Address shippingAddress) { this.shippingAddress = shippingAddress; }
}

public class PaymentRequest {
private String paymentMethod;
private String transactionId;
private long amount;

// getters and setters
public String getPaymentMethod() { return paymentMethod; }
public void setPaymentMethod(String paymentMethod) { this.paymentMethod = paymentMethod; }
public String getTransactionId() { return transactionId; }
public void setTransactionId(String transactionId) { this.transactionId = transactionId; }
public long getAmount() { return amount; }
public void setAmount(long amount) { this.amount = amount; }
}

6. 总结

本文深入探讨了系统模型的架构师级别技术,涵盖了领域建模、状态机、事件驱动架构、微服务设计,以及企业级系统建模的最佳实践。

关键技术要点:

  1. **领域驱动设计(DDD)**:

    • 聚合根、实体、值对象、领域事件
    • 领域服务、仓储模式、规格模式
    • 限界上下文、领域模型
  2. 状态机

    • 状态转换、事件处理、上下文管理
    • 状态验证、转换规则、状态持久化
    • 复杂业务状态建模
  3. 事件驱动架构

    • 事件总线、事件处理器、事件存储
    • 异步事件处理、事件溯源
    • 领域事件、集成事件
  4. 微服务设计

    • 服务注册发现、负载均衡、断路器
    • API网关、限流、服务间通信
    • 服务拆分、数据一致性
  5. 企业级架构

    • 分层架构、模块化设计
    • 可扩展性、可维护性
    • 性能优化、监控告警

架构设计原则:

  • 领域驱动:以业务领域为核心,建立清晰的领域模型
  • 事件驱动:通过事件实现松耦合、高内聚的系统架构
  • 微服务化:将系统拆分为独立的、可独立部署的服务
  • 可扩展性:支持水平扩展和功能扩展
  • 可维护性:代码清晰、文档完整、易于理解和修改

作为架构师,我们需要深入理解系统建模的原理和方法,掌握各种设计模式的应用,并能够根据业务需求选择最合适的架构方案。通过本文的实战案例,我们可以更好地理解系统建模在企业级应用中的重要作用。

系统建模是一个持续的过程,需要根据业务发展和技术演进不断调整和优化。只有深入理解建模技术的本质,才能设计出真正优秀的系统架构解决方案。