反向代理是指用代理服务器来接受客户端的连接请求,然后将请求转发给内部网络中的上游服务器,并将从上游服务器上得到的结果返回给客户端,此时代理服务器对外的表现就是一个Web服务器。
一个简单的SpringBoot项目,打成jar包
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Value("${server.port}")
private String port;
@GetMapping("/luochao/test")
public String test() {
return "Nginx反向代理服务器:" + port;
}
}
修改本地hosts文件
62.234.142.115 www.luochao.com
java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8081使用8081端口启动
使用ip+端口访问
修改nginx.conf文件配置反向代理
server {
listen 80;
server_name www.luochao.com;
location / {
proxy_pass http://62.234.142.115:8081;
index index.html index.htm;
}
}
使用域名反向代理
proxy_pass 该指令用来配置代理服务器的URL
URL参数规则:
- 必须以http://或者https://开头
- 接下来是域名或者ip
- 域名和ip后可以加端口
- 最后是可选的URI
URL参数中携带URI与否,会导致转发给上游请求的URL不同
- 不携带URI,将客户端请求的URL直接转发给上游
- 携带URI,则对用户请求中的URL作如下操作
将location参数中匹配的一段替换为该URI
server {
listen 80;
server_name www.luochao.com;
location /abc {
proxy_pass http://62.234.142.115:8081/luochao;
index index.html index.htm;
}
}
访问http://www.luochao.com/abc/test
会将匹配的/abc换成/luochao
作为代理服务器,一般都需要向上游服务器的集群转发请求。这里的负载均衡是指选择一种策略,尽量把请求平均地分布到每一台上游服务器上
分别在8081和8082端口启动项目
java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8081使用8081端口启动
java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8082使用8082端口启动
upstream块定义了一个上游服务器的集群,便于反向代理中的proxy_pass使用
加权轮询的负载均衡策略
upstream wangzx {
server 62.234.142.115:8081 weight=2;
server 62.234.142.115:8082;
}
server {
listen 80;
server_name www.luochao.com;
location / {
proxy_pass http://wangzx;
index index.html index.htm;
}
}
访问http://www.luochao.com/luochao/test
两次8081,一次8082