nginx的upstream与算法是怎么组织的

mac2024-01-24  36

 

upstream的数据结构

ngx_http_upstream_main_conf_t { ngx_array_t upstreams; /* ngx_http_upstream_srv_conf_t* */ } ngx_http_upstream_srv_conf_t { ngx_http_upstream_peer_t peer; /* 算法 */ ngx_array_t *servers; /* ngx_http_upstream_server_t */ }; typedef struct { ngx_str_t name; ngx_addr_t *addrs; ngx_uint_t naddrs; ngx_uint_t weight; ngx_uint_t max_conns; ngx_uint_t max_fails; time_t fail_timeout; ngx_msec_t slow_start; ngx_uint_t down; unsigned backup:1; } ngx_http_upstream_server_t; typedef struct { /* 初始化下面两个变量 data,init, 如ngx_http_upstream_init_round_robin */ ngx_http_upstream_init_pt init_upstream; /* 初始化request中的数据结构,如ngx_http_upstream_init_round_robin_peer */ ngx_http_upstream_init_peer_pt init; /* 负载均衡算法的数据结构 ngx_http_upstream_rr_peers_t */ void *data; } ngx_http_upstream_peer_t;

rr算法的数据结构

typedef struct { ngx_uint_t config; ngx_http_upstream_rr_peers_t *peers; ngx_http_upstream_rr_peer_t *current; uintptr_t *tried; uintptr_t data; } ngx_http_upstream_rr_peer_data_t; ngx_http_upstream_rr_peers_t { ngx_uint_t number; ngx_http_upstream_rr_peers_t *next; ngx_http_upstream_rr_peer_t *peer; /* 数组 */ }; ngx_http_upstream_rr_peer_t { struct sockaddr *sockaddr; socklen_t socklen; ngx_str_t name; ngx_str_t server; ... }

request如何获取后端

ngx_http_request_t { ngx_http_upstream_t *upstream; } ngx_http_upstream_t { ngx_peer_connection_t peer; ngx_http_upstream_conf_t *conf; ngx_http_upstream_srv_conf_t *upstream; } ngx_peer_connection_t { ngx_connection_t *connection; struct sockaddr *sockaddr; socklen_t socklen; ngx_str_t *name; ngx_event_get_peer_pt get; /* 获取后端 ngx_http_upstream_get_round_robin_peer */ ngx_event_free_peer_pt free; void *data; /* 算法相关数据结构, 如ngx_http_upstream_rr_peer_data_t */ }

总结

一个upstream的所有的server的配置存放在ngx_http_upstream_server_t数组中;算法和算法相关的数据结构放在ngx_http_upstream_peer_t中;一个request获取后端是从request->upstream->peer.get()获取。

最新回复(0)