侧边栏壁纸
博主头像
行至个人博客博主等级

行动起来,活在当下

  • 累计撰写 3 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

nginx实现动态返回数据

zhangyx
2024-02-24 / 0 评论 / 0 点赞 / 14 阅读 / 2452 字

问题背景

最近公司在优化api服务,其中一个接口功能是随机返回json数据,请求量较大,于是想将这个接口交由nginx来处理。

实现方式

由于只返回了有限个数的不同json串,所以想通过nginx创建多个server,通过原来请求的location,转发到当前nginx的这多个server上,来实现随机返回多个json。

nginx配置

# nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    upstream test-node {
            server localhost:8081;
            server localhost:8082;
    }

    server {
        listen       80;
        server_name  localhost;
        location /json {
		proxy_pass http://test-node;
        }
    }

    server {
        listen       8081;
        server_name  localhost;
        location / {
    		default_type application/json;
		    return 200 '{"key1":value1"}';
	    }
    }

    server {
        listen       8082;
        server_name  localhost;
        location / {
    		default_type application/json;
		return 200 '{"key2":value2"}';
        }
    }
}

请求测试

root# curl http://localhost/json
{"key2":value2"}
root# curl http://localhost/json
{"key1":value1"}
root# curl http://localhost/json
{"key1":value1"}
root# curl http://localhost/json
{"key2":value2"}
0

评论区