示例代码来自https://github.com/easynet-cn/batata,本人的一个想兼容nacos(https://github.com/alibaba/nacos)rust项目。其中数据entity是使用sea-orm cli生成,具体可以参考文档https://www.sea-ql.org/SeaORM/docs/next/generate-entity/sea-orm-cli/
构造数据库链接池,链接池配置类似HikariCP(https://github.com/brettwooldridge/HikariCP)
let settings = Config::builder()
.add_source(config::File::with_name("conf/application.yml"))
.build()
.unwrap();
let db_num = settings.get_int("db.num").unwrap();
let mut conns: Vec<DatabaseConnection> = Vec::new();
let max_connections = settings
.get_int("db.pool.config.maximumPoolSize")
.unwrap_or(100) as u32;
let min_connections = settings
.get_int("db.pool.config.minimumPoolSize")
.unwrap_or(1) as u32;
let connect_timeout = settings
.get_int("db.pool.config.connectionTimeout")
.unwrap_or(30) as u64;
let acquire_timeout = settings
.get_int("db.pool.config.initializationFailTimeout")
.unwrap_or(1) as u64;
let idle_timeout = settings.get_int("db.pool.config.idleTimeout").unwrap_or(10) as u64;
let max_lifetime = settings.get_int("db.pool.config.maxLifetime").unwrap_or(30) as u64;
for i in 0..db_num {
let url = &settings
.get_string(format!("db.url.{}", i).as_str())
.unwrap();
let mut opt = ConnectOptions::new(url);
opt.max_connections(max_connections)
.min_connections(min_connections)
.connect_timeout(Duration::from_secs(connect_timeout))
.acquire_timeout(Duration::from_secs(acquire_timeout))
.idle_timeout(Duration::from_secs(idle_timeout))
.max_lifetime(Duration::from_secs(max_lifetime))
.sqlx_logging(true)
.sqlx_logging_level(log::LevelFilter::Info);
let db = Database::connect(opt).await.unwrap();
conns.push(db);
}
条件查询,示例为查询所有namespace
let tenant_infos: Vec<tenant_info::Model> = tenant_info::Entity::find()
.filter(tenant_info::Column::Kp.eq(NamespaceOperationService::DEFAULT_KP))
.all(db)
.await
.unwrap();
in查询,示例为根据namespace ID集合,查询配置数量
#[derive(Debug, FromQueryResult)]
struct SelectResult {
tenant_id: Option<String>,
count: i32,
}
let mut config_infos = config_info::Entity::find()
.select_only()
.column(config_info::Column::TenantId)
.column_as(config_info::Column::Id.count(), "count")
.filter(config_info::Column::TenantId.is_in(tenant_ids))
.filter(config_info::Column::TenantId.is_not_null())
.into_model::<SelectResult>()
.all(db)
.await
.unwrap()
.iter()
.map(|x| (x.tenant_id.clone().unwrap_or_default(), x.count))
.collect::<HashMap<String, i32>>();