微服務實踐k8s&dapr開發部署實驗(1)服務呼叫

shiningrise發表於2024-05-22

前置條件

  • 安裝docker與dapr: 手把手教你學Dapr - 3. 使用Dapr執行第一個.Net程式
  • 安裝k8s
    image

dapr 自託管模式執行

新建一個webapi無許可權專案

image
launchSettings.json中applicationUrl埠改成5001,如下:

"applicationUrl": "http://localhost:5001"   
//WeatherForecastController.cs更改如下
using Microsoft.AspNetCore.Mvc;

namespace backend.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost(Name = "Hello")]
        public object SayHello()
        {
            return new { message = "Hello" }; //這裡返回必須是json物件,如果為字串,則在daprClient.InvokeMethodAsync呼叫時會出錯
        }
    }
}

到backend目錄執行執行下面命令:

dapr run --app-id backend --app-port 5001 dotnet run

然後執行:

dapr invoke --app-id backend --method WeatherForecast  
dapr invoke --app-id backend --method WeatherForecast --verb GET

顯示下圖表示執行成功
image

dapr服務呼叫

新建一個名為front的weiapi無許可權專案
launchSettings.json中applicationUrl埠改成5002,如下:

"applicationUrl": "http://localhost:5002"   

新增nuget包:Dapr.Client
修改WeatherForecastController.cs如下:

using Dapr.Client;
using Microsoft.AspNetCore.Mvc;

namespace front.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {

        [HttpPost(Name = "Hello")]
        public async Task<string> HelloAsync()
        {
            var appId = "backend";
            var methodName = "WeatherForecast";

            using (var daprClient = new DaprClientBuilder().Build())
            {
                try
                {
                    var result = await daprClient.InvokeMethodAsync<object>(HttpMethod.Post, appId, methodName);
                    Console.WriteLine(result);
                    return result.ToString();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An exception occurred while invoking method: '{methodName}' on app-id: '{appId}'");
                    Console.WriteLine(ex.ToString());
                }
            }
            return "Error!";
        }
    }
}

訪問http://http://localhost:5002/swagger/頁面執行如下就成功了
image

k8s&dapr模式執行

Dapr uninstall --all
dapr init -k

新增docker支援
image

新增backend的k8s配置檔案dapr-backend.yaml

kind: Deployment
apiVersion: apps/v1
metadata:
  name: dapr-deploy-backend
  labels:
    service: backend
spec:
  replicas: 2
  selector:
    matchLabels:
       service: backend
  template:
    metadata:
      labels:
        service: backend
      annotations:
        dapr.io/enabled: "true"
        dapr.io/app-id: "backend" #這裡要注意app-id要與front呼叫的名稱要一致
        dapr.io/app-port: "8080"
        #dapr.io/config: "dapr-config"
    spec:
      containers:
        - name: daprbackend
          image: daprbackend
          imagePullPolicy: Never
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: daprbackend
  labels:
    service: backend
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30003
      protocol: TCP
      name: http
    - port: 50001
      targetPort: 50001
      nodePort: 30042
      protocol: TCP
      name: dapr-grpc
  selector:
    service: backend

新增backend的k8s配置檔案dapr-backend.yaml

kind: Deployment
apiVersion: apps/v1
metadata:
  name: dapr-deploy-front
  labels:
    service: front
spec:
  replicas: 1
  selector:
    matchLabels:
       service: front
  template:
    metadata:
      labels:
        service: front
      annotations:
        dapr.io/enabled: "true"
        dapr.io/app-id: "front"
        dapr.io/app-port: "8080"
        #dapr.io/config: "dapr-config"
    spec:
      containers:
        - name: daprfrontend
          image:  daprfrontend
          imagePullPolicy: Never
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: daprfrontend
  labels:
    service: front
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30002
      protocol: TCP
      name: http
    - port: 50001
      targetPort: 50001
      nodePort: 30041
      protocol: TCP
      name: dapr-grpc
  selector:
    service: front

啟動批處理檔案start-all.bat

docker build -t daprbackend -f backend/Dockerfile .
docker build -t daprfrontend -f front/Dockerfile .

Dapr uninstall --all
dapr init -k
kubectl apply -f k8s/dapr-backend.yaml
kubectl apply -f k8s/dapr-front.yaml

pause

停止批處理檔案stop-all.bat

kubectl delete -f ./k8s/dapr-front.yaml 
kubectl delete -f ./k8s/dapr-backend.yaml 
	
Dapr uninstall --all

pause

執行成功驗證

image
image
訪問http://localhost:30002/swagger/index.html
顯示如下說明已經成功
image

專案原始碼下載

專案原始碼下載

常用命令

dapr uninstall
Dapr uninstall --all
dapr init
dapr init -k
dapr run --app-id myapp --dapr-http-port 3500 --dapr-grpc-port 50001 -- dotnet run   #執行.net專案
dapr run --app-id backend --app-port 5001 dotnet run
dapr invoke --app-id backend --method WeatherForecast  #呼叫介面
dapr invoke --app-id backend --method WeatherForecast --verb GET

相關文章

  • 手把手教你學Dapr - 3. 使用Dapr執行第一個.Net程式
  • .Net 7 輕鬆上手Dapr之服務呼叫

相關文章