我在尝试在 Dapr 状态存储中保存键值时遇到以下异常。我对 Dapr 概念很陌生。
Dapr.DaprException:状态操作失败:Dapr 端点指示失败。有关详细信息,请参阅内部异常。 ---> Grpc.Core.RpcException: Status(StatusCode="FailedPrecondition", Detail="状态存储未配置")
我使用了下面的yaml文件和c#代码。
文件名:config.yaml
apiVersion: dapr.io/v1alpha1
kind: Configuration
metadata:
name: daprd-config
spec:
stateStore:
- name: statestore
stateStoreType: inMemory
程序.cs文件
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Dapr.Extensions.Configuration;
namespace DaprPoc
{
public class Program
{
public static void Main(string[] args)
{
//// Set the DAPR_CONFIG environment variable to the path of your config file
//System.Environment.SetEnvironmentVariable("DAPR_CONFIG", "/path/to/config.yaml");
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(x=>x.AddPolicy("EnableCors",
y=>y.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
builder.Services.AddControllers().AddDapr();
//builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
// {
// config.AddDaprConfig(builder =>
// {
// builder.AddYamlFile("mydapr.yaml");
// });
// });
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCloudEvents();
app.UseRouting();
app.UseCors();
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapSubscribeHandler(); // add this line if you want to enable pub/sub
endpoints.MapControllers();
});
app.Run();
}
}
}
控制器
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Dapr.Client;
using Microsoft.AspNetCore.Cors;
namespace DaprPoc.Controllers
{
[Route("api/[controller]")]
[ApiController]
[EnableCors("EnableCors")]
public class StateManagementController : ControllerBase
{
private readonly DaprClient _daprClient;
public StateManagementController(DaprClient daprClient)
{
_daprClient = daprClient;
}
[HttpGet("{key}")]
public async Task<ActionResult<string>> Get(string key)
{
var value = await _daprClient.GetStateAsync<string>("statestore", key);
return Ok(value);
}
[HttpGet("{key}/{value}")]
public async Task<ActionResult> Post(string key,string value)
{
await _daprClient.SaveStateAsync("statestore", key, value);
return Ok(value);
}
}
}
看起来组件文件(config.yaml)不正确。
这是docs中提到的格式:
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: <NAME>
spec:
type: state.in-memory
version: v1
metadata: []
您需要将
<NAME>
替换为您为此组件指定的名称。假设您将使用 inmemory-store
。然后,每当您使用状态管理 API 时,您都需要在 C# 代码中引用此组件名称:
var value = await _daprClient.GetStateAsync<string>("inmemory-store", key);
return Ok(value);
如果您需要更多帮助,请查看状态管理快速入门。您还可以加入 Dapr Discord 来提出更多问题。