nginx

Author Avatar
kevin
发表:2022-09-25 14:21:00
修改:2024-10-09 14:21:32

三大核心:反向代理,负载均衡,动静分离

高性能的HTTP和反向代理web服务器

widows安装

官方网站:http://nginx.org/

双击 nginx.exe , 一闪而过就说明服务开起了

linux可以使用docker安装

# 拉 nginx 镜像
docker pull nginx
# 安装 nginx 镜像
docker run --name nginx \
    -p 80:80 \
    -v /docker/nginx/config:/etc/nginx/conf.d \
    -v /docker/nginx/html:/usr/share/nginx/html \
    -d nginx

配置文件

conf 目录下主配置文件 nginx.conf

  • http全局配置
    • http配置里可以包含多个server配置
    • 每个server 就相当于一个虚拟主机配置
    • server配置
      • 最常见的配置是本虚拟机主机的监听配置和本虚拟主机的名称或IP配置。
      • listen配置端口号
      • 可以配置多个location
        • 主要作用是基于 Nginx 服务器接收到的请求字符串

Nginx反向代理

连接nginx自动跳转到tomcat

proxy_pass http://xxxx:将所有请求转发到tomcats服务器组中配置的某一台服务器上

upstream模块:反向代理服务器组

upstream模块下的server指令:配置处理请求的服务器IP或域名,端口可选,不配置默认使用80端口

http配置下加上

# 反向代理配置,tomcats必须和location配置网址一致
	upstream tomcats {
	   # 这个是tomcat的访问路径
	   server localhost:8080;
	   
	}

location下配置

  location / {
            root   html;
            # 注意:如果反向代理失败,去掉下划线,直接使用serverlist;
			# 网址随便写,但是得和upstream对应
			proxy_pass http://tomcats ;
            index  index.html index.htm;
        }

nginx负载均衡

准备多台tomcat服务器

一般有以下几种规则

  • 轮询(默认)

    • Nginx根据请求次数,将每个请求均匀分配到每台服务器

    • 	# 反向代理配置
      	upstream tomcats{
      	   # 这个是tomcat的访问路径
      	   server localhost:8080;
      	   server localhost:9999;
      	}
      
  • weight 权重

    • weight 代表权重,默认为1,权重越高被分配的客户端越多

    • # 反向代理配置
      upstream tomcats{
      # 这个是tomcat的访问路径
      server localhost:8080 weight=5;
      server localhost:9999 weight=1;
      }
      
  • ip_hash

    • 第一次请求时,根据该客户端的IP算出一个HASH值

    • 不管刷新多少遍,始终访问的是同一台tomcat服务器

    • # 反向代理配置
      upstream tomcats{
          ip_hash; 
      # 这个是tomcat的访问路径
      server localhost:8080 ;
      server localhost:9999 ;
      }
      
  • 最少连接

    • 请求分配给连接数最少的服务器。Nginx会统计哪些服务器的连接数最少

    • # 反向代理配置
      upstream tomcats{
         least_conn;
      # 这个是tomcat的访问路径
      server localhost:8080 ;
      server localhost:9999 ;
      }
      

实现session共享

Nginx+tomcat集群+redis实现session共享

下载:https://github.com/ran-jit/tomcat-cluster-redis-session-manager/wiki

解压之后。将jar包放入tomcat的lib中,所有的tomcat下的lib都要放

配置解压之后的redis-data-cache.properties,端口号等

配置完将这个文件放入tomcat/conf文件夹中。

配置tomcat/cong/context.xml,增加如下两行

<Valve className="tomcat.request.session.redis.SessionHandlerValve"/>
<Manager className="tomcat.request.session.redis.SessionManager"/>

启动redis, 重启tomcat即可

评论