# 微服务中的服务发现

在单体架构时，因为服务不会经常和动态迁移，所有服务地址可以直接在配置文件中配置，所以也不会有服务发现的问题。但是对于微服务来说，应用的拆分，服务之间的解耦，和服务动态扩展带来的服务迁移，服务发现就成了微服务中的一个关键问题。

服务发现分为**客户端服务发现**和**服务端服务发现**两种，架构如下图所示。

![微服务中的服务发现](/files/-Lxzn4Utl2UpR1MLwKG3)

这两种架构都各有利弊，我们拿客户端服务发现软件Eureka和服务端服务发现架构Kubernetes/SkyDNS+Ingress LB+Traefik+PowerDNS为例说明。

| 服务发现方案     | Pros                                         | Cons                                       |
| ---------- | -------------------------------------------- | ------------------------------------------ |
| Eureka     | 使用简单，适用于java语言开发的项目，比服务端服务发现少一次网络跳转          | 对非Java语言的支持不够好，Consumer需要内置特定的服务发现客户端和发现逻辑 |
| Kubernetes | Consumer无需关注服务发现具体细节，只需知道服务的DNS域名即可，支持异构语言开发 | 需要基础设施支撑，多了一次网络跳转，可能有性能损失                  |

**Eureka** 也不是单独使用的，一般会配合 ribbon 一起使用，ribbon 作为路由和负载均衡。

**Ribbon**提供一组丰富的功能集：

* 多种内建的负载均衡规则：
  * Round-robin 轮询负载均衡
  * 平均加权响应时间负载均衡
  * 随机负载均衡
  * 可用性过滤负载均衡（避免跳闸线路和高并发链接数）
  * 自定义负载均衡插件系统
* 与服务发现解决方案的可拔插集成（包括Eureka）
* 云原生智能，例如可用区亲和性和不健康区规避
* 内建的故障恢复能力

## 参考

* [谈服务发现的背景、架构以及落地方案](http://www.infoq.com/cn/articles/background-architecture-and-solutions-of-service-discovery)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hezhiqiang.gitbook.io/kubernetes-handbook/ling-yu-ying-yong/microservices/service-discovery-in-microservices.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
