【C#】在.NET Aspire 中使用 Dapr 配置(Configuration)
一、AppHost项目
configstore.yaml
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: configstore
spec:
type: configuration.redis
version: v1
metadata:
- name: redisHost
value: localhost:6379
- name: redisPassword
value: ""
在AppHost项目添加组件:
// 添加配置组件
var configStore = builder.AddDaprComponent("configstore", "configuration.redis",
new DaprComponentOptions
{
LocalPath = "Resources\\configstore.yaml"
});
在其他项目中添加引用:
builder.AddProject<Projects.Aspire_WPF>("wpfclient")
// ...
.WithReference(configStore) // 添加引用
// ...
二、使用方法
private const string storeName = "statestore";
private const string DAPR_CONFIGURATION_STORE = "configstore";
private static List<string> CONFIGURATION_ITEMS = new List<string> { "key1", "key2" };
1、读取配置
GetConfigurationResponse config = await _client.GetConfiguration(DAPR_CONFIGURATION_STORE, CONFIGURATION_ITEMS);
foreach (var item in config.Items)
{
var cfg = System.Text.Json.JsonSerializer.Serialize(item.Value);
Console.WriteLine("Configuration for " + item.Key + ": " + cfg);
}
2、订阅更新
SubscribeConfigurationResponse subscribe = await _client.SubscribeConfiguration(DAPR_CONFIGURATION_STORE, CONFIGURATION_ITEMS);
await foreach (var items in subscribe.Source) // 这里阻塞:第一次调用、配置更新时通过,取消订阅后结束
{
// 首次调用时只返回订阅Id
if (items.Keys.Count == 0)
{
Console.WriteLine("App subscribed to config changes with subscription id: " + subscribe.Id);
subscriptionId = subscribe.Id; // 暂存Id用于取消订阅时使用
continue;
}
// 配置更新
var cfg = System.Text.Json.JsonSerializer.Serialize(items);
Console.WriteLine("Configuration update " + cfg);
}
3、取消订阅
try
{
await _client.UnsubscribeConfiguration(DAPR_CONFIGURATION_STORE, subscriptionId);
Console.WriteLine("App unsubscribed from config changes");
}
catch (Exception ex)
{
Console.WriteLine("Error unsubscribing from config updates: " + ex.Message);
}
4、设置/修改配置
> redis-cli -a 密码 MSET key1 "value1" key2 "value2"