当前位置:网站首页>Dapr .NET Core示例

Dapr .NET Core示例

2022-06-09 15:41:00 风神修罗使

环境配置

单机本地环境

  1. 下载二进制版本
  2. 将压缩包中dapr.exe文件解压到c:\dapr目录
  3. c:\dapr目录放入到系统PATH环境变量
  4. 启动powershell,运行dapr命令,检查输出是否正常
  5. 运行dapr init命令安装Dapr运行时(需以管理员方式启动终端)
PS C:\WINDOWS\system32> dapr init
Making the jump to hyperspace...
Downloading binaries and setting up components...
Success! Dapr is up and running
  1. 检查dapr是否运行正常,通过docker ps命令
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
032a6f9fd0b0        daprio/dapr         "./placement"            29 minutes ago      Up 29 minutes       0.0.0.0:6050->50005/tcp   dapr_placement
3c109a9886e2        redis               "docker-entrypoint.s…"   30 minutes ago      Up 30 minutes       0.0.0.0:6379->6379/tcp    xenodochial_kapitsa
  1. 本地Dapr集成了一个Redis,用于实现状态存储

注意: 你需要安装Docker for Windows并且将容器设置为Linux容器。


服务发现与调用示例(独立模式)

前置条件

  • 配置好本地开发环境
  • Docker For Windows
  • 安装了.NET Core 3.0 SDK

步骤(VS Code)

  1. 在代码目录创建一个example目录,用于保存解决方案
  2. VS Code中打开example目录,通过Ctrl+Shift+`新建一个终端
  3. 在终端中键入以下命令,创建解决方案
dotnet new sln
  1. 创建一个新项目,采webapi模板,名称为dapr-example
dotnet new webapi -n dapr-example
  1. invoke-service项目加入到解决方案
dotnet sln example.sln add ./dapr-example/dapr-example.csproj
  1. 生成的项目中,默认包含一个天气控制器
  2. 取消HTTPS自动跳转设置,在Startup.cs,Configure方法中,注释掉app.UseHttpsRedirection();
  3. 演示Dapr的服务调用,在终端中切换到项目目录,然后使用dapr启动应用
cd invoke-service
dapr run --app-id dapr-example --app-port 5000 dotnet run

注意: 以上dapr run命令,通过app-id指定了应用的ID,通过app-port指定了应用的端口(webapi默认使用5000作为http端口),后跟dotnet run命名启动当前项目。可参考Dapr文档服务调用

  1. 测试,通过浏览器打开http://localhost:5000/WeatherForecast连接(此时我们没有通过Dapr代理访问)

  2. 下面,可以通过Dapr公开的代理地址来访问我们的服务,根据Dapr服务调用API规范,其代理调用规则为:

POST/GET/PUT/DELETE http://localhost:<Dapr端口>/v1.0/invoke/<id>/method/<method-name>

Dapr端口可从Dapr启动日志中获取,如以下日志表示Dapr公开的HTTP端口为14633(通过Dapr也可使用gRPC方式进行服务调用)

 ?[0m?[93;1m== DAPR == time="2019-10-29T11:18:34+08:00" level=info msg="http server is running on port 14633"
?[0m?[93;1m== DAPR == time="2019-10-29T11:18:34+08:00" level=info msg="gRPC server is running on port 14634"

故,我们可通过以下地址来调用示例方法:

 GET http://localhost:14633/v1.0/invoke/dapr-example/method/WeatherForecast

注意: Dapr的服务调用是有dapr sidecar来实现的,在被调用的服务中无需注入任何与dapr相关的代码。

原网站

版权声明
本文为[风神修罗使]所创,转载请带上原文链接,感谢
https://blog.csdn.net/wulex/article/details/124990926