10.1 系统架构设计原则
面试重要程度:⭐⭐⭐⭐⭐
常见提问方式:如何设计一个高并发系统?系统架构设计需要考虑哪些因素?
预计阅读时间:35分钟
🎯 高并发系统设计核心原则
高可用性设计原则
/**
* 高可用性架构设计
*/
@Component
public class HighAvailabilityDesign {
/**
* 系统可用性计算
*/
public static class AvailabilityCalculator {
// 可用性等级定义
public enum AvailabilityLevel {
BASIC(99.0, "基础级", "87.6小时/年"),
STANDARD(99.9, "标准级", "8.76小时/年"),
HIGH(99.99, "高可用", "52.56分钟/年"),
ULTRA_HIGH(99.999, "超高可用", "5.26分钟/年");
private final double percentage;
private final String name;
private final String downtime;
}
/**
* 计算系统整体可用性(串联系统)
*/
public double calculateSerialAvailability(List<Double> componentAvailabilities) {
return componentAvailabilities.stream()
.reduce(1.0, (a, b) -> a * b);
}
/**
* 计算系统整体可用性(并联系统)
*/
public double calculateParallelAvailability(List<Double> componentAvailabilities) {
double unavailability = componentAvailabilities.stream()
.map(availability -> 1.0 - availability)
.reduce(1.0, (a, b) -> a * b);
return 1.0 - unavailability;
}
}
/**
* 容错设计模式
*/
@Component
public static class FaultTolerancePatterns {
/**
* 故障隔离 - 舱壁模式
*/
@Component
public static class BulkheadPattern {
// 为不同业务分配独立的线程池
private final ExecutorService userServiceExecutor;
private final ExecutorService orderServiceExecutor;
public BulkheadPattern() {
this.userServiceExecutor = new ThreadPoolExecutor(
10, 20, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("user-service-%d").build()
);
this.orderServiceExecutor = new ThreadPoolExecutor(
15, 30, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(200),
new ThreadFactoryBuilder().setNameFormat("order-service-%d").build()
);
}
/**
* 用户服务处理
*/
public CompletableFuture<UserResponse> handleUserRequest(UserRequest request) {
return CompletableFuture.supplyAsync(() -> {
try {
return processUserRequest(request);
} catch (Exception e) {
log.error("User service error", e);
return UserResponse.error("用户服务暂时不可用");
}
}, userServiceExecutor);
}
}
/**
* 超时控制
*/
@Component
public static class TimeoutControl {
/**
* 带超时的服务调用
*/
public <T> CompletableFuture<T> callWithTimeout(
Supplier<T> supplier,
long timeout,
TimeUnit unit) {
CompletableFuture<T> future = CompletableFuture.supplyAsync(supplier);
CompletableFuture<T> timeoutFuture = new CompletableFuture<>();
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.schedule(() -> {
timeoutFuture.completeExceptionally(new TimeoutException("Operation timeout"));
}, timeout, unit);
return CompletableFuture.anyOf(future, timeoutFuture)
.thenApply(result -> (T) result);
}
/**
* HTTP客户端超时配置
*/
@Bean
public RestTemplate restTemplateWithTimeout() {
HttpComponentsClientHttpRequestFactory factory =
new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 连接超时5秒
factory.setReadTimeout(10000); // 读取超时10秒
factory.setConnectionRequestTimeout(3000); // 请求超时3秒
return new RestTemplate(factory);
}
}
/**
* 重试机制
*/
@Component
public static class RetryMechanism {
/**
* 指数退避重试
*/
public <T> T retryWithExponentialBackoff(
Supplier<T> operation,
int maxRetries,
long initialDelay,
double multiplier) {
Exception lastException = null;
long delay = initialDelay;
for (int attempt = 0; attempt <= maxRetries; attempt++) {
try {
return operation.get();
} catch (Exception e) {
lastException = e;
if (attempt == maxRetries) {
break;
}
try {
Thread.sleep(delay);
delay = (long) (delay * multiplier);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Retry interrupted", ie);
}
}
}
throw new RuntimeException("Operation failed after retries", lastException);
}
/**
* Spring Retry注解方式
*/
@Retryable(
value = {Exception.class},
maxAttempts = 3,
backoff = @Backoff(delay = 1000, multiplier = 2)
)
public String callExternalService(String param) {
return externalServiceClient.call(param);
}
@Recover
public String recoverFromFailure(Exception e, String param) {
log.error("External service call failed after retries", e);
return "默认响应";
}
}
}
}
高并发性设计原则
/**
* 高并发架构设计
*/
@Component
public class HighConcurrencyDesign {
/**
* 无状态设计
*/
@RestController
@RequestMapping("/api/stateless")
public static class StatelessController {
@Autowired
private UserService userService;
@Autowir
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
Java面试圣经 文章被收录于专栏
Java面试圣经,带你练透java圣经
海康威视公司氛围 989人发布