编写于:2022年7月21日 , cc
安装的插件:
docker-windows
Dapr
tye
vault
Dapr安装前提,需要安装docker-windows版本
安装 Dapr cli
. 创建dapr命令,拉取dapr
Dapr CLI 是您用于各种 Dapr 相关任务的主要工具。 您可以使用它来运行一个带有Dapr sidecar的应用程序, 以及查看sidecar日志、列出运行中的服务、运行 Dapr 仪表板。
x1#安装命令2wget -q https://raw.githubusercontent.com/dapr/cli/master/install/install.sh -O - | /bin/bash3
4#校验安装是否成功5
6dapr7 __8 ____/ /___ _____ _____9 / __ / __ '/ __ \/ ___/10 / /_/ / /_/ / /_/ / /11 \__,_/\__,_/ .___/_/12 /_/13===============================14Distributed Application Runtime15
输出显示应该如下方所示:
Dapr 与您的应用程序一起作为sidecar运行,在自托管模式下,这意味着它是您本地机器上的一个进程。 因此,初始化 Dapr 包括获取 Dapr sidecar 二进制文件并将其安装到本地.
此外,默认初始化过程还创建了一个开发环境,帮助简化 Dapr 的应用开发。 这包括下列步骤:
确保以管理员方式运行命令提示符终端 (右键单击,以管理员方式运行)
安装最新的 Dapr 运行时二进制程序:
xxxxxxxxxx11dapr init验证
xxxxxxxxxx41dapr --version2
3 CLI version: 1.2.04 Runtime version: 1.4.0
验证容器正在运行
请确保镜像为daprio/dapr, openzipkin/zipkin和 redis 的容器都在运行:
xxxxxxxxxx51docker ps2
348ba145c26b8 openzipkin/zipkin:latest 9411/tcp, 0.0.0.0:9411->9410/tcp dapr_zipkin47c6cb13fa040 daprio/dapr:1.7.4 0.0.0.0:6050->50005/tcp dapr_placement5a0195e3a0fc8 redis 0.0.0.0:6379->6379/tcp dapr_redisWindows 中,Dapr 初始化路径到 %USERPROFILE%.dapr\
Tye插件主要为和dapr连用,在开发中调试使用
安装命令:
xxxxxxxxxx11dotnet tool install --global Microsoft.Tye --version 0.11.0-alpha.22111.1VS调试插件:
https://marketplace.visualstudio.com/items?itemName=ikkentim.TimsTyeExplorer22
Tye入门教程:
https://github.com/dotnet/tye/blob/main/docs/getting_started.md
Tye与dapr结合入门文档:
重点,请仔细阅读此篇文档方便开发时使用和调试
https://github.com/dotnet/tye/blob/main/docs/recipes/dapr.md
在项目中会有三个dapr配置文件
pubsub.yaml # 发布订阅配置文件
statestore.yaml # 状态管理配置文件
secretstores.hashicorp.vault.yaml # 秘钥管理配置文件
暂未使用
xxxxxxxxxx151nameResolution2component"consul"3configuration4 client5 address"192.165.10.102:8500" #consul地址6 selfRegistertrue7 checks8name"Dapr Health Status"9 checkID"daprHealth:${APP_ID}"10 interval"15s"11 http"http://${HOST_ADDRESS}:${DAPR_HTTP_PORT}/v1.0/healthz" #dapr的健康检查地址12name"Service Health Status"13 checkID"serviceHealth:${APP_ID}"14 interval"15s"15 http"http://${HOST_ADDRESS}:${APP_PORT}/api/health/GetHeartbeat" #dapr依赖服务的健康检查地址
在服务调用中,封装了DaprClient的调用方法,使用封装的扩展方法即可调用
xxxxxxxxxx101 //在接收消息的StartUp中注册消息接收的中间件2 services.AddControllers().AddDapr();3
4 //在构造函数中注入 DaprClient 方法5
6var data = _daprClient.DaprInvokeMethodExtAsync<RetDataResult<bool>>7 (HttpMethod.Get8 , DefaultValues.PersonalizationServer 9 , $"api/PageAssembly/CompanyId?companyId={SessionData.CompanyCode}"10 , HttpContext).Result;x
1 /// <summary>2 /// 发送消息3 /// </summary>4 /// <returns></returns>5 [HttpGet]6 public async Task<ActionResult> PubAsync()7 { 8 await _daprClient.PublishEventAsync("pubsub", "test_topic", "推送的消息!");9 return Ok();10 }11 12
13 //在接收消息的StartUp中注册消息接收的中间件14
15 app.UseCloudEvents(); //<--------重点16 17 app.UseEndpoints(endpoints =>18 {19 endpoints.MapControllers();20
21 endpoints.MapSubscribeHandler(); //<--------重点22 });23
24
25 /// <summary>26 /// 接收消息27 /// </summary>28 /// <param name="obj"></param>29 /// <returns></returns>30 [Topic("pubsub", "test_topic")]31 [HttpPost("/sub")]32 public IActionResult SubAsync(string obj)33 {34
35 Console.WriteLine($"weather changed:{obj}");36
37 return Ok();38 }xxxxxxxxxx141# 增加绑定的配置文件,绑定定时任务2
3apiVersiondapr.io/v1alpha14kindComponent5metadata6 namecron7 namespacedefault8spec9 typebindings.cron10 versionv111 metadata12nameschedule13 value"@every 15m" # every 5 seconds14
xxxxxxxxxx71//增加绑定配置文件,即可绑定,定时任务2 [HttpPost("/cron")]3 public IActionResult Index()4 {5 Console.WriteLine($"hello from the cron input binding................{DateTime.Now.ToString("yyyyMMdd H:m:s")}");6 return Ok();7 }
此次采用的秘钥管理组件是 hashicorp-vault
在代码中可以引用:Dapr.Extensions.Configuration 组件,读取vault中的配置,在代码中使用
xxxxxxxxxx341# 增加秘钥管理的配置文件2
3apiVersiondapr.io/v1alpha14kindComponent5metadata6 namevault-secret-store7spec8 typesecretstores.hashicorp.vault9 versionv110 metadata11namevaultAddr12 valuehttp//127.0.0.1820013 #- name: caCert # Optional. This or caPath or caPem14 # value: "[ca_cert]"15 #- name: caPath # Optional. This or CaCert or caPem16 # value: "[path_to_ca_cert_file]"17 #- name: caPem # Optional. This or CaCert or CaPath18 # value : "[encoded_ca_cert_pem]"19nameskipVerify # Optional. Default: false20 value true21 #- name: tlsServerName # Optional.22 # value : "[tls_config_server_name]"23 #- name: vaultTokenMountPath # Required if vaultToken not provided. Path to token file. ~/.vault-token24 # value : ""25namevaultToken # Required if vaultTokenMountPath not provided. Token value.26 value "hvs.n9lOGM7LQXo8JtBogY64RXjA"27 #- name: vaultKVPrefix # Optional. Default: "dapr"28 # value : "dapr"29namevaultKVUsePrefix # Optional. default: "true"30 valuefalse31nameenginePath # Optional. default: "secret"32 value"secret"33namevaultValueType # Optional. default: "map"34 value"map"在代码中的配置与使用
xxxxxxxxxx311//Program.cs 文件中的配置2//DefaultValues.IdentityServer 为设置的公共常量3//new DaprSecretDescriptor 为读取的配置项4.ConfigureAppConfiguration(config =>5{6 #region 设置读取vault配置7
8 var daprClient = new DaprClientBuilder().Build();9 var secretDescriptors = new List<DaprSecretDescriptor>10 {11 new DaprSecretDescriptor(DefaultValues.IdentityServer),12 new DaprSecretDescriptor(DefaultValues.Vault_Secret_ServerAppsettings),13 new DaprSecretDescriptor(DefaultValues.Vault_Secret_CacheRedisConfig),14 new DaprSecretDescriptor(DefaultValues.Vault_Secret_LoggerApi)15 };16 config.AddDaprSecretStore(DefaultValues.Vault_ComponentName, secretDescriptors,17 daprClient);18
19 #endregion20})21 22//Startup.cs 文件中读取配置23 Configuration[“ConnectionStrings”] //此方法直接读取连接字符串24 25//此方法为读取的配置项映射到实体26 services.Configure<Appsettings>(this.Configuration);27//在Controller中使用方式:根据映射的实体构造函数注入使用28 IOptions<Appsettings> 29//在Controller中使用方式:IConfiguration构造函数注入使用 30 IConfiguration _configuration;31 _configuration[“ConnectionStrings”]
创建 tye.yaml,配置dapr,配置项目启动项和端口
x
1
2namemicronet3extensions4namedapr5 log-leveldebug6 components-path"dapr/components"7services8nameconfigserver9 projectConfigServer/Config.csproj10 bindings11port500112namecommonserver13 projectCommonServer/Common.csproj14 bindings15port500216namemongoserver17 projectMongoServer/Mongo.csproj18 bindings19port5003
在项目根目录下cmd,输入以下命令:
x
1tye run2
3Launching Tye Host...4
5[20:00:13 INF] Executing application from E:\ProjectCode\Micronet\tye.yaml6[20:00:13 INF] Dashboard running on http://127.0.0.1:80007[20:00:13 INF] Build Watcher: Watching for builds...8[20:00:13 INF] Building projects浏览器访问 http://127.0.0.1:8000
即可查看运行的服务和运行日志
打开 vs的 tye调试插件:Tye Explorer
选中要调试的项目 Attach to selected ,可多选联调
项目发布Release版本
docker常用命令
docker创建镜像
xxxxxxxxxx41# ids4 镜像名称2# v1 镜像版本3# 最后还有个 "."4docker build -t ids4:v1 .docker导出镜像
xxxxxxxxxx41# ids4 镜像名称2# v1 镜像版本3# ids4.tar.gz 镜像导出的压缩包4docker save ids4:v1 -o ids4.tar.gzdocker导入压缩包
xxxxxxxxxx31# 将镜像拖入指定文件夹2# ids4.tar.gz 镜像导出的压缩包3docker load -i ids4.tar.gzdocker上传镜像到镜像仓库
xxxxxxxxxx81#将镜像标记到镜像仓库2# ids4 镜像名称3# v1 镜像版本4#192.168.59.128:5000/ids4:v1 镜像仓库的地址5docker tag ids4:v1 192.168.59.128:5000/ids4:v16
7#将镜像推送到仓库8docker push在创建镜像前,先生成应用,应用生成在“ dist ”文件夹下。
创建的两个文件都在项目根目录下 以SPA项目为例,在.BS.SPA文件加下。
创建nginx配置文件 文件名称命名为:default.conf
xxxxxxxxxx151server {2 listen 80;3 server_name localhost; # 修改为docker服务宿主机的ip4
5 location / {6 root /usr/share/nginx/html;7 index index.html index.htm;8 try_files $uri $uri/ /index.html =404;9 }10
11 error_page 500 502 503 504 /50x.html;12 location = /50x.html {13 root html;14 }15}
创建dockerfile
xxxxxxxxxx91FROM nginx2
3MAINTAINER cc4
5RUN rm /etc/nginx/conf.d/default.conf6
7ADD default.conf /etc/nginx/conf.d/8
9COPY dist/ /usr/share/nginx/html/创建镜像
xxxxxxxxxx11docker build -t vueclient:v1 .
k8s中运行vue项目的yaml文件,与后端相同,去除dapr配置即可示例如下:
xxxxxxxxxx181 template2 metadata3 labels4 serviceids45 annotations#--- 从此处开始去除6 dapr.io/enabled"true" 7 dapr.io/app-id"ids4"8 dapr.io/app-port"5401"9 dapr.io/config"dapr-config" #--- 到此处结束10 spec11 containers12nameids413 image192.168.59.1285000/ids4v114 imagePullPolicyIfNotPresent15 ports16namehttp17 containerPort540118 protocolTCP
详情见HashCorpVault文档
暂未使用,仅作为参考学习使用
xxxxxxxxxx141231. docker-compose.yaml中的配置注释45+ . redis设置6- 拉取最新镜像创建redis容器7```yaml8redis:9image: "redis:latest"10ports:11- "6379:6379" #指定端口,对外映射端口12networks:13- ts_web #设置同一网络主要为服务之间联通14
. zipkin设置
xxxxxxxxxx61 zipkin2 image"openzipkin/zipkin:latest"3 ports4"9412:9411" #指定端口,对外映射端口5 networks6ts_web #设置同一网络主要为服务之间联通. dapr placement设置
xxxxxxxxxx71 placement2 image"daprio/dapr"3 command"./placement" "-port" "50006"4 ports5"50006:50006" #指定端口,对外映射端口6 networks7ts_web #设置同一网络主要为服务之间联通. 构建服务(Common服务)
x
1 common2 image$DOCKER_REGISTRY-common3 build4 context.5 dockerfileCommon/Dockerfile #依据本地路径下的dockerfile文件创建镜像6 ports7 8"30002:3500" #访问dapr Sidecar9"5002:5002" #访问swagger10 networks11ts_web #设置同一网络主要为服务之间联通. 构建服务(依据Common服务创建对应的dapr服务)
x
1 commonserver-api-dapr2 image"daprio/daprd:1.7.0" #dapr镜像3 command "./daprd"4 "-app-id" "Common" #app-id是必填的,与consul中的服务名称的功能是一致的5 "-app-port" "5002" #app-port是必填的,与服务的端口保持一致即可6 "-placement-host-address" "placement:50006" #placement端口地址7 "-config""/dapr/config.yaml" #dapr配置文件路径8 "-components-path" "/dapr/components" #dapr组件路径9 depends_on10commonserver #依赖的容器11consul412 volumes13"./dapr:/dapr" #指定的路径14 network_mode"service:common" #网络依赖. 网关服务构建
x
1 apigateway2 image$DOCKER_REGISTRY-apigateway3 build4 context.5 dockerfileApiGateWay/Dockerfile #依据本地路径下的dockerfile文件创建镜像6 ports7"7000:80" #网关映射端口8 networks9ts_web #设置同一网络主要为服务之间联通. docker容器创建的网络连接
xxxxxxxxxx31 networks2 ts_web3 externaltruedocker-compose 命令
xxxxxxxxxx51#启动docker-compose2 docker-compose up -d3
4#停止docker-compose5 docker-compose down