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;
        
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        
        /**
         * 无状态的用户信息查询
         */
        @GetMapping("/user/{userId}")
        public ResponseEntity<UserInfo> getUserInfo(@PathVariable Long userId) {
            try {
                String cacheKey = "user:info:" + userId;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(cacheKey);
                
                if (userInfo == null) {
                    userInfo = userService.getUserById(userId);
                    if (userInfo != null) {
                        redisTemplate.opsForValue().set(cacheKey, userInfo, Duration.ofMinutes(30));
                    }
                }
                
                return ResponseEntity.ok(userInfo);
                
            } catch (Exception e) {
                log.error("Failed to get user info", e);
                return ResponseEntity.status(500).build();
            }
        }
        
        /**
         * 无状态的订单处理
         */
        @PostMapping("/order")
        public ResponseEntity<OrderResult> createOrder(@RequestBody CreateOrderRequest request) {
            String lockKey = "order:lock:" + request.getUserId();
            
            try {
                Boolean lockAcquired = redisTemplate.opsForValue()
                    .setIfAbsent(lockKey, "locked", Duration.ofSeconds(30));
                
                if (!lockAcquired) {
                    return ResponseEntity.status(429)
                        .body(OrderResult.error("请勿重复提交订单"));
                }
                
                OrderResult result = userService.createOrder(request);
                return ResponseEntity.ok(result);
                
            } finally {
                redisTemplate.delete(lockKey);
            }
        }
    }
    
    /**
     * 异步处理设计
     */
    @Component
    public static class AsynchronousProcessing {
        
        @Autowired
        private RabbitTemplate rabbitTemplate;
        
        /**
         * 异步事件处理
         */
        @EventListener
        @Async("taskExecutor")
        public void handleOrderCreatedEvent(OrderCreatedEvent event) {
            try {
                sendOrderNotification(event.getOrderId());
                updateInventory(event.getOrderItems());
                generateInvoice(event.getOrderId());
                
            } catch (Exception e) {
                log.error("Failed to process order created event", e);
            }
        }
        
        /**
         * 异步线程池配置
         */
        @Bean("taskExecutor")
        public TaskExecutor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(50);
            executor.setQueueCapacity(200);
            executor.setKeepAliveSeconds(60);
            executor.setThreadNamePrefix("async-task-");
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            executor.initialize();
            return executor;
        }
    }
    
    /**
     * 缓存设计模式
     */
    @Component
    public static class CacheDesignPatterns {
        
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        
        /**
         * Cache-Aside模式
         */
        public UserInfo getUserWithCacheAside(Long userId) {
            String cacheKey = "user:" + userId;
            
            // 1. 先查缓存
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(cacheKey);
            if (userInfo != null) {
                return userInfo;
            }
            
            // 2. 缓存未命中,查数据库
            userInfo = userRepository.findById(userId);
            if (userInfo != null) {
                // 3. 写入缓存
                redisTemplate.opsForValue().set(cacheKey, userInfo, Duration.ofMinutes(30));
            }
            
            return userInfo;
        }
        
        /**
         * Write-Through模式
         */
        public void updateUserWithWriteThrough(UserInfo userInfo) {
            String cacheKey = "user:" + userInfo.getId();
            
            // 同时更新数据库和缓存
            userRepository.save(userInfo);
            redisTemplate.opsForValue().set(cacheKey, userInfo, Duration.ofMinutes(30));
        }
    }
}

🔧 可扩展性与可维护性设计

水平扩展设计

/**
 * 水平扩展架构设计
 */
@Component
public class HorizontalScalabilityDesign {
    
    /**
     * 服务发现与注册
     */
    @Component
    public static class ServiceDiscovery {
        
        @Autowired
        private DiscoveryClient discoveryClient;
        
        /**
         * 获取可用服务实例
         */
        public List<ServiceInstance> getAvailableInstances(String serviceName) {
            return discoveryClient.getInstances(serviceName);
        }
        
        /**
         * 负载均衡选择实例
         */
        public ServiceInstance selectInstance(String serviceName, LoadBalanceStrategy strategy) {
            List<ServiceInstance> instances = getAvailableInstances(serviceName);
            
            if (instances.isEmpty()) {
                throw new ServiceUnavailableException("No available instances for service: " + serviceName);
            }
            
            switch (strategy) {
                case ROUND_ROBIN:
                    return selectByRoundRobin(instances);
                case RANDOM:
                    return selectByRandom(instances);
                case LEAST_CONNECTIONS:
                    return selectByLeastConnections(instances);
                default:
                    return instances.get(0);
            }
        }
        
        private ServiceInstance selectByRoundRobin(List<ServiceInstance> instances) {
            int index = (int) (System.currentTimeMillis() % instances.size());
            return instances.get(index);
        }
    }
    
    /**
     * 自动扩缩容
     */
    @Component
    public static class AutoScaling {
        
        @Autowired
        private MetricsCollector metricsCollector;
        
        private static final int MAX_INSTANCES = 20;
        private static final int MIN_INSTANCES = 2;
        
        /**
         * 基于CPU使用率的自动扩容
         */
        @Scheduled(fixedRate = 60000) // 1分钟检查一次
        public void checkAutoScaling() {
            double avgCpuUsage = metricsCollector.getAverageCpuUsage();
            int currentInstances = getCurrentInstanceCount();
            
            if (avgCpuUsage > 70 && currentInstances < MAX_INSTANCES) {
                scaleUp();
            } else if (avgCpuUsage < 30 && currentInstances > MIN_INSTANCES) {
                scaleDown();
            }
        }
        
        /**
         * 基于请求量的自动扩容
         */
        public void checkRequestBasedScaling() {
            long currentQPS = metricsCollector.getCurrentQPS();
            int currentInstances = getCurrentInstanceCount();
            
            // 每个实例处理1000QPS
            int requiredInstances = (int) Math.ceil(currentQPS / 1000.0);
            
            if (requiredInstances > currentInstances) {
                scaleUpTo(requiredInstances);
            } else if (requiredInstances < currentInstances) {
                scaleDownTo(requiredInstances);
            }
        }
    }
}

性能优化设计

/**
 * 高性能架构设计
 */
@Component
public class HighPerformanceDesign {
    
    /**
     * 数据库连接池优化
     */
    @Configuration
    public static class DatabaseOptimization {
        
        /**
         * HikariCP连接池配置
         */
        @Bean
        @Primary
        public DataSource primaryDataSource() {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl("jdbc:mysql://localhost:3306/app_db");
            config.setUsername("app_user");
            config.setPassword("app_password");
            
            // 连接池配置
            config.setMaximumPoolSize(50);              // 最大连接数
            config.setMinimumIdle(10);                  // 最小空闲连接
            config.setConnectionTimeout(30000);         // 连接超时30秒
            config.setIdleTimeout(600000);              // 空闲超时10分钟
            config.setMaxLifetime(1800000);             // 连接最大生命周期30分钟
            
            // 性能优化配置
            config.addDataSourceProperty("cachePrepStmts", "true");
            config.addDataSourceProperty("prepStmtCacheSize", "250");
            config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
            config.addDataSourceProperty("useServerPrepStmts", "true");
            config.addDataSourceProperty("rewriteBatchedStatements", "true");
            
            return new HikariDataSource(config);
        }
    }
    
    /**
     * JVM性能调优
     */
    @Component
    public static class JVMTuning {
        
        /**
         * JVM启动参数建议
         */
        public static class JVMParameters {
            
            // 堆内存配置
            public static final String HEAP_CONFIG = 
                "-Xms4g -Xmx4g " +                    // 堆内存4G
                "-XX:NewRatio=1 " +                   // 新生代与老年代比例1:1
                "-XX:SurvivorRatio=8";                // Eden与Survivor比例8:1:1
            
            // GC配置
            public static final String GC_CONFIG = 
                "-XX:+UseG1GC " +                     // 使用G1垃圾收集器
                "-XX:MaxGCPauseMillis=200 " +         // 最大GC停顿时间200ms
                "-XX:G1HeapRegionSize=16m";           // G1区域大小16MB
            
            // 监控配置
            public static final String MONITORING_CONFIG = 
                "-XX:+PrintGC " +                     // 打印GC信息
                "-XX:+PrintGCDetails " +              // 打印GC详细信息
                "-Xloggc:gc.log";                     // GC日志文件
        }
    }
}

💡 面试回答要点

标准回答模板

第一部分:设计原则概述

"高并发系统设计需要遵循三高原则:
1. 高可用:99.99%可用性,故障隔离、超时重试、熔断降级
2. 高并发:无状态设计、异步处理、缓存优化、负载均衡
3. 高性能:连接池优化、JVM调优、数据库优化、网络优化

核心是通过冗余消除单点故障,通过分层解耦提升扩展性。"

第二部分:具体实现策略

"实现策略包括:
1. 架构层面:微服务架构、服务网格、容器化部署
2. 应用层面:无状态设计、异步处理、批量操作
3. 数据层面:读写分离、分库分表、多级缓存
4. 运维层面:监控告警、自动扩缩容、灰度发布"

第三部分:容错与恢复

"容错机制:
1. 故障隔离:舱壁模式、线程池隔离、资源隔离
2. 快速失败:超时控制、熔断器、限流
3. 优雅降级:服务降级、功能开关、兜底数据
4. 自动恢复:健康检查、自动重启、故障转移"

核心要点总结:

  • ✅ 掌握高并发系统设计的核心原则和实现方法
  • ✅ 理解高可用、高并发、高性能的具体技术手段
  • ✅ 具备系统架构设计和性能优化能力
  • ✅ 了解容错机制和自动化运维策略
Java面试圣经 文章被收录于专栏

Java面试圣经

全部评论

相关推荐

08-20 14:38
南开大学 Java
Leaton:我也,感觉聊的还挺好的,要结束的时候还说二面会邮箱通知我,反问又让我多问点问题,然后一个礼拜反手给我挂了
大厂面试问八股多还是项目...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务