1. 回顾

上一章,我们动手在K8S集群中安装了Dapr:

Dapr+Net6+K8S最小原型项目架构和实现-10-在Master节点上给K8S集群安装Dapr_敦格-CSDN博客Dapr+Net6+K8S最小原型项目架构和实现-10-在Master节点上给K8S集群安装Daprhttps://blog.csdn.net/shuaihj/article/details/122969361

这一章,K8S集群和Dapr运行时都准备好了 ,我们开始使用AspNetCore6.0编写Dapr项目。

 2. 新建一个ASP.NET Core Web API项目 Service01

  • 新建HelloController
  • 定义一个API: api/hello
  • 每个Service01实例分配不同的InstanceId
  • API被访问时,返回InstanceId,来验证负载均衡效果
using Microsoft.AspNetCore.Mvc;

namespace Service01.Controllers
{
    [ApiController]
    public class HelloController : ControllerBase
    {
        // 每个Service01实例分配不同的InstanceId
        private static readonly string InstanceId = Guid.NewGuid().ToString();

        [HttpGet("api/Hello")]
        public async Task<IActionResult> Hello()
        {
            await Task.CompletedTask;

            // API被访问时,返回InstanceId,来验证负载均衡效果
            return Ok(new { Service = "Service01", InstanceId });
        }
    }
}

3. 新建一个ASP.NET Core Web API项目 Service02

3.1. 引用Dapr.AspNetCore包

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
	  <!--引用Dapr.AspNetCore包-->
	  <PackageReference Include="Dapr.AspNetCore" Version="1.6.0" />
  </ItemGroup>

</Project>

3.2. 注入Dapr service

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers()
    .AddDapr(); // 注入Dapr service

var app = builder.Build();

app.UseAuthorization();

app.MapControllers();

app.Run();

3.3. 新建HelloController

  • 通过dapr访问Service01的API
using Dapr.Client;
using Microsoft.AspNetCore.Mvc;

namespace Service02.Controllers
{
    [ApiController]
    public class HelloController : ControllerBase
    {
        private readonly DaprClient _daprClient;

        public HelloController(DaprClient daprClient)
        {
            _daprClient = daprClient;
        }

        [HttpGet("api/Hello")]
        public async Task<IActionResult> Hello()
        {
            // 通过dapr访问Service01的API
            var result = await _daprClient.InvokeMethodAsync<object>(HttpMethod.Get, "service01", "api/hello");
            
            return Ok(result);
        }
    }
}

4. 给Service01和Service02准备Dockerfile

4.1. 给Service01 添加Dockerfile

  • Dockerfile文件及内容会自动生成,无需更改

4.2. 给Service02 添加Dockerfile

  • Dockerfile文件及内容会自动生成,无需更改

5. 上传Service01和Service02的Docker镜像

5.1. 登录 docker hub

https://hub.docker.com/
docker login

5.2. 给service01和service02打镜像

docker build -t k8schina/service01:v1 -f ./Service01/Dockerfile .
docker build -t k8schina/service02:v1 -f ./Service02/Dockerfile .

5.3. 上传Service01和service02的镜像

docker push k8schina/service01:v1
docker push k8schina/service02:v1

5.4. 查看上传结果

6. 下一章

Dapr+Net6+K8S最小原型项目架构和实现-12-将Dapr项目部署到K8S集群_敦格-CSDN博客Dapr+Net6+K8S最小原型项目架构和实现-12-将Dapr项目部署到K8S集群https://blog.csdn.net/shuaihj/article/details/122971745?spm=1001.2014.3001.5501

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐