环境配置
单机本地环境
- 下载二进制版本
- 将压缩包中
dapr.exe
文件解压到c:\dapr
目录 - 将
c:\dapr
目录放入到系统PATH环境变量 - 启动powershell,运行dapr命令,检查输出是否正常
- 运行
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
- 检查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
- 本地Dapr集成了一个
Redis
,用于实现状态存储
注意: 你需要安装Docker for Windows
并且将容器设置为Linux容器。
服务发现与调用示例(独立模式)
前置条件
- 已配置好本地开发环境
- Docker For Windows
- 安装了
.NET Core 3.0
SDK
步骤(VS Code)
- 在代码目录创建一个
example
目录,用于保存解决方案 - VS Code中打开
example
目录,通过Ctrl+Shift+`新建一个终端 - 在终端中键入以下命令,创建解决方案
dotnet new sln
- 创建一个新项目,采webapi模板,名称为
dapr-example
dotnet new webapi -n dapr-example
- 将
invoke-service
项目加入到解决方案
dotnet sln example.sln add ./dapr-example/dapr-example.csproj
- 生成的项目中,默认包含一个天气控制器
- 取消HTTPS自动跳转设置,在
Startup.cs,Configure
方法中,注释掉app.UseHttpsRedirection();
- 演示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文档服务调用
-
测试,通过浏览器打开
http://localhost:5000/WeatherForecast
连接(此时我们没有通过Dapr代理访问) -
下面,可以通过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
相关的代码。