【C#】在.NET Aspire 中使用 Dapr 配置(Configuration)

【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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值