> For the complete documentation index, see [llms.txt](https://yangsx95.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yangsx95.gitbook.io/notes/architect/xing-neng-you-hua/jie-kou-xing-neng-you-hua.md).

# 接口性能优化

当出现接口性能问题时，特别是生产问题，绝不可以抱着侥幸心理，必须找到根本原因及时处理，防止下次留下更大的坑。

## 解决思路

### 定位问题

定位该接口的哪一个环节比较慢，性能瓶颈在哪儿？可以使用APM（Application Performance Monitor 应用性能监控）工具，他们主要关注分布式系统的性能监控和跟踪，比如：

* skywalking
* pinpoint
* zipkin

或者

* 使用拦截器计算接口耗时，并进行告警（钉钉、微信、邮件）
* MySql慢查询日志

如果生产环境下没有任何应用性能检测工具，可以使用**Arthas**的`trace`命令，分析具体慢的代码逻辑，该方法的定位比较粗糙。

### 解决问题

* 扩容（应用自动扩容、redis扩容、mysql在线扩容、kafka分区扩容）
* 应用重启
* 优化代码逻辑 -> 发布hotfx快速部署

## 常见的接口性能优化方案

### SQL慢

通过explain命令对执行计划进行分析：

* 锁表，将锁表的慢sql，kill掉
* 未加索引
* 有索引，但是未生效
* 小表驱动大表（尽可能的过滤掉数据）
* SQL过于复杂，可以使用代码拼接，比如如果不是查询条件，可以不join到表中，使用代码进行内存拼接
* 返回的数据量过于大，可以考虑进行分页、分批量多线程查询、直接进行条数限制、只查询部分字段
* 单表数据量过大，可以考虑进行分库分表，或者进行clickhouse、es存储
* 如果复杂sql是表单导出，可以考虑让大数据端进行处理

### 调用三方接口慢

* 如果可以的话，对三方接口进行优化
* 如果优化不了
  * 需要设置合理的超时时间
  * 集成sentinel或hystix限流熔断框架，防止对方接口拖垮我们的接口
  * 事务型操作根据实际情况决定是否需要进行重试补偿（本地消息表+job重试），比如新增、修改等操作要考虑对方接口是否支持幂等，防止超发
  * 循环调用改为批量调用，以减少IO损耗
  * 缓存查询结果（开票的三方获取token接口，每天只可重新获取一次token）

### 中间件慢

* redis慢
  * 热key：考虑使用本地缓存替换
  * 大key：拆分大key、或使用hash结构而不是json再进行返序列化
* kafka慢：
  * 生产端慢：可以使用阻塞队列接收、或者批量丢入消息
  * 消费端慢：扩分区、增加消费节点、增加消费线程、批量消费、批量写库

### 程序逻辑慢

* 非法校验逻辑前置，避免无用数据穿透消耗系统资源，减少无用调用
* 循环调用改为单次调用，数据在内存组装处理
* 可以异步调用的地方由同步改为异步调用
* 非核心逻辑剥离，拆分大事务，采用mq异步解耦


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://yangsx95.gitbook.io/notes/architect/xing-neng-you-hua/jie-kou-xing-neng-you-hua.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.
