You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于响应式Azure Cosmos Client在Spring Boot中实现吞吐量控制

给PersonRepository配置Cosmos NoSQL吞吐量控制(1500 RU/秒)

要通过Java SDK的ThroughputControlGroupConfig限制Person容器的RU使用率,核心是给Repository关联的Cosmos容器实例启用吞吐量控制配置,步骤如下:

1. 创建吞吐量控制配置实例

首先构建ThroughputControlGroupConfig,设置目标RU、控制组ID和优先级:

ThroughputControlGroupConfig throughputControlConfig = ThroughputControlGroupConfig.builder()
        .groupId("person-container-throughput-group") // 唯一标识控制组
        .targetThroughput(1500) // 限制为1500 RU/秒
        .priority(1) // 优先级,数值越小优先级越高(同一客户端下多控制组时生效)
        .build();

2. 给Person容器启用吞吐量控制

结合Spring Boot的响应式Cosmos Client,在配置类中生成带有控制配置的容器实例:

@Configuration
public class ReactiveCosmosConfig {

    @Autowired
    private ReactiveCosmosClient reactiveCosmosClient;

    @Value("${azure.cosmos.database}")
    private String databaseName;

    @Bean
    public ReactiveCosmosContainer personReactiveContainer() {
        // 获取目标数据库
        ReactiveCosmosDatabase database = reactiveCosmosClient.getDatabase(databaseName);
        // 获取Person容器并启用吞吐量控制
        ReactiveCosmosContainer container = database.getContainer("Person");
        container.enableThroughputControlGroup(throughputControlConfig);
        return container;
    }
}

3. 关联容器到PersonRepository

让Spring Data的ReactivePersonRepository使用上述配置好的容器:

方式1:自定义Repository实例

如果需要手动初始化Repository,直接传入带控制的容器:

@Bean
public ReactivePersonRepository reactivePersonRepository(ReactiveCosmosContainer personReactiveContainer) {
    CosmosEntityInformation<Person, String> entityInfo = new MappingCosmosEntityInformation<>(Person.class);
    ReactiveCosmosTemplate template = new ReactiveCosmosTemplate(reactiveCosmosClient, databaseName, personReactiveContainer);
    return new SimpleReactiveCosmosRepository<>(entityInfo, template);
}

方式2:自动关联Repository接口

如果你的PersonRepository是继承ReactiveCosmosRepository的接口:

@Repository
public interface ReactivePersonRepository extends ReactiveCosmosRepository<Person, String> {
}

只需确保配置类中生成的ReactiveCosmosContainer被Spring容器管理,Spring Data会自动将其关联到对应的Repository(通过容器名称匹配)。

关键说明

  • 吞吐量控制是绑定在容器实例上的,所有通过该实例执行的操作都会受到RU限制
  • 同一个groupId的容器实例会共享配置的吞吐量配额
  • 可以通过Azure Cosmos DB门户的"Metrics"面板验证RU使用率是否被限制在1500以内

内容的提问来源于stack exchange,提问作者DockYard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:45:25