需求
公司要各个服务之间调用要在header中传requestid,以通过此requestid 方便查找服务的调用方,并且可通过此requestid展示出贯穿整个服务的流程,但是规划如此,进度总是一拖再拖,只能进行强制措施了,不传requestid的服务禁止访问,由于所有服务的入口基本是在nginx这里,所以从nginx入手,通过判断header中没有requestid的返回403状态码并进行相关提示。
具体步骤
1. 先配置个服务用于测试
nginx配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| server{ listen 80; server_name header-hotfix.xk12.cn; access_log /xdfapp/logs/nginx/header-access-https.log main; error_log /xdfapp/logs/nginx/header-error-https.log info;
root /xdfapp/apps/headher-test;
add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' ; add_header Pragma "public"; add_header Cache-Control "public"; client_body_temp_path /tmp 1 2; client_body_in_file_only off; index index.php index.html index.htm; set $error_body '403 Error, 没传requestid, 请传一下requestid。'; if ( $http_requestid = "" ){ return 403 "$error_body"; } location ~ \.php { include fastcgi_params; set $path_info ""; set $real_script_name $fastcgi_script_name; if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") { set $real_script_name $1; set $path_info $2; } fastcgi_param SCRIPT_FILENAME $document_root$real_script_name; fastcgi_param SCRIPT_NAME $real_script_name; fastcgi_param PATH_INFO $path_info; fastcgi_param DEV_ENV hotfix; fastcgi_intercept_errors on; fastcgi_pass 127.0.0.1:9000; }
}
|
写个php程序,展示header中的内容
1 2 3 4
| # cat /xdfapp/apps/headher-test/index.php <?php print_r($_SERVER); ?>
|
2. 使用curl 测试一下
没有加requestid这个header,则返回我们设置的提示内容
1 2
| # curl -x 127.0.0.1:80 header-hotfix.xk12.cn 403 Error, 没传requestid, 请传一下requestid。
|
加requestid在试一下,返回正常了,并且在倒数第五行打印出了我传进去的requestid。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| # curl -H "requestid:112" -x 127.0.0.1:80 header-hotfix.xk12.cn Array ( [USER] => web [HOME] => /home/web [FCGI_ROLE] => RESPONDER [QUERY_STRING] => [REQUEST_METHOD] => GET [CONTENT_TYPE] => [CONTENT_LENGTH] => [SCRIPT_NAME] => /index.php [REQUEST_URI] => / [DOCUMENT_URI] => /index.php [DOCUMENT_ROOT] => /xdfapp/apps/headher-test [SERVER_PROTOCOL] => HTTP/1.1 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_SOFTWARE] => nginx/1.6.2 [REMOTE_ADDR] => 127.0.0.1 [REMOTE_PORT] => 12741 [SERVER_ADDR] => 127.0.0.1 [SERVER_PORT] => 80 [SERVER_NAME] => header-hotfix.xk12.cn [REDIRECT_STATUS] => 200 [SCRIPT_FILENAME] => /xdfapp/apps/headher-test/index.php [PATH_INFO] => [DEV_ENV] => hotfix [HTTP_USER_AGENT] => curl/7.29.0 [HTTP_HOST] => header-hotfix.xk12.cn [HTTP_ACCEPT] => */* [HTTP_PROXY_CONNECTION] => Keep-Alive [HTTP_REQUESTID] => 112 [PHP_SELF] => /index.php [REQUEST_TIME_FLOAT] => 1560320601.7359 [REQUEST_TIME] => 1560320601 )
|
实战中的坑
- 坑位1,return 403 “提示语” 这样用curl是正常的,但是浏览器不支持这种告警