服务发现与健康检查
学习微服务如何动态发现彼此,以及健康检查如何确保流量只发送到健康的实例。
服务发现与健康检查 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Discovery Problem
In a microservices system, instances start, stop, and move across hosts constantly. Hardcoding IP addresses breaks immediately.
Service discovery lets a service find healthy instances of another service by name at runtime.
Client-Side vs Server-Side
Two patterns exist:
- Client-side: the caller queries a registry and picks an instance
- Server-side: a load balancer or gateway resolves the name and forwards the request
Service Registries
A registry stores live instances. Popular options include Consul, etcd, and Kubernetes DNS.
Services register on startup and deregister on shutdown.
Registering a Service
On boot, a service announces its address to the registry.
import httpx
async def register():
await httpx.AsyncClient().put(
"http://consul:8500/v1/agent/service/register",
json={"Name": "orders", "Address": "10.0.0.5", "Port": 8000})Why Health Checks Matter
A registered instance might still be broken. Health checks ensure the registry only routes to instances that are actually able to serve requests.
A FastAPI Health Endpoint
Expose a lightweight endpoint that returns quickly when the service is healthy.
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}Liveness vs Readiness
Two distinct checks:
- Liveness: is the process alive? If not, restart it.
- Readiness: can it serve traffic now with DB connected and caches warm? If not, hold traffic.
A Readiness Check
Readiness verifies downstream dependencies before accepting traffic.
from fastapi import Response, status
@app.get("/ready")
async def ready(response: Response):
if not await db_is_up():
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"ready": False}
return {"ready": True}Kubernetes Probes
Kubernetes uses these endpoints as probes to manage pods automatically.
livenessProbe:
httpGet:
path: /health
port: 8000
readinessProbe:
httpGet:
path: /ready
port: 8000Graceful Deregistration
On shutdown, deregister so callers stop routing to a dying instance, and finish in-flight requests first.
@app.on_event("shutdown")
async def shutdown():
await deregister_from_registry()TTL and Stale Entries
Registry entries usually carry a TTL. If a service stops sending heartbeats, its entry expires automatically so callers stop routing to a dead instance.
Quick Check
Test your discovery knowledge.
Recap
You learned how services find and trust each other:
- Service discovery resolves services by name via a registry
- Health checks ensure only healthy instances get traffic
- Liveness restarts, readiness gates traffic
Together they keep a dynamic microservices system resilient.
常见问题解答
「服务发现与健康检查」课时是免费的吗?
是的 — 「服务发现与健康检查」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
「服务发现与健康检查」这节课中我会学到什么?
学习微服务如何动态发现彼此,以及健康检查如何确保流量只发送到健康的实例。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 FastAPI Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「服务发现与健康检查」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 设计微服务架构
- 服务间通信
- 使用 FastAPI 实现 API 网关
- 服务发现与健康检查