Files
sharp-basic/CONFIGURATION.md
T
2025-12-22 19:50:09 +08:00

487 lines
10 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Sharp-Basic 配置指南
本文档说明 Sharp-Basic 框架的配置约定和最佳实践。
## 目录
- [配置文件模板](#配置文件模板)
- [约定配置节名称](#约定配置节名称)
- [环境变量覆盖](#环境变量覆盖)
- [模块配置详解](#模块配置详解)
- [最佳实践](#最佳实践)
---
## 配置文件模板
Sharp-Basic 提供了完整的配置文件模板:**`appsettings.template.json`**
### 使用方法
1. **复制模板文件**
```bash
cp appsettings.template.json appsettings.json
```
2. **根据项目需要选择性保留配置**
- 只使用数据库?保留 `Database` 节
- 需要PLC通信?保留 `Plc:Siemens` 节
- 不需要的配置可以删除
3. **修改配置值**
```json
{
"Database": {
"Provider": "SqlServer",
"ConnectionString": "你的数据库连接字符串"
},
"Plc": {
"Siemens": {
"IpAddress": "你的PLC IP地址"
}
}
}
```
---
## 约定配置节名称
Sharp-Basic 遵循 **"约定优于配置"** 原则,每个模块都有固定的配置节名称:
### 核心模块
| 模块 | 配置节名称 | 说明 | 必填字段 |
|------|------------|------|----------|
| **System** | `System` | 系统级HTTP配置 | `HTTPIp`, `HttpPort` |
| **Database** | `Database` | 数据库连接配置 | `Provider`, `ConnectionString` |
| **Logging** | `Logging` | 日志级别配置 | `LogLevel` |
| **SharpLog** | `SharpLog` | Sharp日志扩展 | 无(全部可选) |
### 网络模块
| 模块 | 配置节名称 | 说明 | 必填字段 |
|------|------------|------|----------|
| **NetClient** | `NetClient` | HTTP客户端配置 | 无(可使用System默认值) |
| **NetServer** | `NetServer` | HTTP服务端配置 | 无(可使用System默认值) |
### IoT模块
| 模块 | 配置节名称 | 说明 | 必填字段 |
|------|------------|------|----------|
| **Plc.Siemens** | `Plc:Siemens` | 西门子PLC配置 | `IpAddress`, `CpuType` |
| **SerialPort** | `SerialPort` | 串口通信配置 | `PortName`, `BaudRate` |
### 工具模块
| 模块 | 配置节名称 | 说明 | 必填字段 |
|------|------------|------|----------|
| **Process** | `Process` | 进程执行配置 | 无(全部可选) |
| **Python** | `Python` | Python脚本配置 | 无(全部可选) |
| **Cache** | `Cache` | 缓存配置 | 无(全部可选) |
| **EventBus** | `EventBus` | 事件总线配置 | 无(全部可选) |
---
## 环境变量覆盖
所有配置都可以通过环境变量覆盖,格式:`SHARP__{节名}__{键名}`
### 覆盖规则
- 使用双下划线 `__` 分隔层级
- 所有字母必须大写(Windows不区分大小写,Linux区分)
- 冒号 `:` 用双下划线 `__` 替代
### 示例
#### 覆盖数据库配置
```bash
# Windows (PowerShell)
$env:SHARP__Database__Provider="Sqlite"
$env:SHARP__Database__ConnectionString="Data Source=test.db"
# Linux/macOS
export SHARP__Database__Provider=Sqlite
export SHARP__Database__ConnectionString="Data Source=test.db"
```
#### 覆盖PLC配置
```bash
# Windows (PowerShell)
$env:SHARP__Plc__Siemens__IpAddress="192.168.1.200"
$env:SHARP__Plc__Siemens__CpuType="S71500"
# Linux/macOS
export SHARP__Plc__Siemens__IpAddress=192.168.1.200
export SHARP__Plc__Siemens__CpuType=S71500
```
#### 覆盖System配置
```bash
# Windows (PowerShell)
$env:SHARP__System__HttpPort="9090"
# Linux/macOS
export SHARP__System__HttpPort=9090
```
### 优先级
配置优先级从高到低:
1. **环境变量** - 最高优先级
2. **appsettings.{Environment}.json** - 环境特定配置
3. **appsettings.json** - 默认配置
---
## 模块配置详解
### 1. 数据库配置 (Database)
#### 最简配置
```json
{
"Database": {
"Provider": "Sqlite",
"ConnectionString": "Data Source=app.db"
}
}
```
#### 代码中使用
```csharp
var config = ConfigBuilder.CreateDefault().Configuration;
services.AddSharpDatabase<AppDbContext>(config); // 自动读取 Database 节
```
#### 支持的数据库提供程序
- `SqlServer` - Microsoft SQL Server
- `Sqlite` - SQLite
- `PostgreSQL` - PostgreSQL
- `MySql` - MySQL/MariaDB
- `InMemory` - 内存数据库(仅用于测试)
---
### 2. PLC配置 (Plc:Siemens)
#### 最简配置
```json
{
"Plc": {
"Siemens": {
"IpAddress": "192.168.1.100",
"CpuType": "S71200"
}
}
}
```
#### 代码中使用
```csharp
var config = ConfigBuilder.CreateDefault().Configuration;
services.AddSiemensPlc(config.GetSection("Plc:Siemens"));
```
#### 支持的CPU类型
- `S71200` - S7-1200 系列
- `S71500` - S7-1500 系列
- `S7300` - S7-300 系列
- `S7400` - S7-400 系列
- `S7200` - S7-200 系列
- `S7200Smart` - S7-200 Smart 系列
---
### 3. 日志配置 (Logging & SharpLog)
#### 最简配置
```json
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"SharpLog": {
"LogFilePath": "logs/app-.log",
"RollingInterval": "Day"
}
}
```
#### 代码中使用
```csharp
services.AddLogging(b => b.AddSharpLog()); // 自动读取 SharpLog 节
```
---
### 4. HTTP配置 (System, NetClient, NetServer)
#### System配置(共享默认值)
```json
{
"System": {
"HTTPIp": "127.0.0.1",
"HttpPort": 8080,
"TimeoutSeconds": 30,
"Scheme": "http"
}
}
```
#### NetClient配置(可选,留空则使用System默认值)
```json
{
"NetClient": {
"BaseAddress": "http://api.example.com",
"Timeout": "00:00:30",
"EnableLogging": true
}
}
```
#### NetServer配置(可选,留空则使用System默认值)
```json
{
"NetServer": {
"ListenUrls": [
"http://localhost:8080/"
]
}
}
```
---
## 最佳实践
### 1. 按需配置
**只保留需要的配置节**,不要保留所有模板内容:
```json
{
// ❌ 不好:保留了不使用的配置
"Database": { ... },
"Plc": { ... },
"SerialPort": { ... },
"Python": { ... }
}
{
// ✅ 好:只保留需要的配置
"Database": { ... },
"Logging": { ... }
}
```
### 2. 使用环境特定配置
为不同环境创建不同的配置文件:
```
appsettings.json # 默认配置
appsettings.Development.json # 开发环境
appsettings.Production.json # 生产环境
appsettings.Testing.json # 测试环境
```
### 3. 敏感信息使用环境变量
**不要在配置文件中存储敏感信息**(密码、密钥等):
```bash
# ✅ 好:使用环境变量
export SHARP__Database__ConnectionString="Server=prod;User=sa;Password=SecretPass123"
export SHARP__Plc__Siemens__IpAddress="192.168.1.100"
```
```json
// ❌ 不好:敏感信息写在配置文件
{
"Database": {
"ConnectionString": "Server=prod;User=sa;Password=SecretPass123"
}
}
```
### 4. 添加注释说明
在配置文件中添加注释(JSON5格式,或删除注释后部署):
```json
{
// 数据库配置 - 生产环境使用SQL Server
"Database": {
"Provider": "SqlServer",
"ConnectionString": "Server=.;Database=MyApp;..."
},
// PLC配置 - 车间1号PLC
"Plc": {
"Siemens": {
"IpAddress": "192.168.1.100", // 车间1号PLC
"CpuType": "S71200"
}
}
}
```
### 5. 配置验证
Sharp-Basic 会在启动时验证必填配置项:
```csharp
// ✅ 好:配置缺失时会抛出清晰的异常
services.AddSharpDatabase<AppDbContext>(config);
// 异常:未找到数据库连接字符串配置: Database:ConnectionString
services.AddSiemensPlc(config.GetSection("Plc:Siemens"));
// 异常:未配置PLC IP地址
```
---
## 快速参考
### 典型WPF应用配置
```json
{
"System": {
"HTTPIp": "127.0.0.1",
"HttpPort": 8080
},
"Database": {
"Provider": "Sqlite",
"ConnectionString": "Data Source=app.db"
},
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"SharpLog": {
"LogFilePath": "logs/app-.log",
"RollingInterval": "Day"
}
}
```
### 工业IoT应用配置
```json
{
"System": {
"HTTPIp": "0.0.0.0",
"HttpPort": 8080
},
"Database": {
"Provider": "SqlServer",
"ConnectionString": "Server=.;Database=ScadaDB;Trusted_Connection=True;"
},
"Plc": {
"Siemens": {
"IpAddress": "192.168.1.100",
"CpuType": "S71200",
"MonitorInterval": 500,
"AutoReconnect": true
}
},
"SerialPort": {
"PortName": "COM1",
"BaudRate": 9600
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Plc.Siemens": "Debug"
}
}
}
```
### Web服务应用配置
```json
{
"System": {
"HTTPIp": "0.0.0.0",
"HttpPort": 5000,
"Scheme": "https"
},
"Database": {
"Provider": "PostgreSQL",
"ConnectionString": "Host=localhost;Database=myapi;Username=postgres;Password=***"
},
"NetServer": {
"ListenUrls": [
"https://0.0.0.0:5000/",
"http://0.0.0.0:5001/"
],
"ShowDetailedErrors": false
},
"Cache": {
"DefaultExpirationSeconds": 300,
"SizeLimit": 10000
}
}
```
---
## 相关文档
- [appsettings.template.json](appsettings.template.json) - 完整配置模板
- [Config模块README](src/Sharp/Config/README.md) - 配置管理详解
- [Data模块README](src/Sharp/Data/README.md) - 数据库配置详解
- [Plc.Siemens模块README](src/Sharp/Plc.Siemens/README.md) - PLC配置详解
---
## 故障排查
### 问题:找不到配置节
**错误信息**:
```
未找到数据库连接字符串配置: Database:ConnectionString
```
**解决方法**:
1. 检查配置文件名是否为 `appsettings.json`
2. 检查配置节名称是否正确(区分大小写)
3. 检查配置文件是否在项目根目录
4. 检查配置文件的 "复制到输出目录" 设置
### 问题:环境变量不生效
**原因**:环境变量格式错误
**正确格式**:
```bash
# ✅ 正确:双下划线分隔
SHARP__Database__Provider=Sqlite
# ❌ 错误:单下划线
SHARP_Database_Provider=Sqlite
# ❌ 错误:使用冒号
SHARP:Database:Provider=Sqlite
```
### 问题:配置被覆盖
**检查优先级**:
1. 先检查环境变量
2. 再检查 appsettings.{Environment}.json
3. 最后检查 appsettings.json
---
**版本**: 1.0.0
**更新日期**: 2025-12-22