问题背景
最近公司在优化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"}
评论区