1.安装启动nginx


(1).安装编译工具及库文件

yum -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

Nginx安装启动+springboot项目实现负载均衡实战

 

(2).安装 PCRE,下载地址: https://ftp.pcre.org/pub/pcre/pcre-8.35.tar.gz

[root@localhost ~]# cd /usr/local/src/
[root@localhost src]# wget https://ftp.pcre.org/pub/pcre/pcre-8.35.tar.gz
[root@localhost src]# tar -zxvf pcre-8.35.tar.gz
[root@localhost src]# cd pcre-8.35/
[root@localhost pcre-8.35]# ./configure && make && make install

 

(3).安装nginx,下载地址: http://nginx.org/download/nginx-1.6.2.tar.gz

[root@localhost src]# cd /usr/local/src/
[root@localhost src]# wget http://nginx.org/download/nginx-1.6.2.tar.gz
[root@localhost src]# tar -zxvf nginx-1.6.2.tar.gz
[root@localhost src]# cd nginx-1.6.2/
[root@localhost nginx-1.6.2]# ./configure && make && make install

 

(4).启动nginx

[root@localhost /]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ./nginx

Nginx安装启动+springboot项目实现负载均衡实战

2.springboot项目实现负载均衡示例


(1).创建springboot项目

Nginx安装启动+springboot项目实现负载均衡实战

 

(2).编写可访问的demo代码

package com.project.demo.spring.boot.controller;

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

/**
 * @author:wk
 * @date:2020/9/11
 */
@ResponseBody
@Controller
@RequestMapping("/demo")
public class TestController {
    @GetMapping("/getServerName")
    public String getServerName() {
        return "server1";
    }
}

 

(3).将项目打包放到一台机器上,改动返回值为"server2"并将其打包放到另一台机器上,分别启动

 Nginx安装启动+springboot项目实现负载均衡实战

Nginx安装启动+springboot项目实现负载均衡实战

 

(4).修改nginx负载均衡方面配置(默认为轮询方式),并保存

upstream myServer {
        server 10.1.4.85:8080;
        server 10.1.8.116:8080;
    }

    server {
        listen       7000;
        server_name  localhost;

        location / {
            proxy_pass http://myServer;
            root   html;
            index  index.html index.htm;
        }

 

(5).重载nginx配置

[root@localhost nginx]# cd /usr/local/nginx/sbin/
[root@localhost sbin]# ./nginx -s reload

 

(6).这时多次访问http://(nginx安装机器ip):7000/demo/getServerName,就会发现会轮询的调用10.1.4.85和10.1.8.116的接口

 Nginx安装启动+springboot项目实现负载均衡实战

相关文章:

  • 2021-07-03
  • 2021-05-01
  • 2021-12-30
  • 2021-04-04
  • 2021-12-04
猜你喜欢
  • 2021-06-14
  • 2021-09-15
  • 2021-05-17
  • 2022-12-23
  • 2022-02-01
  • 2021-06-29
  • 2021-11-08
相关资源
相似解决方案