- 下载最新版的nginx,我这里使用的是windows-1.19.8版本做测试,之前下载的低版本,试验了很久都没有成功,应该是配置写法有所更新。
- 接着,我通过springboot部署了两个tomcat,端口分别是8881和8882,添加一个Controller如下。
8881
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello (){
System.out.println("hello world, this is nginx01");
return "hello world, this is nginx01";
}
@RequestMapping("/hi")
public String hi(){
System.out.println("hi, this is nginx01");
return "hi, this is nginx01";
}
}
8882
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello (){
System.out.println("hello world, this is nginx02");
return "hello world, this is nginx02";
}
}
- 配置nginx,nginx解压即可用,打开conf目录下的nginx.conf文件,根据自己的项目环境进行配置。
位置③处固定写法,指向位置①,位置①处配置集群和各个服务的权重,比较直观好懂,位置②处配置nginx监听端口和服务名,重要的是端口的配置,如果默认80端口被占用,服务会启动失败。
windows版的nginx启动时,一闪而过,像是程序闪退,实际上是启动成功了的,在任务管理器的进程里面可以看到。 - 通过nginx反向代理测试
先只启动8881 tomcat服务,访问http://localhost:8080
springboot添加的tomcat依赖没有首页面,正常。接着访问http://localhost:8080/hello
无论访问多少次都是返回这个,因为目前集群中只启动了一台服务,接着我们再启动8882 tomcat服务,继续访问/hello,页面交替(不是严格轮训交替,整体上保持相同的权重)显示hello world, this is nginx01
和hello world, this is nginx02
。
再访问http://localhost:8080/hi
,页面显示hi, this is nginx01
,再刷新,可能显示error页面,因为8882这个tomcat没有这个请求,所以会报404。