百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

[Java实战]Springboot项目高并发性能优化

zhezhongyun 2025-06-10 04:05 31 浏览

一、测试验证结果

1.1 功能测试

#优化前
 curl -X POST http://127.0.0.1:8080/api/users   -H "Content-Type: application/json"   -d '{"name":"张三","email":"zhangsan@example.com"}'   -v
#优化后
 curl -X POST http://127.0.0.1:8081/api/users   -H "Content-Type: application/json"   -d '{"name":"张三","email":"zhangsan@example.com"}'   -v

1.2 性能测试

优化前:12000 qps
优化后:36000 qps

1.3 代码运行截图

二、问题根因分析

2.1 线程模型瓶颈

Spring Boot默认的Tomcat容器使用BIO/NIO模型,每个请求占用1个线程,当长连接数超过线程池容量时会发生排队甚至拒绝

2.2 同步阻塞处理

若业务逻辑中存在同步阻塞操作(如同步数据库查询),会快速耗尽线程资源

2.3 上下文切换开销

大量线程导致CPU时间片频繁切换,实际有效利用率降低

三、Netty替代方案(针对高并发长连接场景)

3.1 原架构

package com.example.controller;

import com.example.model.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/api")
public class ApiController {

    private final List<User> users = new ArrayList<>();
    private final AtomicLong counter = new AtomicLong();

    // 测试接口
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }

    // 获取所有用户
    @GetMapping("/users")
    public List<User> getAllUsers() {
        return users;
    }

    // 创建用户
    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        user.setId(counter.incrementAndGet());
        users.add(user);
        return user;
    }

    // 根据ID查询用户
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        return users.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("User not found"));
    }

    // 更新用户
    @PutMapping("/users/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        User user = users.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("User not found"));

        user.setName(userDetails.getName());
        user.setEmail(userDetails.getEmail());
        return user;
    }

    // 删除用户
    @DeleteMapping("/users/{id}")
    public String deleteUser(@PathVariable Long id) {
        users.removeIf(u -> u.getId().equals(id));
        return "User deleted successfully";
    }
}

3.2. 整体架构调整(推荐方案)

package com.example.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

public class NettyServer {
    // 监控指标(生产环境建议使用Prometheus等专业工具)
    private static int activeConnections = 0;

    public static void main(String[] args) {
        // 优化线程池配置
        EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("boss"));
        EventLoopGroup workerGroup = new NioEventLoopGroup(
                Runtime.getRuntime().availableProcessors() * 2,
                new DefaultThreadFactory("worker")
        );

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 内存池优化
                            pipeline.addLast(new ChannelTrafficShapingHandler(1024 * 1024, 1024 * 1024));
                            // HTTP协议处理
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(10 * 1024 * 1024));
                            // 超时控制(读超时60秒)
                            pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            // 监控处理器
                            pipeline.addLast(new ConnectionMonitorHandler());
                            // 业务逻辑处理器
                            pipeline.addLast(new BusinessHandler());
                            // 统一异常处理
                            pipeline.addLast(new GlobalExceptionHandler());
                        }
                    })
                    // 服务器参数优化
                    .option(ChannelOption.SO_BACKLOG, 65535)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
                            new WriteBufferWaterMark(8 * 1024, 32 * 1024))
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

            // 绑定端口并添加监听器
            ChannelFuture f = b.bind(8081)
                    .addListener((ChannelFutureListener) future -> {
                        if (future.isSuccess()) {
                            System.out.println("================服务启动成功 端口: 8081====================");
                            printSystemInfo();
                        } else {
                            System.err.println("端口绑定失败: " + future.cause().getMessage());
                            System.exit(1);
                        }
                    })
                    .sync();

            // 添加关闭钩子
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
                System.out.println("服务已优雅关闭");
            }));

            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    // 监控处理器
    @ChannelHandler.Sharable
    private static class ConnectionMonitorHandler extends ChannelDuplexHandler {
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            activeConnections++;
            ctx.fireChannelActive();
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) {
            activeConnections--;
            ctx.fireChannelInactive();
        }
    }

    // 全局异常处理
    @ChannelHandler.Sharable
    private static class GlobalExceptionHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            if (cause instanceof IOException && "Connection reset by peer".equals(cause.getMessage())) {
                System.out.println("客户端强制断开: " + ctx.channel().remoteAddress());
                ctx.close();
            } else {
                System.err.println("未处理异常: ");
                cause.printStackTrace();
                ctx.close();
            }
        }
    }

    // 系统信息打印
    private static void printSystemInfo() {
        System.out.println("当前配置参数:");
        System.out.println("CPU核心数: " + Runtime.getRuntime().availableProcessors());
        System.out.println("最大内存: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "MB");
        System.out.println("JVM参数: " + ManagementFactory.getRuntimeMXBean().getInputArguments());
    }
}

3.3 关键优化点

  • 异步非阻塞处理:所有IO操作在NIO线程完成,业务处理移交独立线程池
  • 连接管理优化
// 限制最大连接数
public class ConnectionLimiter extends ChannelInboundHandlerAdapter {
    private static final AtomicInteger connections = new AtomicInteger(0);
    private static final int MAX_CONN = 10000;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        if (connections.incrementAndGet() > MAX_CONN) {
            ctx.close();
            return;
        }
        // 正常处理
    }
}


协议优化:采用二进制协议(如Protobuf)替代JSON,降低序列化开销

四、Spring Boot整合方案(兼容现有服务)

4.1 混合部署模式

// 在Spring Boot中启动Netty
@SpringBootApplication
public class HybridApp {
    public static void main(String[] args) {
        SpringApplication.run(HybridApp.class, args);
        new NettyServer().start();  // 启动Netty服务
    }
}

// 配置不同的端口
server.port=8080   # Spring MVC端口
netty.port=8081    # Netty服务端口

4.2 服务分流策略

  • 将高频长连接请求(如即时消息、实时定位)路由到Netty服务
  • 保留Spring MVC处理RESTful短连接请求

五、补充优化措施

5.1 业务逻辑优化

-// 异步处理模板
public class AsyncProcessor {
    private static final Executor bizExecutor = Executors.newFixedThreadPool(
        Runtime.getRuntime().availableProcessors() * 2); // 独立业务线程池

    public void process(ChannelHandlerContext ctx, Object msg) {
        CompletableFuture.supplyAsync(() -> {
            // 业务处理逻辑
            return processBusiness(msg);
        }, bizExecutor).thenAcceptAsync(result -> {
            ctx.writeAndFlush(result);
        }, ctx.executor()); // 回到IO线程写响应
    }
}

5.2 监控配置

<!-- Netty自带监控 -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-monitor</artifactId>
    <version>${netty.version}</version>
</dependency>
// 连接数监控
public class ConnectionMonitor extends ChannelInboundHandlerAdapter {
    private static final Counter connections = Metrics.counter("netty.connections");

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        connections.increment();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        connections.decrement();
    }
}

六、实施建议

6.1 分阶段改造

先对压力最大的接口进行Netty改造

6.2 压力测试

使用wrk进行对比测试

# 测试命令示例
 ./wrk -t12 -c400 -d30s -T5s -s post_test.lua http://localhost:8081/api/users

6.3 监控指标

重点关注qps、cpu利用率、gc次数等核心指标

改造后预期效果(经验值):

  • 连接容量提升:从Tomcat默认200~500提升到10,000+
  • CPU利用率下降:相同压力下可降低30%-50%
  • 内存消耗:减少线程栈内存占用(每个线程约1MB)

建议先通过jstack分析当前线程状态,确认是否真的是线程数过多导致的问题,再针对性优化。同时要确保业务代码没有同步阻塞操作,必要时结合Arthas进行线上诊断。

希望这篇文章对你有所帮助!如果觉得不错,别忘了点赞收藏哦!

相关推荐

Python入门学习记录之一:变量_python怎么用变量

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

python变量命名规则——来自小白的总结

python是一个动态编译类编程语言,所以程序在运行前不需要如C语言的先行编译动作,因此也只有在程序运行过程中才能发现程序的问题。基于此,python的变量就有一定的命名规范。python作为当前热门...

Python入门学习教程:第 2 章 变量与数据类型

2.1什么是变量?在编程中,变量就像一个存放数据的容器,它可以存储各种信息,并且这些信息可以被读取和修改。想象一下,变量就如同我们生活中的盒子,你可以把东西放进去,也可以随时拿出来看看,甚至可以换成...

绘制学术论文中的“三线表”具体指导

在科研过程中,大家用到最多的可能就是“三线表”。“三线表”,一般主要由三条横线构成,当然在变量名栏里也可以拆分单元格,出现更多的线。更重要的是,“三线表”也是一种数据记录规范,以“三线表”形式记录的数...

Python基础语法知识--变量和数据类型

学习Python中的变量和数据类型至关重要,因为它们构成了Python编程的基石。以下是帮助您了解Python中的变量和数据类型的分步指南:1.变量:变量在Python中用于存储数据值。它们充...

一文搞懂 Python 中的所有标点符号

反引号`无任何作用。传说Python3中它被移除是因为和单引号字符'太相似。波浪号~(按位取反符号)~被称为取反或补码运算符。它放在我们想要取反的对象前面。如果放在一个整数n...

Python变量类型和运算符_python中变量的含义

别再被小名词坑哭了:Python新手常犯的那些隐蔽错误,我用同事的真实bug拆给你看我记得有一次和同事张姐一起追查一个看似随机崩溃的脚本,最后发现罪魁祸首竟然是她把变量命名成了list。说实话...

从零开始:深入剖析 Spring Boot3 中配置文件的加载顺序

在当今的互联网软件开发领域,SpringBoot无疑是最为热门和广泛应用的框架之一。它以其强大的功能、便捷的开发体验,极大地提升了开发效率,成为众多开发者构建Web应用程序的首选。而在Spr...

Python中下划线 ‘_’ 的用法,你知道几种

Python中下划线()是一个有特殊含义和用途的符号,它可以用来表示以下几种情况:1在解释器中,下划线(_)表示上一个表达式的值,可以用来进行快速计算或测试。例如:>>>2+...

解锁Shell编程:变量_shell $变量

引言:开启Shell编程大门Shell作为用户与Linux内核之间的桥梁,为我们提供了强大的命令行交互方式。它不仅能执行简单的文件操作、进程管理,还能通过编写脚本实现复杂的自动化任务。无论是...

一文学会Python的变量命名规则!_python的变量命名有哪些要求

目录1.变量的命名原则3.内置函数尽量不要做变量4.删除变量和垃圾回收机制5.结语1.变量的命名原则①由英文字母、_(下划线)、或中文开头②变量名称只能由英文字母、数字、下画线或中文字所组成。③英文字...

更可靠的Rust-语法篇-区分语句/表达式,略览if/loop/while/for

src/main.rs://函数定义fnadd(a:i32,b:i32)->i32{a+b//末尾表达式}fnmain(){leta:i3...

C++第五课:变量的命名规则_c++中变量的命名规则

变量的命名不是想怎么起就怎么起的,而是有一套固定的规则的。具体规则:1.名字要合法:变量名必须是由字母、数字或下划线组成。例如:a,a1,a_1。2.开头不能是数字。例如:可以a1,但不能起1a。3....

Rust编程-核心篇-不安全编程_rust安全性

Unsafe的必要性Rust的所有权系统和类型系统为我们提供了强大的安全保障,但在某些情况下,我们需要突破这些限制来:与C代码交互实现底层系统编程优化性能关键代码实现某些编译器无法验证的安全操作Rus...

探秘 Python 内存管理:背后的神奇机制

在编程的世界里,内存管理就如同幕后的精密操控者,确保程序的高效运行。Python作为一种广泛使用的编程语言,其内存管理机制既巧妙又复杂,为开发者们提供了便利的同时,也展现了强大的底层控制能力。一、P...