在本地起多个服务,形成集群环境

158 阅读2分钟

Step 1:

利用IntelliJ启动多个服务,每个服务的端口是不同的。其实是启动了多个tomcat。具体操作见下图:

如图,我们已经在8080端口和8081端口都启动了服务。图中有一个错误就是:8082那里要加上参数名字:-Dserver.port=8082;

Step 2:

利用nginx做反向代理,当我们访问某一个domain的时候,让请求平均的访问到两个服务上。

  1. 这一步首先要安装nginx:brew install nginx

  2. 安装完之后,可以查一下nginx的版本,已确定安装成功: nginx -v

  3. 启动nginx:nginx 但是nginx运行在8080端口,所以要先把8080端口的服务关掉。备注:端口号是在配置文件 nginx.conf 里面配置的,默认端口是 8080 ,配置文件的位置 /usr/local/etc/nginx/nginx.conf

  4. 成功启动后,就可以在http://localhost:8080访问到nginx了

  5. 关闭nginx的命令:nginx -s stop

  6. 更改nginx.config文件,更改后的配置文件如下

    http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65;

    server {
        listen       8080;
        server_name  localhost;
    
        location / {
            root   html;
            index  index.html index.htm;
        }
    
        location /api {
            default_type  application/json;
            # internal;
            keepalive_timeout 30s;
            keepalive_requests 1000;
            # 支持keep-alive
            proxy_http_version 1.1;
            rewrite /api(/.*) $1 break;
            proxy_pass_request_headers on;
            # more_clear_input_headers Accept-Encoding;
            proxy_next_upstream error timeout;
            # proxy_pass http:127.0.0.1:8081
            proxy_pass http://backend;
        }
    }
    
    upstream backend {
        server 127.0.0.1:8081 max_fails=5 fail_timeout=10s weight=1;
        server 127.0.0.1:8082 max_fails=5 fail_timeout=10s weight=1;
    }
    

    }

这时,如果调用nginx启动在8080端口上,当我们调用localhost:8080/api时,nginx就会帮我们把请求转发到127.0.0.1:8001 和 127.0.0.1:8082上。

  1. api调用。现在我们调用的api改成了:localhost:8080/api/voucher-order/seckill/7 这跟调用localhost:8081/voucher-order/seckill/7localhost:8082/voucher-order/seckill/7的效果是一样的。当然啦,这个url是这个服务里的一个接口,不用在意啦。