微服务实践k8s&dapr开发部署实验(1)服务调用

前置条件

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

相关文章

posted @ 2024-05-22 15:49  shiningrise  阅读(348)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css