news 2026/6/1 23:24:58

Dapr分布式运行时实战:用Sidecar模式构建云原生微服务

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Dapr分布式运行时实战:用Sidecar模式构建云原生微服务

Dapr 分布式运行时实战:用 Sidecar 模式构建云原生微服务

作者:Crown_22 | 云原生 & 分布式系统开发者 | 技术分享


前言

微服务架构下,每个服务都要处理服务发现、消息队列、状态管理、分布式锁、可观测性等横切关注点。这些逻辑跟业务无关,却占了大量代码量。

Dapr(Distributed Application Runtime)的核心理念:把分布式系统的通用能力抽离为 Sidecar 进程,通过 HTTP/gRPC API 调用,让业务代码零侵入地获得这些能力

本文将从零构建一个基于 Dapr 的微服务系统,涵盖状态管理、发布订阅、服务间调用、Actor 模式和可观测性。


一、Dapr 架构原理

1.1 Sidecar 模式

┌─────────────────────┐ ┌─────────────────────┐ │ 应用进程 │ │ Dapr Sidecar │ │ │ │ │ │ ┌───────────────┐ │ HTTP │ ┌────────────────┐ │ │ │ 业务代码 │◄─┼──────┼─►│ State Store │ │ │ │ (无SDK依赖) │ │ :3500│ │ Pub/Sub │ │ │ └───────────────┘ │ │ │ Service Invoke │ │ │ │ │ │ Bindings │ │ └─────────────────────┘ │ └───────┬────────┘ │ │ │ │ └──────────┼───────────┘ │ ┌───────────────┼───────────────┐ ▼ ▼ ▼ ┌─────────┐ ┌──────────┐ ┌──────────┐ │ Redis │ │ RabbitMQ │ │ CosmosDB │ └─────────┘ └──────────┘ └──────────┘

1.2 核心构建块

构建块功能API
Service-to-Service服务间调用 + 服务发现GET/POST /v1.0/invoke/{service}/{method}
State Management状态存储(KV)GET/PUT/DELETE /v1.0/state/{store}
Pub/Sub发布订阅消息POST /v1.0/publish/{topic}
Bindings外部系统绑定POST /v1.0/bindings/{name}
Actors虚拟 Actor 模式PUT/POST /v1.0/actors/{type}/{id}
Observability可观测性自动注入 trace/metrics
Secrets密钥管理GET /v1.0/secrets/{store}/{key}

二、环境搭建

2.1 安装 Dapr CLI

# 安装 Dapr CLIwget-qhttps://raw.githubusercontent.com/dapr/cli/master/install/install.sh-O-|/bin/bash# 初始化 Dapr(开发模式,自动配置 Redis)dapr init# 验证安装dapr--version# Output: CLI version: 1.14.0 Runtime version: 1.14.0# 检查组件dapr components

2.2 组件配置

# ~/.dapr/components/statestore.yamlapiVersion:dapr.io/v1alpha1kind:Componentmetadata:name:statestorespec:type:state.redisversion:v1metadata:-name:redisHostvalue:localhost:6379-name:redisPasswordvalue:""
# ~/.dapr/components/pubsub.yamlapiVersion:dapr.io/v1alpha1kind:Componentmetadata:name:pubsubspec:type:pubsub.redisversion:v1metadata:-name:redisHostvalue:localhost:6379-name:redisPasswordvalue:""

三、服务间调用实战

3.1 订单服务

# order_service.pyimportjsonimportuuidfromdatetimeimportdatetimefromflaskimportFlask,request,jsonify app=Flask(__name__)# Dapr 配置DAPR_HTTP_PORT=3500STATE_STORE="statestore"CATALOG_APP_ID="catalog-service"defdapr_invoke(app_id:str,method:str,data:dict=None)->dict:"""通过 Dapr 调用其他服务"""importrequests url=f"http://localhost:{DAPR_HTTP_PORT}/v1.0/invoke/{app_id}/method/{method}"ifdata:resp=requests.post(url,json=data)else:resp=requests.get(url)returnresp.json()ifresp.status_code==200elseNonedefdapr_save_state(key:str,value:dict):"""保存状态到 Dapr State Store"""importrequests url=f"http://localhost:{DAPR_HTTP_PORT}/v1.0/state/{STATE_STORE}"data=[{"key":key,"value":value}]requests.post(url,json=data)defdapr_get_state(key:str)->dict:"""从 Dapr State Store 获取状态"""importrequests url=f"http://localhost:{DAPR_HTTP_PORT}/v1.0/state/{STATE_STORE}/{key}"resp=requests.get(url)returnresp.json()ifresp.status_code==200elseNone@app.route("/orders",methods=["POST"])defcreate_order():"""创建订单"""data=request.json order_id=str(uuid.uuid4())# 1. 通过 Dapr 调用商品服务获取商品信息items_with_info=[]foritemindata["items"]:product=dapr_invoke(CATALOG_APP_ID,f"products/{item['product_id']}")ifnotproduct:returnjsonify({"error":f"商品{item['product_id']}不存在"}),400# 检查库存ifproduct["stock"]<item["quantity"]:returnjsonify({"error":f"商品{product['name']}库存不足"}),400items_with_info.append({"product_id":item["product_id"],"product_name":product["name"],"unit_price":product["price"],"quantity":item["quantity"]})# 2. 计算总金额total=sum(i["unit_price"]*i["quantity"]foriinitems_with_info)# 3. 创建订单对象order={"id":order_id,"customer_id":data["customer_id"],"items":items_with_info,
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/1 23:22:43

帧率×比特率×GOP结构×CRF×预设档位,Sora 2五大核心编码参数协同逻辑深度拆解,错过即降质37%

更多请点击&#xff1a; https://intelliparadigm.com 第一章&#xff1a;Sora 2编码参数协同逻辑的底层范式演进 Sora 2并非单纯对前代模型的参数扩容&#xff0c;而是重构了时空表征与控制信号之间的耦合机制。其核心突破在于将传统分离的“运动建模”“结构约束”与“语义对…

作者头像 李华
网站建设 2026/6/1 23:15:04

从零搭建Arduino智能家居模型:光感照明与振动安防实战

1. 项目概述&#xff1a;从零搭建一个会“思考”的迷你智能之家几年前&#xff0c;当我第一次把一堆传感器、LED灯和一块小小的Arduino板连接起来&#xff0c;并让它们根据我的指令协同工作时&#xff0c;那种感觉就像赋予了无生命的物体以简单的“智能”。如今&#xff0c;智能…

作者头像 李华
网站建设 2026/6/1 23:12:56

AI领域个人品牌构建:从播客到文字的内容矩阵策略

1. 项目概述&#xff1a;从播客主理人到内容创作者的深度剖析“Meet the Writer: Hacker Noon‘s Contributor Craig S. Smith, Host of the Eye on AI Podcast”这个标题&#xff0c;初看像是一篇人物专访的引子&#xff0c;但它背后蕴含的&#xff0c;其实是一个关于个人品牌…

作者头像 李华
网站建设 2026/6/1 23:12:22

实战指南:5步深度部署changedetection.io网站变更监控系统

实战指南&#xff1a;5步深度部署changedetection.io网站变更监控系统 【免费下载链接】changedetection.io Best and simplest tool for website change detection, web page monitoring, and website change alerts. Perfect for tracking content changes, price drops, res…

作者头像 李华
网站建设 2026/6/1 23:10:48

深入Cornerstone渲染管线:揭秘医学影像从像素数据到屏幕显示的完整旅程

深入Cornerstone渲染管线&#xff1a;揭秘医学影像从像素数据到屏幕显示的完整旅程医学影像的数字化呈现是现代医疗诊断的核心环节之一。在Web环境下实现高效、精准的医学影像渲染&#xff0c;需要一套复杂的处理流程将原始的DICOM像素数据转化为屏幕上可交互的图像。Cornersto…

作者头像 李华
网站建设 2026/6/1 23:09:29

从导电网格到交互艺术:基于Makey Makey的巨型坐标画布制作与编程实践

1. 项目概述&#xff1a;当你的身体成为画笔作为一名在创客教育领域摸爬滚打了十多年的老师&#xff0c;我一直在寻找那些能让学生“哇”出来的项目。它不能太简单&#xff0c;否则缺乏挑战&#xff1b;也不能太复杂&#xff0c;否则会吓退初学者。而今天要分享的这个“巨型坐标…

作者头像 李华