Nginx集群与SpringCloud Gateway集成Nacos的配置指南

Nginx集群与SpringCloud Gateway集成Nacos的配置指南

最牛逼的SpringCloudAlibab微服务实战全栈开发

环境准备

  • Nginx 1.18+
  • JDK 8+
  • SpringCloud Gateway 2.2+
  • Nacos Server 1.4+

Nginx集群配置

安装与基础配置

在每台Nginx服务器上安装Nginx,修改nginx.conf主配置文件:

复制代码
worker_processes auto;
events {
    worker_connections 10240;
    use epoll;
}

http {
    upstream gateway_cluster {
        least_conn;
        server 192.168.1.101:9999 weight=5;
        server 192.168.1.102:9999 weight=5;
        keepalive 32;
    }
}

负载均衡策略

添加负载均衡参数:

复制代码
upstream gateway_cluster {
    server 192.168.1.101:9999 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:9999 max_fails=3 fail_timeout=30s;
    hash $request_uri consistent;
}

高并发优化

在http块中添加:

复制代码
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
client_max_body_size 20m;
gzip on;

SpringCloud Gateway配置

POM依赖

xml 复制代码
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

bootstrap.yml

yaml 复制代码
spring:
  application:
    name: api-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        namespace: public
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/user/**
          filters:
            - StripPrefix=1

动态路由配置

创建DynamicRouteConfig.java:

java 复制代码
@Configuration
public class DynamicRouteConfig {
    @Bean
    public RouteDefinitionWriter routeDefinitionWriter() {
        return new InMemoryRouteDefinitionRepository();
    }
}

Nacos服务注册发现

Nacos Server配置

修改application.properties:

复制代码
server.port=8848
nacos.naming.empty-service.auto-clean=true
nacos.naming.clean.empty-service.interval=60000

服务提供者配置

在服务提供者的application.yml中添加:

yaml 复制代码
spring:
  cloud:
    nacos:
      discovery:
        cluster-name: DEFAULT
        ephemeral: true
        heart-beat-interval: 5000
        heart-beat-timeout: 15000

高并发调优

Gateway线程池配置

在application.yml中增加:

yaml 复制代码
server:
  tomcat:
    max-threads: 1000
    min-spare-threads: 50

Nginx健康检查

配置主动健康检查:

复制代码
upstream gateway_cluster {
    zone gateway 64k;
    server 192.168.1.101:9999 slow_start=30s;
    server 192.168.1.102:9999 slow_start=30s;
    health_check interval=5s uri=/health timeout=3s;
}

熔断限流配置

Gateway熔断设置

添加Resilience4J依赖后配置:

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
        - id: circuitbreaker_route
          uri: lb://user-service
          predicates:
            - Path=/api/user/**
          filters:
            - name: CircuitBreaker
              args:
                name: myCircuitBreaker
                fallbackUri: forward:/fallback

Redis限流配置

集成Redis限流过滤器:

java 复制代码
@Bean
public RedisRateLimiter redisRateLimiter() {
    return new RedisRateLimiter(10, 20, 1);
}

监控与日志

Prometheus监控

添加监控端点:

yaml 复制代码
management:
  endpoints:
    web:
      exposure:
        include: prometheus,health,info
  metrics:
    tags:
      application: ${spring.application.name}

Nginx日志格式化

配置访问日志格式:

复制代码
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 /var/log/nginx/access.log main buffer=32k flush=5s;

集群验证步骤

启动Nacos Server后依次启动各服务

通过Nginx访问网关接口验证负载均衡

检查Nacos控制台服务注册状态

使用JMeter进行压力测试,监控各节点资源使用情况

常见问题处理

服务未注册:检查Nacos地址和命名空间配置

502错误:验证Gateway服务是否健康

性能瓶颈:调整Nginx的worker_connections和Gateway线程数

路由失效:确认Nacos配置的自动刷新间隔

相关推荐
耀耀_很无聊2 小时前
17_Spring Boot 使用 MDC 实现 TraceId 日志追踪
java·spring boot·后端
CoderYanger3 小时前
Java EE 进阶:15. Linux基本使用和程序部署(第二弹):部署 Web 项目到 Linux
linux·服务器·数据库·spring boot·spring·阿里云·java-ee
程序员小杰@3 小时前
SpringBoot + SpringCloudAlibaba 日志 & 链路追踪 完整总结
java·spring boot·后端
IT研究室6 小时前
最新计算机毕业设计选题推荐-基于spring boot的房屋交易系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
RuoyiOffice6 小时前
Java物联网项目拆解:设备接入之后,数据怎样真正用起来
java·vue.js·spring boot·物联网·iot·企业管理·ruoyi office
淘源码A7 小时前
智能预问诊系统源码,基于SpringBoot、MyBatis-Plus、uni-app等技术栈,开箱即用
java·spring boot·源码·二次开发·电子病历·预问诊·智能预问诊
IT枫斗者9 小时前
AI Coding 蜜月期之后,我们重新思考了 AI 提效
java·开发语言·人工智能·gateway·fastapi
钱栈up13 小时前
删 18 个模块全程零报错:烧结系统单体拆微服务的 P0 实操
spring boot·微服务
软件技术NINI1 天前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
顧棟1 天前
INFINI Gateway 启动过程分析
服务器·网络·gateway