您的位置:首页 > 运维架构 > Tomcat

nginx配置三台tomcat的负载均衡

2019-05-31 16:06 375 查看

从一点半到三点半终于实现了用nginx对三台tomcat实现负载均衡。
现在记录一下整个实现的过程。
第一步
我准备了三台服务器
192.168.32.130 spark1
192.168.32.131 spark2
192.168.32.132 spark3
第二步
分别在三台服务器上安装了tomat
第三步
编写 一个java程序 打成war包 并发布到tomcat上

package com.imooc.myo2o.web.test;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.InetAddress;

@Controller
@RequestMapping(value = "test")
public class TestController {
@RequestMapping(value = "/host")
@ResponseBody
private String test(){
String host = null;
try{
host = InetAddress.getLocalHost().getHostName();
System.out.println("打印Host: "+host);
}catch (Exception e){
e.printStackTrace();
}
return host;
}
}

第四步
配置nginx
如果还没有安装nginx,以下安装nginx的详细教程可以参考
https://blog.csdn.net/qq_37554565/article/details/90713663
安装完nginx后接着配置 /usr/local/nginx/conf/nginx.conf

主要是配置

upstream tomcats {
server 192.168.32.130:8080 weight=1;
server 192.168.32.131:8080 weight=1;
server 192.168.32.132:8080 weight=1;
}
和
server的
location ~ .* {
proxy_pass http://tomcats;
root   html;
index  index.html index.htm;
}

以下面是nginx.conf的完整内容

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
worker_connections  1024;
}

http {
include       mime.types;
default_type  application/octet-stream;

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

#access_log  logs/access.log  main;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;

#gzip  on;
upstream tomcats {
server 192.168.32.130:8080 weight=1;
server 192.168.32.131:8080 weight=1;
server 192.168.32.132:8080 weight=1;
}
server {
listen       80;
server_name  localhost;

#charset koi8-r;

#access_log  logs/host.access.log  main;

location ~ .* {
proxy_pass http://tomcats;
root   html;
index  index.html index.htm;
}

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
}

}

第五步 启动nginx

# 检验文件
[root@spark1 nginx]# sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
# 加载修改文件
[root@spark1 nginx]# sbin/nginx -s reload
[root@spark1 nginx]# sbin/nginx

第六步 访问测试端口
页面访问 http://192.168.32.130/shop/test/host 的接口会平均分发到spark1、spark2、spark3上
如图



到这里就实现了用nginx实现对一个请求分散到三台服务器了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: