C#配置全面詳解:從傳統方式到現代配置系統

C#配置全面詳解:從傳統方式到現代配置系統

在軟件開發中,配置是指應用程序運行時可調整的參數集合,如數據庫連接字符串、API 地址、日志級別等。將這些參數從代碼中分離出來,便于在不修改代碼的情況下調整應用行為。C# 提供了多種配置管理方式,從傳統的 XML 配置文件到現代的多源配置系統,每種方式都有其適用場景。本文將全面介紹 C# 中的配置技術,幫助開發者根據項目需求選擇合適的配置方案。

一、配置基礎與核心概念

1. 為什么需要配置管理

硬編碼配置存在諸多問題:

  • 修改配置需要重新編譯代碼
  • 不同環境(開發、測試、生產)需要不同配置時難以維護
  • 敏感信息(如密碼、密鑰)暴露在代碼中不安全

良好的配置管理應具備:

  • 易于修改,無需重新編譯
  • 支持不同環境的配置隔離
  • 能保護敏感信息
  • 便于擴展和維護

2. C# 配置技術演進

C# 配置技術經歷了多個階段:

  • 傳統方式.NET Framework 中的app.configweb.config
  • 現代方式.NET Core引入的新配置系統,支持多源配置、依賴注入等
  • 云原生方式:結合環境變量、服務發現、配置中心等

二、.NET Framework傳統配置方式

1. 配置文件結構

.NET Framework應用使用 XML 格式的配置文件:

  • 控制臺 / 桌面應用:app.config(編譯后生成[程序名].exe.config
  • Web 應用:web.config

典型的app.config結構:

<?xml version="1.0" encoding="utf-8" ?>
<configuration><!-- 應用設置 --><appSettings><add key="MaxRetries" value="3" /><add key="LogLevel" value="Info" /><add key="ApiUrl" value="https://api.example.com" /></appSettings><!-- 連接字符串 --><connectionStrings><add name="DefaultConnection"connectionString="Server=localhost;Database=Test;Integrated Security=True"providerName="System.Data.SqlClient" /></connectionStrings><!-- 其他配置節 --><system.web><!-- Web相關配置 --></system.web></configuration>

2. 讀取配置(ConfigurationManager)

使用System.Configuration命名空間下的ConfigurationManager類讀取配置,需引用System.Configuration程序集。

using System;
using System.Configuration;class TraditionalConfigDemo
{static void Main(){// 讀取appSettings配置string maxRetries = ConfigurationManager.AppSettings["MaxRetries"];string logLevel = ConfigurationManager.AppSettings["LogLevel"];string apiUrl = ConfigurationManager.AppSettings["ApiUrl"];Console.WriteLine($"最大重試次數: {maxRetries}");Console.WriteLine($"日志級別: {logLevel}");Console.WriteLine($"API地址: {apiUrl}");// 讀取連接字符串ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"];if (connectionString != null){Console.WriteLine($"連接字符串: {connectionString.ConnectionString}");Console.WriteLine($"提供程序: {connectionString.ProviderName}");}}
}

3. 自定義配置節

對于復雜配置,可以定義自定義配置節:

<!-- 配置文件中定義自定義配置節 -->
<configuration><!-- 注冊自定義配置節 --><configSections><section name="EmailSettings" type="ConfigDemo.EmailSettingsSection, ConfigDemo" /></configSections><!-- 自定義配置內容 --><EmailSettings><SmtpServer address="smtp.example.com" port="587" /><Credentials username="user@example.com" password="password" /><Options enableSsl="true" timeout="30000" /></EmailSettings>
</configuration>

對應的 C# 類:

using System.Configuration;// 自定義配置節
public class EmailSettingsSection : ConfigurationSection
{[ConfigurationProperty("SmtpServer")]public SmtpServerElement SmtpServer => (SmtpServerElement)this["SmtpServer"];[ConfigurationProperty("Credentials")]public CredentialsElement Credentials => (CredentialsElement)this["Credentials"];[ConfigurationProperty("Options")]public OptionsElement Options => (OptionsElement)this["Options"];
}// 配置元素
public class SmtpServerElement : ConfigurationElement
{[ConfigurationProperty("address", IsRequired = true)]public string Address => (string)this["address"];[ConfigurationProperty("port", DefaultValue = 25)]public int Port => (int)this["port"];
}public class CredentialsElement : ConfigurationElement
{[ConfigurationProperty("username", IsRequired = true)]public string Username => (string)this["username"];[ConfigurationProperty("password", IsRequired = true)]public string Password => (string)this["password"];
}public class OptionsElement : ConfigurationElement
{[ConfigurationProperty("enableSsl", DefaultValue = false)]public bool EnableSsl => (bool)this["enableSsl"];[ConfigurationProperty("timeout", DefaultValue = 10000)]public int Timeout => (int)this["timeout"];
}// 讀取自定義配置節
class CustomConfigDemo
{static void Main(){EmailSettingsSection emailSettings =(EmailSettingsSection)ConfigurationManager.GetSection("EmailSettings");if (emailSettings != null){Console.WriteLine($"SMTP服務器: {emailSettings.SmtpServer.Address}:{emailSettings.SmtpServer.Port}");Console.WriteLine($"用戶名: {emailSettings.Credentials.Username}");Console.WriteLine($"啟用SSL: {emailSettings.Options.EnableSsl}");}}
}

三、.NET Core/.NET 5 + 現代配置系統

.NET Core 引入了全新的配置系統,具有以下特點:

  • 支持多種配置源(JSON、XML、INI、環境變量、命令行等)
  • 配置值可以被后續源覆蓋(配置優先級)
  • 支持配置綁定到實體類
  • 集成依賴注入系統
  • 支持配置熱重載

1. 配置源與優先級

默認配置源及優先級(從低到高):

  1. appsettings.json
  2. appsettings.[Environment].json(如appsettings.Development.json
  3. 用戶 Secrets(僅開發環境)
  4. 環境變量
  5. 命令行參數

2. 控制臺應用中的配置

  • 基本使用
  1. 創建appsettings.json文件(設置 “復制到輸出目錄” 為 “如果較新則復制”):

    {
    "AppSettings": {
    "MaxRetries": 3,
    "LogLevel": "Info",
    "ApiUrl": "https://api.example.com"
    },
    "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=Test;Integrated Security=True"
    },
    "EmailSettings": {
    "SmtpServer": {"Address": "smtp.example.com","Port": 587
    },
    "Credentials": {"Username": "user@example.com","Password": "password"
    },
    "Options": {"EnableSsl": true,"Timeout": 30000
    }
    }
    }
    
  2. 安裝必要的 NuGet 包:

    Install-Package Microsoft.Extensions.Configuration
    Install-Package Microsoft.Extensions.Configuration.Json
    Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables
    Install-Package Microsoft.Extensions.Configuration.CommandLine
    
  3. 讀取配置:

    using System;
    using Microsoft.Extensions.Configuration;
    using System.IO;class ConsoleConfigDemo
    {
    static void Main(string[] args)
    {// 構建配置IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false, reloadOnChange: true).AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true).AddEnvironmentVariables().AddCommandLine(args).Build();// 直接讀取配置string maxRetries = config["AppSettings:MaxRetries"];string apiUrl = config["AppSettings:ApiUrl"];string connectionString = config["ConnectionStrings:DefaultConnection"];Console.WriteLine($"最大重試次數: {maxRetries}");Console.WriteLine($"API地址: {apiUrl}");Console.WriteLine($"連接字符串: {connectionString}");// 讀取嵌套配置string smtpAddress = config["EmailSettings:SmtpServer:Address"];int smtpPort = int.Parse(config["EmailSettings:SmtpServer:Port"]);Console.WriteLine($"SMTP服務器: {smtpAddress}:{smtpPort}");
    }
    }
    

3. 配置綁定到實體類

將配置綁定到實體類更便于使用:

using Microsoft.Extensions.Configuration;// 定義實體類
public class AppSettings
{public int MaxRetries { get; set; }public string LogLevel { get; set; }public string ApiUrl { get; set; }
}public class ConnectionStrings
{public string DefaultConnection { get; set; }
}public class SmtpServerSettings
{public string Address { get; set; }public int Port { get; set; }
}public class CredentialsSettings
{public string Username { get; set; }public string Password { get; set; }
}public class EmailOptions
{public bool EnableSsl { get; set; }public int Timeout { get; set; }
}public class EmailSettings
{public SmtpServerSettings SmtpServer { get; set; }public CredentialsSettings Credentials { get; set; }public EmailOptions Options { get; set; }
}// 綁定并使用配置
class ConfigBindingDemo
{static void Main(string[] args){IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();// 綁定到實體類AppSettings appSettings = new AppSettings();config.GetSection("AppSettings").Bind(appSettings);ConnectionStrings connectionStrings = new ConnectionStrings();config.GetSection("ConnectionStrings").Bind(connectionStrings);EmailSettings emailSettings = config.GetSection("EmailSettings").Get<EmailSettings>(); // 另一種綁定方式// 使用綁定后的配置Console.WriteLine($"最大重試次數: {appSettings.MaxRetries}");Console.WriteLine($"連接字符串: {connectionStrings.DefaultConnection}");Console.WriteLine($"SMTP服務器: {emailSettings.SmtpServer.Address}:{emailSettings.SmtpServer.Port}");Console.WriteLine($"啟用SSL: {emailSettings.Options.EnableSsl}");}
}

4. ASP.NET Core 中的配置

ASP.NET Core 自動構建配置系統,可直接注入IConfiguration使用:

// 在Program.cs中(ASP.NET Core 6+)
var builder = WebApplication.CreateBuilder(args);// 配置已自動加載,可在此處添加額外配置源
builder.Configuration.AddIniFile("appsettings.ini", optional: true);var app = builder.Build();// 在控制器中使用
app.MapGet("/config", (IConfiguration config) =>
{var logLevel = config["AppSettings:LogLevel"];var connectionString = config["ConnectionStrings:DefaultConnection"];return new{LogLevel = logLevel,ConnectionString = connectionString};
});app.Run();

在控制器中使用:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;public class ConfigController : Controller
{private readonly IConfiguration _config;// 注入IConfigurationpublic ConfigController(IConfiguration config){_config = config;}public IActionResult Index(){string apiUrl = _config["AppSettings:ApiUrl"];// 使用配置...return View();}}

四、選項模式(Options Pattern)

選項模式是.NET Core推薦的配置使用方式,通過強類型訪問配置,提供更好的封裝和可測試性。

1. 基本使用

  • 定義選項類:

    using Microsoft.Extensions.Options;// 選項類
    public class AppSettingsOptions
    {
    public const string AppSettings = "AppSettings";
    public int MaxRetries { get; set; }
    public string LogLevel { get; set; }
    public string ApiUrl { get; set; }
    }public class EmailSettingsOptions
    {
    public const string EmailSettings = "EmailSettings";
    public SmtpServerSettings SmtpServer { get; set; }
    public CredentialsSettings Credentials { get; set; }
    public EmailOptions Options { get; set; }
    }
    
  • 在依賴注入中配置選項:

    // 控制臺應用
    var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");IConfiguration config = builder.Build();// 創建服務集合
    var services = new ServiceCollection();// 配置選項
    services.Configure<AppSettingsOptions>(config.GetSection(AppSettingsOptions.AppSettings));
    services.Configure<EmailSettingsOptions>(config.GetSection(EmailSettingsOptions.EmailSettings));// 注冊需要使用選項的服務
    services.AddSingleton<MyService>();// 構建服務提供器
    using (var serviceProvider = services.BuildServiceProvider())
    {
    var myService = serviceProvider.GetRequiredService<MyService>();
    myService.DoWork();
    }
    
  • 使用選項:

    public class MyService
    {
    private readonly AppSettingsOptions _appSettings;
    private readonly IOptions<EmailSettingsOptions> _emailSettings;// 注入選項
    public MyService(IOptions<AppSettingsOptions> appSettings,IOptions<EmailSettingsOptions> emailSettings)
    {_appSettings = appSettings.Value;_emailSettings = emailSettings;
    }public void DoWork()
    {Console.WriteLine($"最大重試次數: {_appSettings.MaxRetries}");Console.WriteLine($"SMTP服務器: {_emailSettings.Value.SmtpServer.Address}");
    }
    }
    

2. 三種選項接口

.NET Core提供三種選項接口,適用于不同場景:

  • IOptions

    • 單例模式,應用啟動時初始化
    • 不支持配置熱重載
    • 適用于啟動后不會變化的配置
  • IOptionsSnapshot

    • 作用域模式,每個請求 / 作用域重新計算
    • 支持配置熱重載
    • 適用于 Web 應用,每個請求可能需要最新配置
  • IOptionsMonitor

    • 單例模式,但支持配置熱重載
    • 可通過OnChange方法監聽配置變化
    • 適用于長時間運行的服務,需要實時響應配置變化
// 使用IOptionsMonitor監聽配置變化
public class MonitorService
{private readonly IOptionsMonitor<AppSettingsOptions> _monitor;private IDisposable _changeToken;public MonitorService(IOptionsMonitor<AppSettingsOptions> monitor){_monitor = monitor;// 監聽配置變化_changeToken = _monitor.OnChange((newValue, name) =>{Console.WriteLine($"配置已變化: 新的最大重試次數 {newValue.MaxRetries}");});}public void ShowSettings(){Console.WriteLine($"當前日志級別: {_monitor.CurrentValue.LogLevel}");}// 清理資源public void Dispose(){_changeToken?.Dispose();}
}

五、其他配置源

1. 環境變量

環境變量是容器化部署(如 Docker、Kubernetes)中常用的配置方式:

// 添加環境變量配置源
var config = new ConfigurationBuilder().AddEnvironmentVariables().Build();// 讀取環境變量
// 環境變量名通常使用下劃線分隔,如AppSettings__MaxRetries對應配置中的AppSettings:MaxRetries
string maxRetries = config["AppSettings__MaxRetries"];

在 Docker 中設置環境變量:

ENV AppSettings__MaxRetries=5ENV ConnectionStrings__DefaultConnection="Server=db;Database=Test;User Id=sa;Password=password"

2. 命令行參數

命令行參數可用于臨時覆蓋配置:

// 添加命令行配置源
var config = new ConfigurationBuilder().AddCommandLine(args).Build();

運行程序時傳遞參數:

dotnet MyApp.dll --AppSettings:MaxRetries 5 --ConnectionStrings:DefaultConnection "Server=..."

3. INI 文件

INI 文件適合簡單的鍵值對配置:

; appsettings.ini[AppSettings]
MaxRetries=3
LogLevel=Info
ApiUrl=https://api.example.com[ConnectionStrings]
DefaultConnection=Server=localhost;Database=Test;Integrated Security=True

讀取 INI 文件:

var config = new ConfigurationBuilder().AddIniFile("appsettings.ini", optional: true, reloadOnChange: true).Build();

4. XML 文件

除了傳統的app.config,新配置系統也支持讀取 XML 文件:

<!-- appsettings.xml -->
<configuration><AppSettings><MaxRetries>3</MaxRetries><LogLevel>Info</LogLevel></AppSettings><ConnectionStrings><DefaultConnection>Server=localhost;Database=Test;</DefaultConnection></ConnectionStrings>
</configuration>

讀取 XML 文件:

var config = new ConfigurationBuilder().AddXmlFile("appsettings.xml", optional: true, reloadOnChange: true).Build();

六、配置高級特性

1. 配置熱重載

配置熱重載允許應用在不重啟的情況下讀取更新后的配置:

// 啟用熱重載
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json", reloadOnChange: true) // 啟用熱重載.Build();// 監控配置變化
var changeToken = config.GetReloadToken();
changeToken.RegisterChangeCallback(state =>
{Console.WriteLine("配置已更新!");// 重新獲取配置// ...}, null);

ASP.NET Core 中使用IOptionsSnapshotIOptionsMonitor自動獲取熱重載的配置。

2. 開發環境用戶密鑰

為避免將開發環境的敏感信息提交到代碼庫,可使用用戶密鑰(User Secrets):

  • 初始化用戶密鑰(在項目目錄執行):
    dotnet user-secrets init
    
  • 設置密鑰:
    dotnet user-secrets set "Credentials:Password" "dev-password"
    
  • 在代碼中使用:
    // 自動讀取用戶密鑰(僅在開發環境生效)
    var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .AddUserSecrets<Program>() // 傳入任意類型以確定項目
    .Build();string password = config["Credentials:Password"];
    

3. 敏感配置加密

敏感信息(如密碼、API 密鑰)不應明文存儲,可使用 DPAPI 或 Azure Key Vault 等進行加密。

  • 使用 DataProtection 加密配置

    using Microsoft.AspNetCore.DataProtection;
    using Microsoft.Extensions.DependencyInjection;// 加密配置
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"C:keys"))
    .SetApplicationName("MyApp");var services = serviceCollection.BuildServiceProvider();
    var protector = services.GetDataProtectionProvider().CreateProtector("ConfigProtection");// 加密
    string plainText = "sensitive-password";
    string encryptedText = protector.Protect(plainText);// 解密
    string decryptedText = protector.Unprotect(encryptedText);
    
  • Azure Key Vault
    對于云部署,推薦使用 Azure Key Vault 存儲敏感配置:

// 安裝包:Install-Package Azure.Extensions.AspNetCore.Configuration.Secrets
var config = new ConfigurationBuilder().AddAzureKeyVault(new Uri("https://myvault.vault.azure.net/"),new DefaultAzureCredential()).Build();

七、多環境配置管理

應用在不同環境(開發、測試、生產)通常需要不同配置,.NET Core 提供了環境區分機制。

1. 環境變量指定環境

通過ASPNETCORE_ENVIRONMENT(Web 應用)或DOTNET_ENVIRONMENT(控制臺應用)環境變量指定當前環境:

# 開發環境
set ASPNETCORE_ENVIRONMENT=Development# 生產環境
set ASPNETCORE_ENVIRONMENT=Production

在 Docker 中設置:

ENV ASPNETCORE_ENVIRONMENT=Production

2. 環境特定配置文件

創建環境特定的配置文件,命名格式為appsettings.[Environment].json

  • appsettings.Development.json:開發環境配置
  • appsettings.Test.json:測試環境配置
  • appsettings.Production.json:生產環境配置

配置文件加載順序:

  1. appsettings.json(基礎配置)
  2. appsettings.[Environment].json(環境特定配置,覆蓋基礎配置)
// 加載環境特定配置
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false).AddJsonFile($"appsettings.{env}.json", optional: true).Build();

3. ASP.NET Core 中配置多環境

ASP.NET Core 自動處理多環境配置,可在Program.cs中針對不同環境進行配置:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();// 根據環境配置中間件
if (app.Environment.IsDevelopment())
{app.UseDeveloperExceptionPage(); // 開發環境顯示詳細錯誤頁
}
else
{app.UseExceptionHandler("/Error"); // 生產環境使用自定義錯誤頁app.UseHsts(); // 生產環境啟用HSTS
}// 其他中間件配置
app.UseHttpsRedirection();
app.UseStaticFiles();// ...
app.Run();

八、最佳實踐與常見問題

1. 最佳實踐

  • 分離配置與代碼:所有可配置參數都應放在配置文件中,避免硬編碼
  • 敏感信息保護:密碼、密鑰等敏感信息應加密存儲或使用環境變量、密鑰管理服務
  • 使用選項模式:優先使用IOptions<T>而非直接訪問IConfiguration,提高可測試性
  • 合理組織配置結構:按功能模塊劃分配置節點,如DatabaseLoggingExternalServices
  • 配置驗證:對配置進行驗證,確保應用啟動時所有必要配置都已正確設置
// 配置驗證示例(使用DataAnnotations)
public class AppSettingsOptions : IValidatableObject
{[Required]public int MaxRetries { get; set; }[Required][Url]public string ApiUrl { get; set; }public IEnumerable<ValidationResult> Validate(ValidationContext validationContext){if (MaxRetries < 0 || MaxRetries > 10){yield return new ValidationResult("最大重試次數必須在0-10之間",new[] { nameof(MaxRetries) });}}
}// 在依賴注入中啟用驗證
services.AddOptions<AppSettingsOptions>().Bind(config.GetSection(AppSettingsOptions.AppSettings)).ValidateDataAnnotations() // 啟用DataAnnotations驗證.ValidateOnStart(); // 應用啟動時驗證

2. 常見問題

  • 配置未更新

    • 檢查配置文件的 “復制到輸出目錄” 屬性是否正確
    • 確保使用了支持熱重載的選項接口(IOptionsSnapshotIOptionsMonitor
    • 驗證配置源的優先級,是否有其他源覆蓋了配置
  • 敏感信息泄露

    • 不要將敏感信息提交到代碼庫,使用用戶密鑰或環境變量
    • 生產環境配置文件應限制訪問權限
    • 考慮使用加密或密鑰管理服務
  • 配置綁定失敗

    • 檢查配置文件中的鍵名與實體類屬性名是否一致(大小寫敏感)
    • 確保配置值的類型與實體類屬性類型匹配(如字符串不能轉換為整數)
    • 使用IOptions<TOptions>.Value時檢查是否為null
  • 多環境配置不生效

    • 檢查環境變量是否正確設置(ASPNETCORE_ENVIRONMENT
    • 驗證環境特定配置文件的名稱是否正確
    • 檢查配置文件的加載順序是否正確

九、總結

C# 提供了從傳統 XML 配置到現代多源配置系統的完整解決方案:

  • 傳統.NET Framework:使用app.config/web.configConfigurationManager,適合維護舊項目
  • .NET Core/.NET 5+:采用新配置系統,支持多種配置源、熱重載和依賴注入,是新項目的首選
  • 選項模式:通過IOptions<T>系列接口提供強類型配置訪問,提高代碼可維護性和可測試性
  • 多環境管理:通過環境變量和環境特定配置文件,輕松實現不同環境的配置隔離

選擇合適的配置方式應根據項目類型(傳統框架還是現代框架)、部署環境(本地還是云原生)、團隊習慣等因素綜合考慮。無論采用哪種方式,保持配置的清晰組織、敏感信息的安全保護以及配置的可擴展性都是關鍵原則。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/88085.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/88085.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/88085.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據中臺架構解析:湖倉一體的實戰設計

目錄 一、數據中臺與湖倉一體架構是什么 1. 數據中臺 2. 湖倉一體架構 3. 湖倉一體在數據中臺里的價值 二、湖倉一體架構的核心部件 1. 數據湖 2. 數據倉庫 3. 數據集成工具 4. 數據分析與處理引擎 三、湖倉一體架構實戰設計 1. 需求分析與規劃 2. 數據湖建設 3. …

SQL Server表分區技術詳解

表分區概述 表分區是將大型數據庫表物理分割為多個較小單元的技術,邏輯上仍表現為單一實體。該技術通過水平分割數據顯著提升查詢性能,尤其針對TB級數據表可降低90%的響應時間。典型應用場景包含訂單歷史表、日志記錄表等具有明顯時間特征的業務數據,以及需要定期歸檔的審計…

WHIP(WebRTC HTTP Ingestion Protocol)詳解

WHIP&#xff08;WebRTC HTTP Ingestion Protocol&#xff09;詳解 WHIP&#xff08;WebRTC HTTP Ingestion Protocol&#xff09;是一種基于 HTTP 的協議&#xff0c;用于將 WebRTC 媒體流推送到媒體服務器&#xff08;如 SRS、Janus、LiveKit&#xff09;。它是為簡化 WebRT…

圖像噪點消除:用 OpenCV 實現多種濾波方法

在圖像處理中&#xff0c;噪點是一個常見的問題。它可能是由于圖像采集設備的缺陷、傳輸過程中的干擾&#xff0c;或者是光照條件不佳引起的。噪點會影響圖像的質量和后續處理的效果&#xff0c;因此消除噪點是圖像預處理的重要步驟之一。本文將介紹如何使用 OpenCV 實現幾種常…

AI的Prompt提示詞:英文寫好還是中文好?

在與AI人大模型交互時,Prompt(提示詞)的質量直接決定了輸出的精準度和有效性。一個常見的問題是:究竟是用英文寫Prompt好,還是用中文寫更好?這并非一個簡單的二元選擇,而是涉及到語言模型的底層邏輯、表達的精確性以及個人使用習慣的綜合考量。 英文Prompt的優勢 模型訓…

react的條件渲染【簡約風5min】

const flag1true; console.log(flag1&&hello); console.log(flag1||hello); const flag20; console.log(flag2&&hello); console.log(flag2||hello); // &&運算符&#xff0c;如果第一個條件為假&#xff0c;則返回第一個條件&#xff0c;否則返回第二…

【RK3568+PG2L50H開發板實驗例程】FPGA部分 | 紫光同創 IP core 的使用及添加

本原創文章由深圳市小眼睛科技有限公司創作&#xff0c;版權歸本公司所有&#xff0c;如需轉載&#xff0c;需授權并注明出處&#xff08;www.meyesemi.com)1.實驗簡介實驗目的&#xff1a;了解 PDS 軟件如何安裝 IP、使用 IP 以及查看 IP 手冊實驗環境&#xff1a;Window11 PD…

thinkphp微信小程序一鍵獲取手機號登陸(解密數據)

微信小程序獲取手機號登錄的步驟相對較為簡單,主要分為幾個部分: 1.用戶授權獲取手機號: 微信小程序通過調用 wx.getPhoneNumber API 獲取用戶授權后,獲取手機號。 2.前端獲取用戶的手機號: 用戶在小程序中點擊獲取手機號時,系統會彈出授權框,用戶同意后,你可以通過 …

數據庫設計精要:完整性和范式理論

文章目錄數據的完整性實體的完整性主鍵域完整性參照完整性外鍵多表設計/多表理論一對一和一對多多對多數據庫的設計范式第一范式&#xff1a;原子性第二范式&#xff1a;唯一性第三范式&#xff1a;不冗余性數據的完整性 實體的完整性 加主鍵&#xff0c;保證一個表中每一條數…

智能推薦社交分享小程序(websocket即時通訊、協同過濾算法、時間衰減因子模型、熱度得分算法)

&#x1f388;系統亮點&#xff1a;websocket即時通訊、協同過濾算法、時間衰減因子模型、熱度得分算法&#xff1b;一.系統開發工具與環境搭建1.系統設計開發工具后端使用Java編程語言的Spring boot框架項目架構&#xff1a;B/S架構運行環境&#xff1a;win10/win11、jdk17小程…

部署NextCloud AIO + Frp + nginx-proxy-manager內網穿透私有云服務

網絡拓撲 假設已有域名為nextcloud.yourhost.com 用戶通過域名https訪問 -> Nginx -> frps -> frpc -> NextCloud 其中Nginx和frps安裝在具有公網IP的服務器上&#xff0c;frpc和NextCloud安裝在內網服務器中。 Nginx配置 通過docker安裝nginx-proxy-manager 外…

【源力覺醒 創作者計劃】文心開源大模型ERNIE-4.5-0.3B-Paddle私有化部署保姆級教程及技術架構探索

一起來輕松玩轉文心大模型吧&#x1f449;一文心大模型免費下載地址: https://ai.gitcode.com/theme/1939325484087291906 前言 2025年6月30日&#xff0c;百度正式開源文心大模型4.5系列&#xff08;ERNIE 4.5&#xff09;&#xff0c;涵蓋10款不同參數規模的模型&#xff0…

大模型面試:如何解決幻覺問題

在大模型面試中回答“如何解決幻覺”問題時&#xff0c;需要展現你對問題本質的理解、技術方案的掌握以及工程實踐的洞察。以下是一個結構化的回答框架和關鍵點&#xff0c;供你參考&#xff1a;回答框架&#xff1a;問題理解 -> 解決方案 -> 總結 1. 明確問題&#xff0…

matlab實現五自由度機械臂阻抗控制下的力跟蹤

五自由度機械臂阻抗控制下的力跟蹤,可以實現對力的跟蹤反饋&#xff0c;基于MATLAB的機器人工具箱 eyebot.m , 767 zuakang_wailiraodong.m , 2568 colormp.mat , 682

excel日志表介紹

在Excel中制作“日志表事物”&#xff08;可理解為記錄事務的日志表格&#xff09;&#xff0c;通常用于系統性追蹤事件、任務、操作或數據變化。以下從表格設計、核心要素、制作步驟、函數應用及場景案例等方面詳細說明&#xff0c;幫助你高效創建和使用事務日志表。 一、日志…

汽車信息安全 -- SHE密鑰更新小細節

之前我們把SHE密鑰更新流程做了梳理&#xff0c;汽車信息安全 -- SHE 密鑰更新流程 但在實際做SHE Emulation的時候還是發現了問題&#xff0c;例如如果想更新SHE Key ID等于30&#xff0c;會如何影響M1-M5的值呢&#xff1f;。 今天就聊聊關于幾家對于SHE Key的管理。 1. N…

Spring Boot配置優先級完全指南:實戰解析覆蓋規則

一、結論Spring Boot 中&#xff0c;位置越靠后優先級越高&#xff0c;外部配置壓倒內部配置&#xff0c;命令行參數擁有最高優先權。案例&#xff1a; 在一次生產事故中&#xff0c;某團隊通過 application-prod.properties 將服務端口設為 9000&#xff0c;但某運維人員在啟動…

嵌入式數據庫sqlite測試程序

繼上篇對嵌入式數據庫sqlite的移植和注意項&#xff0c;以及使用命令行測試之后&#xff0c;本篇對其進行了更進一步的程序測試&#xff0c;以備近期在項目中使用。測試程序及說明如下&#xff1a;/**************** 相關函數說明 ******************/ /* (1)sqlite3_open的函…

【學習篇】SQL復雜查詢學習

要求&#xff1a;能對千萬行級別的大表優化讀寫效率。 難點&#xff1a;如何創建千萬行級別的大表 MySQL數據庫的高效查詢不僅依賴于合理的表結構和索引設計&#xff0c;還需要掌握高級查詢技巧和性能優化方法。 數據表與數據表之間關系三種&#xff1a;實體之間關系 多對多…

Sequential Predictive Modeling of Clinical Trial Outcome with Meta-Learning解讀

SPOT(Sequential Predictive Modeling of Clinical Trial Outcome with Meta-Learning)模型是用于臨床試驗結果預測的模型, 借鑒了模型無關元學習(MAML,Model-Agnostic Meta-Learning)的框架,將模型參數分為全局共享參數和任務特定參數,以平衡跨任務泛化與任務內適配:…