Spring Boot高并发设计实战:线程池调优、限流熔断与异步消息处理方案

Tomcat线程池参数调优:压测数据说话

Spring Boot默认内嵌Tomcat线程池配置对低负载场景够用,但面对高并发时就暴露短板。调优前先用压测工具拿到基线数据。

# 用wrk压测获取基线
wrk -t8 -c500 -d30s http://localhost:8080/api/orders

关键参数在application.yml中配置:

server:
  tomcat:
    threads:
      max: 400            # 最大工作线程数,默认200
      min-spare: 50        # 最小空闲线程数,默认10
    max-connections: 8000  # 最大连接数,默认8192
    accept-count: 200      # 等待队列长度,默认100
    connection-timeout: 5000

线程数不是越大越好。CPU密集型任务线程数=CPU核数+1;IO密集型任务线程数=CPU核数×(1+等待时间/计算时间)。实际值要通过压测调整,观察CPU利用率和线程等待时间。

监控线程池状态:

@RestController
public class TomcatMetricsController {

    @Autowired
    private ServerProperties serverProperties;

    @GetMapping("/metrics/tomcat")
    public Map<String, Object> tomcatMetrics() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor)
            ManagementFactory.getPlatformMBeanServer().getAttribute(
                new ObjectName("Tomcat:type=ThreadPool,name="http-nio-*""),
                "activeCount"
            );
        return Map.of(
            "activeThreads", executor.getActiveCount(),
            "poolSize", executor.getPoolSize(),
            "queueSize", executor.getQueue().size(),
            "completedTasks", executor.getCompletedTaskCount()
        );
    }
}

接口级限流:Sentinel配置与自定义规则

高并发场景下限流是第一道防线。Sentinel相比Guava RateLimiter的优势是支持集群限流和丰富的流控效果。

// 引入依赖
// implementation 'com.alibaba.csp:sentinel-spring-boot-starter:1.8.7'

// 自定义限流规则配置
@Configuration
public class SentinelConfig {

    @PostConstruct
    public void initRules() {
        List<FlowRule> rules = new ArrayList<>();

        // 订单创建接口:QPS限流200
        FlowRule orderRule = new FlowRule();
        orderRule.setResource("POST:/api/orders");
        orderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        orderRule.setCount(200);
        orderRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);
        orderRule.setWarmUpPeriodSec(10);  // 预热10秒
        rules.add(orderRule);

        // 支付接口:更严格限流
        FlowRule payRule = new FlowRule();
        payRule.setResource("POST:/api/payments");
        payRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        payRule.setCount(50);
        payRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
        payRule.setMaxQueueingTimeMs(2000);  // 排队超时2秒
        rules.add(payRule);

        FlowRuleManager.loadRules(rules);
    }
}

// 控制器中使用
@RestController
public class OrderController {

    @SentinelResource(value = "POST:/api/orders",
        blockHandler = "createOrderBlock",
        fallback = "createOrderFallback")
    @PostMapping("/api/orders")
    public Order createOrder(@RequestBody OrderRequest req) {
        return orderService.create(req);
    }

    public Order createOrderBlock(BlockException ex) {
        throw new BusinessException("SYSTEM_BUSY", "系统繁忙,请稍后重试");
    }

    public Order createOrderFallback(Throwable ex) {
        log.error("订单创建异常", ex);
        throw new BusinessException("SYSTEM_ERROR", "系统异常");
    }
}

熔断降级:Resilience4j断路器配置

当下游服务异常率升高时,断路器打开,快速失败而非让请求堆积超时。

// application.yml配置
resilience4j:
  circuitbreaker:
    instances:
      paymentService:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 20
        failure-rate-threshold: 50
        slow-call-duration-threshold: 3s
        slow-call-rate-threshold: 60
        permitted-number-of-calls-in-half-open-state: 5
        wait-duration-in-open-state: 30s
        minimum-number-of-calls: 10

// 在服务调用处使用
@Service
public class PaymentServiceClient {

    @CircuitBreaker(name = "paymentService", fallbackMethod = "payFallback")
    @TimeLimiter(name = "paymentService")
    public CompletableFuture<PaymentResult> pay(PaymentRequest req) {
        return CompletableFuture.supplyAsync(() -> {
            return restTemplate.postForObject(
                "http://payment-service/api/pay", req, PaymentResult.class);
        });
    }

    private PaymentResult payFallback(Throwable t) {
        log.warn("支付服务熔断降级: {}", t.getMessage());
        return PaymentResult.degrade("支付服务暂时不可用");
    }
}

RabbitMQ异步消息处理架构

高并发写操作不适合同步处理。用消息队列削峰填谷,核心流程同步返回,后续处理异步化。

// 消息生产者
@Service
public class OrderMessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendOrderCreatedEvent(Order order) {
        OrderEvent event = OrderEvent.from(order);
        rabbitTemplate.convertAndSend(
            "order.exchange",
            "order.created",
            event,
            msg -> {
                msg.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return msg;
            }
        );
    }
}

// 消息消费者(手动ACK + 重试)
@Component
@RabbitListener(queues = "order.created.queue")
public class OrderCreatedConsumer {

    @RabbitHandler
    public void handle(OrderEvent event, Channel channel,
                       @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            inventoryService.deduct(event);
            pointsService.earn(event);
            channel.basicAck(tag, false);
        } catch (BusinessException e) {
            // 业务异常,不重试,进死信队列
            channel.basicReject(tag, false);
        } catch (Exception e) {
            // 系统异常,重试
            channel.basicNack(tag, false, true);
        }
    }
}

// 死信队列配置
@Configuration
public class DLQConfig {

    @Bean
    public Queue orderDeadLetterQueue() {
        return QueueBuilder.durable("order.dlq")
            .withArgument("x-message-ttl", 86400000)  // 24小时过期
            .build();
    }

    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange("order.exchange");
    }
}

并发安全与本地缓存设计

Spring Boot的@Cacheable在高并发下有缓存击穿风险——大量线程同时穿透到数据库。用互锁加载解决:

@Service
public class ProductService {

    private final Map<String, CompletableFuture<Product>> loadingMap =
        new ConcurrentHashMap<>();

    @Cacheable(value = "products", key = "#id")
    public Product getProduct(String id) {
        // 防止缓存击穿:同一个key只允许一个线程加载
        while (true) {
            CompletableFuture<Product> existing = loadingMap.get(id);
            if (existing != null) {
                try {
                    return existing.get();
                } catch (Exception e) {
                    loadingMap.remove(id);
                    throw new BusinessException("PRODUCT_LOAD_ERROR");
                }
            }

            CompletableFuture<Product> future = new CompletableFuture<>();
            if (loadingMap.putIfAbsent(id, future) == null) {
                try {
                    Product product = productRepository.findById(id);
                    future.complete(product);
                    return product;
                } catch (Exception e) {
                    future.completeExceptionally(e);
                    throw e;
                } finally {
                    loadingMap.remove(id);
                }
            }
        }
    }
}

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/springboot-gao-bing-fa-she-ji-shi-zhan-xian-cheng-chi-diao/

(0)
小编小编
上一篇 14小时前
下一篇 14小时前

相关推荐

Spring Boot高并发设计实战:线程池调优、限流熔断与异步消息处理方案

Tomcat线程池参数调优:压测数据说话

Spring Boot默认内嵌Tomcat线程池配置对低负载场景够用,但面对高并发时就暴露短板。调优前先用压测工具拿到基线数据。

# 用wrk压测获取基线
wrk -t8 -c500 -d30s http://localhost:8080/api/orders

关键参数在application.yml中配置:

server:
  tomcat:
    threads:
      max: 400            # 最大工作线程数,默认200
      min-spare: 50        # 最小空闲线程数,默认10
    max-connections: 8000  # 最大连接数,默认8192
    accept-count: 200      # 等待队列长度,默认100
    connection-timeout: 5000

线程数不是越大越好。CPU密集型任务线程数=CPU核数+1;IO密集型任务线程数=CPU核数×(1+等待时间/计算时间)。实际值要通过压测调整,观察CPU利用率和线程等待时间。

监控线程池状态:

@RestController
public class TomcatMetricsController {

    @Autowired
    private ServerProperties serverProperties;

    @GetMapping("/metrics/tomcat")
    public Map<String, Object> tomcatMetrics() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor)
            ManagementFactory.getPlatformMBeanServer().getAttribute(
                new ObjectName("Tomcat:type=ThreadPool,name="http-nio-*""),
                "activeCount"
            );
        return Map.of(
            "activeThreads", executor.getActiveCount(),
            "poolSize", executor.getPoolSize(),
            "queueSize", executor.getQueue().size(),
            "completedTasks", executor.getCompletedTaskCount()
        );
    }
}

接口级限流:Sentinel配置与自定义规则

高并发场景下限流是第一道防线。Sentinel相比Guava RateLimiter的优势是支持集群限流和丰富的流控效果。

// 引入依赖
// implementation 'com.alibaba.csp:sentinel-spring-boot-starter:1.8.7'

// 自定义限流规则配置
@Configuration
public class SentinelConfig {

    @PostConstruct
    public void initRules() {
        List<FlowRule> rules = new ArrayList<>();

        // 订单创建接口:QPS限流200
        FlowRule orderRule = new FlowRule();
        orderRule.setResource("POST:/api/orders");
        orderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        orderRule.setCount(200);
        orderRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);
        orderRule.setWarmUpPeriodSec(10);  // 预热10秒
        rules.add(orderRule);

        // 支付接口:更严格限流
        FlowRule payRule = new FlowRule();
        payRule.setResource("POST:/api/payments");
        payRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        payRule.setCount(50);
        payRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
        payRule.setMaxQueueingTimeMs(2000);  // 排队超时2秒
        rules.add(payRule);

        FlowRuleManager.loadRules(rules);
    }
}

// 控制器中使用
@RestController
public class OrderController {

    @SentinelResource(value = "POST:/api/orders",
        blockHandler = "createOrderBlock",
        fallback = "createOrderFallback")
    @PostMapping("/api/orders")
    public Order createOrder(@RequestBody OrderRequest req) {
        return orderService.create(req);
    }

    public Order createOrderBlock(BlockException ex) {
        throw new BusinessException("SYSTEM_BUSY", "系统繁忙,请稍后重试");
    }

    public Order createOrderFallback(Throwable ex) {
        log.error("订单创建异常", ex);
        throw new BusinessException("SYSTEM_ERROR", "系统异常");
    }
}

熔断降级:Resilience4j断路器配置

当下游服务异常率升高时,断路器打开,快速失败而非让请求堆积超时。

// application.yml配置
resilience4j:
  circuitbreaker:
    instances:
      paymentService:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 20
        failure-rate-threshold: 50
        slow-call-duration-threshold: 3s
        slow-call-rate-threshold: 60
        permitted-number-of-calls-in-half-open-state: 5
        wait-duration-in-open-state: 30s
        minimum-number-of-calls: 10

// 在服务调用处使用
@Service
public class PaymentServiceClient {

    @CircuitBreaker(name = "paymentService", fallbackMethod = "payFallback")
    @TimeLimiter(name = "paymentService")
    public CompletableFuture<PaymentResult> pay(PaymentRequest req) {
        return CompletableFuture.supplyAsync(() -> {
            return restTemplate.postForObject(
                "http://payment-service/api/pay", req, PaymentResult.class);
        });
    }

    private PaymentResult payFallback(Throwable t) {
        log.warn("支付服务熔断降级: {}", t.getMessage());
        return PaymentResult.degrade("支付服务暂时不可用");
    }
}

RabbitMQ异步消息处理架构

高并发写操作不适合同步处理。用消息队列削峰填谷,核心流程同步返回,后续处理异步化。

// 消息生产者
@Service
public class OrderMessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendOrderCreatedEvent(Order order) {
        OrderEvent event = OrderEvent.from(order);
        rabbitTemplate.convertAndSend(
            "order.exchange",
            "order.created",
            event,
            msg -> {
                msg.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return msg;
            }
        );
    }
}

// 消息消费者(手动ACK + 重试)
@Component
@RabbitListener(queues = "order.created.queue")
public class OrderCreatedConsumer {

    @RabbitHandler
    public void handle(OrderEvent event, Channel channel,
                       @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            inventoryService.deduct(event);
            pointsService.earn(event);
            channel.basicAck(tag, false);
        } catch (BusinessException e) {
            // 业务异常,不重试,进死信队列
            channel.basicReject(tag, false);
        } catch (Exception e) {
            // 系统异常,重试
            channel.basicNack(tag, false, true);
        }
    }
}

// 死信队列配置
@Configuration
public class DLQConfig {

    @Bean
    public Queue orderDeadLetterQueue() {
        return QueueBuilder.durable("order.dlq")
            .withArgument("x-message-ttl", 86400000)  // 24小时过期
            .build();
    }

    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange("order.exchange");
    }
}

并发安全与本地缓存设计

Spring Boot的@Cacheable在高并发下有缓存击穿风险——大量线程同时穿透到数据库。用互锁加载解决:

@Service
public class ProductService {

    private final Map<String, CompletableFuture<Product>> loadingMap =
        new ConcurrentHashMap<>();

    @Cacheable(value = "products", key = "#id")
    public Product getProduct(String id) {
        // 防止缓存击穿:同一个key只允许一个线程加载
        while (true) {
            CompletableFuture<Product> existing = loadingMap.get(id);
            if (existing != null) {
                try {
                    return existing.get();
                } catch (Exception e) {
                    loadingMap.remove(id);
                    throw new BusinessException("PRODUCT_LOAD_ERROR");
                }
            }

            CompletableFuture<Product> future = new CompletableFuture<>();
            if (loadingMap.putIfAbsent(id, future) == null) {
                try {
                    Product product = productRepository.findById(id);
                    future.complete(product);
                    return product;
                } catch (Exception e) {
                    future.completeExceptionally(e);
                    throw e;
                } finally {
                    loadingMap.remove(id);
                }
            }
        }
    }
}

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/springboot-gao-bing-fa-she-ji-shi-zhan-xian-cheng-chi-diao/

(0)
小编小编
上一篇 14小时前
下一篇 14小时前

相关推荐

Spring Boot高并发设计实战:线程池调优与Sentinel限流熔断配置

高并发场景下,Spring Boot应用的线程池配置和限流熔断策略直接决定系统稳定性。不合理的线程池参数会导致OOM或服务雪崩,缺少限流保护则可能在流量洪峰时击垮下游依赖。本文从线程池调优、异步编排、Sentinel流控、熔断降级四个维度,提供微服务高并发架构的实战配置方案。

ThreadPoolTaskExecutor线程池参数调优

Spring Boot默认的线程池配置不适合生产环境。需要根据CPU密集型或IO密集型场景,分别配置核心线程数、最大线程数和队列容量。

@Configuration
public class ThreadPoolConfig {

    // CPU密集型:核心线程数 = CPU核数 + 1
    @Bean("cpuExecutor")
    public ThreadPoolTaskExecutor cpuExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int cpuCores = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(cpuCores + 1);
        executor.setMaxPoolSize(cpuCores + 1);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("cpu-pool-");
        // 拒绝策略:CallerRunsPolicy让调用线程执行,形成背压
        executor.setRejectedExecutionHandler(
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        executor.initialize();
        return executor;
    }

    // IO密集型:核心线程数 = CPU核数 * 2
    @Bean("ioExecutor")
    public ThreadPoolTaskExecutor ioExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int cpuCores = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(cpuCores * 2);
        executor.setMaxPoolSize(cpuCores * 4);
        executor.setQueueCapacity(1000);
        executor.setKeepAliveSeconds(120);
        executor.setThreadNamePrefix("io-pool-");
        executor.setRejectedExecutionHandler(
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        executor.initialize();
        return executor;
    }
}

线程池监控是调优的前提。通过Micrometer暴露线程池指标到Prometheus:

@Component
public class ThreadPoolMonitor {

    @Autowired
    @Qualifier("ioExecutor")
    private ThreadPoolTaskExecutor ioExecutor;

    @Scheduled(fixedRate = 10000)
    public void reportMetrics() {
        ThreadPoolExecutor pool = ioExecutor.getThreadPoolExecutor();
        log.info("IO线程池 - 活跃:{}, 队列:{}, 已完成:{}, 最大峰值:{}",
            pool.getActiveCount(),
            pool.getQueue().size(),
            pool.getCompletedTaskCount(),
            pool.getLargestPoolSize());
    }
}

CompletableFuture异步编排实战

高并发接口中多个独立的数据查询可以通过CompletableFuture并行执行,将串行的多次RPC调用转为并行,接口耗时从各调用之和降低到最大单次调用耗时。

@Service
public class OrderDetailService {

    @Autowired
    @Qualifier("ioExecutor")
    private ThreadPoolTaskExecutor executor;

    @Autowired
    private UserFeignClient userClient;
    @Autowired
    private ProductFeignClient productClient;
    @Autowired
    private LogisticsFeignClient logisticsClient;

    public OrderDetailVO getOrderDetail(Long orderId) {
        // 三个独立查询并行执行
        CompletableFuture<UserDTO> userFuture = CompletableFuture
            .supplyAsync(() -> userClient.getById(orderId), executor);

        CompletableFuture<ProductDTO> productFuture = CompletableFuture
            .supplyAsync(() -> productClient.getByOrderId(orderId), executor);

        CompletableFuture<LogisticsDTO> logisticsFuture = CompletableFuture
            .supplyAsync(() -> logisticsClient.getByOrderId(orderId), executor);

        // 等待全部完成,超时2秒
        try {
            CompletableFuture.allOf(userFuture, productFuture, logisticsFuture)
                .get(2, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            // 超时降级:部分数据返回null,前端展示占位
            log.warn("订单详情查询超时, orderId={}", orderId);
        } catch (Exception e) {
            log.error("订单详情查询异常", e);
            throw new ServiceException("查询失败");
        }

        // 组装结果
        OrderDetailVO vo = new OrderDetailVO();
        vo.setUser(userFuture.getNow(null));
        vo.setProduct(productFuture.getNow(null));
        vo.setLogistics(logisticsFuture.getNow(null));
        return vo;
    }
}

Sentinel限流规则与流控策略配置

Sentinel提供QPS限流、线程数限流、关联限流、链路限流等多种流控策略。生产环境通常组合使用QPS限流和线程数限流。

@Configuration
public class SentinelConfig {

    @PostConstruct
    public void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();

        // 规则1:订单创建接口QPS限流
        FlowRule orderRule = new FlowRule();
        orderRule.setResource("createOrder");
        orderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        orderRule.setCount(500);  // 单机QPS上限500
        orderRule.setLimitApp("default");
        // 排队等待:匀速通过,避免突发流量击穿
        orderRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
        orderRule.setMaxQueueingTimeMs(2000);  // 最大排队2秒
        rules.add(orderRule);

        // 规则2:数据库写入线程数限流
        FlowRule dbRule = new FlowRule();
        dbRule.setResource("dbWrite");
        dbRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        dbRule.setCount(50);  // 最大并发线程50
        rules.add(dbRule);

        // 规则3:关联限流 - 写接口限流时同时限制读接口
        FlowRule relatedRule = new FlowRule();
        relatedRule.setResource("queryOrder");
        relatedRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        relatedRule.setCount(1000);
        relatedRule.setStrategy(RuleConstant.STRATEGY_RELATE);
        relatedRule.setRefResource("createOrder");  // 当createOrder QPS高时限制queryOrder
        rules.add(relatedRule);

        FlowRuleManager.loadRules(rules);
    }
}
// 接口注解方式使用Sentinel
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @SentinelResource(
        value = "createOrder",
        blockHandler = "createOrderBlockHandler",
        fallback = "createOrderFallback"
    )
    @PostMapping("/create")
    public Result<OrderVO> createOrder(@RequestBody OrderDTO dto) {
        return Result.success(orderService.create(dto));
    }

    // 限流后处理
    public Result<OrderVO> createOrderBlockHandler(OrderDTO dto, BlockException ex) {
        log.warn("创建订单被限流: {}", dto.getOrderNo());
        return Result.error(429, "系统繁忙,请稍后重试");
    }

    // 降级处理
    public Result<OrderVO> createOrderFallback(OrderDTO dto, Throwable e) {
        log.error("创建订单降级", e);
        return Result.error(503, "服务暂时不可用");
    }
}

熔断降级策略与异常fallback

当下游服务持续超时或报错时,熔断器会快速失败,避免线程堆积导致雪崩。Sentinel熔断策略支持慢调用比例和异常比例两种模式。

@PostConstruct
public void initDegradeRules() {
    List<DegradeRule> rules = new ArrayList<>();

    // 慢调用熔断:RT > 500ms视为慢调用
    DegradeRule slowCallRule = new DegradeRule();
    slowCallRule.setResource("queryOrder");
    slowCallRule.setGrade(CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType());
    slowCallRule.setCount(500);           // 最大RT 500ms
    slowCallRule.setSlowRatioThreshold(0.6);  // 慢调用比例阈值60%
    slowCallRule.setMinRequestAmount(5);  // 最小请求数
    slowCallRule.setStatIntervalMs(10000); // 统计窗口10秒
    slowCallRule.setBreakTimeMs(10000);   // 熔断持续时间10秒
    rules.add(slowCallRule);

    // 异常比例熔断:异常率 > 50%
    DegradeRule errorRule = new DegradeRule();
    errorRule.setResource("queryOrder");
    errorRule.setGrade(CircuitBreakerStrategy.ERROR_RATIO.getType());
    errorRule.setCount(0.5);              // 异常比例50%
    errorRule.setMinRequestAmount(10);
    errorRule.setStatIntervalMs(10000);
    errorRule.setBreakTimeMs(15000);
    rules.add(errorRule);

    DegradeRuleManager.loadRules(rules);
}

接口幂等性与压测验证

高并发场景下重复提交是常见问题。通过Redis实现接口幂等控制,防止重复创建订单。

@Service
public class OrderService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public OrderVO create(OrderDTO dto) {
        String idempotentKey = "order:create:" + dto.getRequestId();
        // SETNX + TTL 实现幂等锁
        Boolean acquired = redisTemplate.opsForValue()
            .setIfAbsent(idempotentKey, "1", 30, TimeUnit.SECONDS);

        if (Boolean.FALSE.equals(acquired)) {
            throw new BusinessException("请勿重复提交");
        }

        try {
            // 业务逻辑
            return doCreate(dto);
        } catch (Exception e) {
            // 失败时删除锁,允许重试
            redisTemplate.delete(idempotentKey);
            throw e;
        }
    }
}

配置完成后使用JMeter或wrk进行压测验证。逐步增加并发线程数,观察线程池队列堆积、Sentinel限流触发、熔断器状态切换是否符合预期。关键指标包括:接口P99延迟、错误率、线程池活跃数、Sentinel拒绝请求数。根据压测结果调整线程池容量和限流阈值,找到吞吐量和延迟的最佳平衡点。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/springboot-gao-bing-fa-she-ji-shi-zhan-xian-cheng-chi-diao/

(0)
小编小编
上一篇 16小时前
下一篇 16小时前

相关推荐