Blazor+Dapr+K8s微服務之狀態管理

小莊發表於2021-08-25

 

1         狀態管理伺服器端介面

1.1         新增Dapr.AspNetCore包

在DaprTest1.Server專案中新增Dapr.AspNetCore包,該包實現了ASP.NET Core與Dapr的整合,例如自動依賴注入DaprClient物件,將狀態管理功能直接整合到 ASP.NET Core 模型繫結功能中等。

 

修改DaprTest1.Server專案的Startup.cs檔案,將Dapr物件依賴注入到ASP.NET Core。

 public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllersWithViews().AddDapr();
            services.AddRazorPages();
            services.AddScoped<InvocationHandler>();

            // 注入httpClient
            services.AddHttpClient("HttpClient").AddHttpMessageHandler<InvocationHandler>()
            .AddTypedClient(client =>
            {
                client.BaseAddress = new Uri("http://serviceapi1");
                return RestService.For<ICallServiceApi1>(client);
            });
        }

在DaprTest1.Server專案的WeatherForecastController.cs檔案中注入DaprClient物件

  private readonly DaprClient _daprClient;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, ICallServiceApi1 callServiceApi1, DaprClient daprClient)
        {
            _logger = logger;
            _callServiceApi1 = callServiceApi1;
            _daprClient = daprClient;
        }

 

1.2         狀態儲存介面

在DaprTest1.Server專案的WeatherForecastController.cs檔案中增加狀態儲存介面。

  [HttpPost(nameof(SaveStateValue))]
        public async Task SaveStateValue(StateModel stateModel)
        {
            await _daprClient.SaveStateAsync("statestore", stateModel.Key, stateModel.Value);
        }

其中 StateModel  為自定義的狀態模型物件。

1.3         狀態刪除介面

在DaprTest1.Server專案的WeatherForecastController.cs檔案中增加狀態刪除介面。

 [HttpDelete(nameof(DeleteStateValue) + "/{stateKey}")]
        public async Task DeleteStateValue(string stateKey)
        {
            await _daprClient.DeleteStateAsync("statestore", stateKey);
        }

1.4         狀態獲取介面

在DaprTest1.Server專案的WeatherForecastController.cs檔案中增加兩個狀態獲取介面。

 [HttpGet("GetStateValue/{stateKey}")]
        public async Task<string> GetStateValue(string stateKey)
        {
            return await _daprClient.GetStateAsync<string>("statestore", stateKey);
        }

        [HttpGet(nameof(GetStateValueFromState) + "/{stateKey}")]
        public async Task<string> GetStateValueFromState([FromState("statestore", "stateKey")] StateEntry<string> stateEntry)
        {
            return await Task.FromResult(stateEntry.Value);
        }

注意,第二個狀態獲取介面是通過ASP.NET Core 模型繫結實現的。

 

2         狀態管理選單和頁面

在DaprTest1.Server專案的NavMenu.razor檔案新增狀態管理選單。

 <li class="nav-item px-3">
            <NavLink class="nav-link" href="statemanage">
                <span class="oi oi-list-rich" aria-hidden="true"></span> 狀態管理
            </NavLink>
        </li>

在DaprTest1.Server專案新增狀態管理頁面

@page "/statemanage"
@using DaprTest1.Shared
@using System.Text.Json
@inject HttpClient Http

<h1>狀態儲存</h1>

<p>This component demonstrates storing state.</p>

<p>狀態鍵: TestStateKey, 狀態值:<input type="text" @bind="stateModel.Value" /></p>

<button class="btn btn-primary" @onclick="SaveStateValue">儲存狀態</button>
<button class="btn btn-primary" @onclick="DeleteStateValue">刪除狀態</button>
<button class="btn btn-primary" @onclick="GetStateValue">獲取狀態</button>
<button class="btn btn-primary" @onclick="GetStateValueFromState">獲取狀態[FromState]</button>


<p>獲取到的狀態值: @stateValue</p>

@code {
    private StateModel stateModel = new StateModel() { Key = "TestStateKey" };
    private string stateValue = "";

    private async Task SaveStateValue()
    {
        await Http.PostAsJsonAsync<StateModel>("WeatherForecast/SaveStateValue", stateModel);
    }
    private async Task DeleteStateValue()
    {
        await Http.DeleteAsync("WeatherForecast/DeleteStateValue/" + stateModel.Key);
    }
      private async Task GetStateValue()
    {
        stateValue = await Http.GetStringAsync("WeatherForecast/GetStateValue/" + stateModel.Key);
    }
     private async Task GetStateValueFromState()
    {
        stateValue = await Http.GetStringAsync("WeatherForecast/GetStateValueFromState/" + stateModel.Key);
    }
}

3         狀態管理測試

和上一節一樣,我們先開啟每個微服務的SideCar,然後啟動兩個微服務,訪問狀態管理頁面:

 

我們可以檢視快取,看到狀態資料,其中快取Key是由儲存狀態的微服務ID+“||”+自定義的快取Key組成,快取內容Dapr自動增加了版本號。

 

相關程式碼:iamxiaozhuang/dapr-test (github.com)

相關文章