记录:前后端拆分后的组合


  最近设计架构时,有个场景,首先是前后端分离,再就是一前端对多后端,这里需要解决两件事,一是前端的html,js,css需要一个host;二是需要一个api网关,能组织后端的api服务。有很多反向代理产品能实现,这里选择了Nginx来实现。

  下面是在一个前端的html文件中调用后端api的例子,前端是不知道后端的api是不是组合的,所以只用相对路径请求就ok




Welcome to nginx!



Welcome to nginx!

If you see this page, the nginx web server is successfully installed and working. Further configuration is required.

For online documentation and support please refer to "http://nginx.org/">nginx.org.
Commercial support is available at "http://nginx.com/">nginx.com.

Thank you for using nginx.

"a">


"b">

下面nginx的配置

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       8484;
        server_name  localhost; 
        location / {
            root   html;
            index  index.html index.htm;
        }    
    #-------
    location /service_a/ {
       proxy_pass http://localhost:5001/;
    }
    location /service_b/ {
       proxy_pass http://localhost:6001/;
    }
    #-------     
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

其实的A服务,B服务相似

namespace NginxTest1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        private readonly ILogger _logger;
        public TestController(ILogger logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public string Get()
        {
            var str = "ServiceA:5001_" + DateTime.Now;
            _logger.LogInformation(str);
            return str;
        }
    }
}

运给的结果

 关于前后端服务的部署,就随便了,可虚机,可docker

  想要更快更方便的了解相关知识,可以关注微信公众号