前言
大家好,我是老马。很高兴遇到你。
我们为 java 开发者实现了 java 版本的 nginx
如果你想知道 servlet 如何处理的,可以参考我的另一个项目:
手写从零实现简易版 tomcat minicat
手写 nginx 系列
如果你对 nginx 原理感兴趣,可以阅读:
从零手写实现 nginx-01-为什么不能有 java 版本的 nginx?
从零手写实现 nginx-03-nginx 基于 Netty 实现
从零手写实现 nginx-04-基于 netty http 出入参优化处理
从零手写实现 nginx-05-MIME类型(Multipurpose Internet Mail Extensions,多用途互联网邮件扩展类型)
从零手写实现 nginx-12-keep-alive 连接复用
从零手写实现 nginx-13-nginx.conf 配置文件介绍
从零手写实现 nginx-14-nginx.conf 和 hocon 格式有关系吗?
从零手写实现 nginx-15-nginx.conf 如何通过 java 解析处理?
从零手写实现 nginx-16-nginx 支持配置多个 server
从零手写实现 nginx-18-nginx 请求头+响应头操作
从零手写实现 nginx-20-nginx 占位符 placeholder
从零手写实现 nginx-21-nginx modules 模块信息概览
从零手写实现 nginx-22-nginx modules 分模块加载优化
从零手写实现 nginx-23-nginx cookie 的操作处理
从零手写实现 nginx-26-nginx rewrite 指令
从零手写实现 nginx-27-nginx return 指令
从零手写实现 nginx-28-nginx error_pages 指令
从零手写实现 nginx-29-nginx try_files 指令
从零手写实现 nginx-30-nginx proxy_pass upstream 指令
从零手写实现 nginx-31-nginx load-balance 负载均衡
从零手写实现 nginx-32-nginx load-balance 算法 java 实现
从零手写实现 nginx-33-nginx http proxy_pass 测试验证
从零手写实现 nginx-34-proxy_pass 配置加载处理
从零手写实现 nginx-35-proxy_pass netty 如何实现?
配置加载
配置文件的例子
- nginx-proxy-pass.conf
配置文件加载
下面的实现主要用来解析 upstream 模块处理。
配置的预处理
我们在处理配置的时候,需要处理一下上面的配置
整体逻辑
直接处理上述的 NginxUserServerLocationConfig 加载处理,针对 proxy_pass 指令解析处理。
getUpstreamName 获取 upstreamName
假如配置信息为 proxy_pass http://backend;
那么我们需要解析到 backend
作为 upstreamName。
getUpstreamConfig 获取配置信息
如果我们得到了 upstreamName,那么如何找到对应的 upstream 配置呢?
根据 upstream 名称,找到对应的配置信息。
buildServerList 如何构建对应的目标服务器列表?
这里稍微繁琐一点。
默认配置
我们首先可以指定默认的端口:
在 HTTP 和 HTTPS 通信中,默认端口号如下:
- HTTP: 默认端口是 80。
- HTTPS: 默认端口是 443。
核心实现
核心实现如下:
- 没找到对应的 upstream
直接根据指定的配置,构建服务器列表。
比如 proxy_pass http://localhost:8080;
- 找到对应的 upstream 配置
根据对应的服务器列表,构建对应的列表即可。
这里需要注意一下细节,处理一下 host+port+weight
小结
到这里开始,我们介绍了如何解析配置文件。
并且介绍了针对 proxy_pass 的指令,如何做好对应的配置解析处理。
下一节,我们一起看一下如何实现 proxy_pass 的反向代理。