nginx发起http请求

桃扇骨 2022-06-18 10:28 381阅读 0赞

配置

可以用proxypass

配置文件如下:

  1. worker_processes 2; #nginx worker 数量
  2. error_log logs/error.log; #指定错误日志文件路径
  3. events {
  4. worker_connections 1024;
  5. }
  6. http {
  7. upstream md5_server{
  8. server 127.0.0.1:81;
  9. keepalive 20;
  10. }
  11. server {
  12. listen 1024;
  13. location /test {
  14. content_by_lua_block {
  15. ngx.req.read_body()
  16. local args, err = ngx.req.get_uri_args()
  17. local res = ngx.location.capture('/spe_md5',
  18. {
  19. method = ngx.HTTP_POST,
  20. body = args.data
  21. }
  22. )
  23. if 200 ~= res.status then
  24. ngx.exit(res.status)
  25. end
  26. ngx.say(args.data)
  27. ngx.say(res.body)
  28. if args.key == res.body then
  29. ngx.say("valid request")
  30. else
  31. ngx.say("invalid request")
  32. end
  33. }
  34. }
  35. location /spe_md5 {
  36. proxy_pass http://md5_server;
  37. #For HTTP, the proxy_http_version directive should be set to “1.1” and the “Connection”
  38. #header field should be cleared.(from:http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive)
  39. proxy_http_version 1.1;
  40. proxy_set_header Connection "";
  41. }
  42. }# server port 1024
  43. server {
  44. listen 81;
  45. location /spe_md5 {
  46. content_by_lua_block {
  47. ngx.req.read_body()
  48. local data = ngx.req.get_body_data()
  49. ngx.print(ngx.md5(data))
  50. }
  51. }
  52. }
  53. }

配置了一个81端口的上游服务器,并在/test下用capture做了一个子查询,最后返回md5值

测试

  1. curl -v -X GET 'localhost:1024/test?key=5d41402abc4b2a76b9719d911017c592&data=hello'

参考

openresty最佳实践

发表评论

表情:
评论列表 (有 0 条评论,381人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java发起http请求

    在日常工作中,我们经常会遇到需要调用内部 API 或者第三方 API 的情况,主要有以下方式: 一、HttpURLConnection 占坑 二、HttpClien