Java網絡編程性能優化

1.網絡編程性能優化基礎

1. 性能關鍵指標

指標

描述

優化目標

響應時間

從請求到響應的總時間

降低到毫秒級

吞吐量

單位時間內處理的請求數量

提高到每秒數千至數萬請求

并發用戶數

系統同時處理的用戶數量

支持數千至數萬并發連接

資源利用率

CPU、內存、網絡帶寬的使用率

保持在合理水平避免瓶頸

2. 性能瓶頸分析

? 網絡應用性能瓶頸層次

2.連接池優化

1. 連接池工作原理

2. HttpClient連接池示例

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;public class HttpClientConnectionPoolExample {private static CloseableHttpClient httpClient;static {// 創建連接池管理器PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();// 設置最大連接數
        cm.setMaxTotal(200);// 設置每個路由的默認連接數
        cm.setDefaultMaxPerRoute(20);// 創建HttpClient并配置連接池
        httpClient = HttpClients.custom().setConnectionManager(cm).evictIdleConnections(30, TimeUnit.SECONDS) // 空閑連接超時時間.build();}public static CloseableHttpResponse execute(HttpUriRequest request) throws IOException {return httpClient.execute(request);}public static void main(String[] args) throws IOException {HttpGet request = new HttpGet("https://example.com");try (CloseableHttpResponse response = execute(request)) {System.out.println("Status code: " + response.getStatusLine().getStatusCode());}}
}

3.異步編程優化

1. 同步與異步對比

? 同步處理流程

? 異步處理流程

2. CompletableFuture異步處理示例

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class AsyncHttpClientExample {private static final ExecutorService executor = Executors.newFixedThreadPool(10);private static final HttpClient client = HttpClient.newBuilder().executor(executor).build();public static CompletableFuture<String> fetchUrlAsync(String url) {HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();return client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(response -> {if (response.statusCode() == 200) {return response.body();} else {throw new RuntimeException("HTTP request failed: " + response.statusCode());}}).exceptionally(ex -> {System.err.println("Error fetching URL: " + ex.getMessage());return null;});}public static void main(String[] args) throws IOException, InterruptedException {// 異步獲取多個URLCompletableFuture<String> future1 = fetchUrlAsync("https://example.com");CompletableFuture<String> future2 = fetchUrlAsync("https://example.org");// 所有任務完成后執行CompletableFuture.allOf(future1, future2).thenRun(() -> {System.out.println("Both requests completed");System.out.println("Length of response 1: " + (future1.join() != null ? future1.join().length() : 0));System.out.println("Length of response 2: " + (future2.join() != null ? future2.join().length() : 0));
                    executor.shutdown();});// 主線程可以繼續執行其他任務System.out.println("Main thread continues...");Thread.sleep(2000);}
}

4.數據緩存優化

1. 緩存策略與位置

? 多級緩存架構

2. Caffeine本地緩存示例

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;import java.util.concurrent.TimeUnit;public class CaffeineCacheExample {private static final Cache<String, String> cache = Caffeine.newBuilder().maximumSize(1000)                  // 最大緩存條目數.expireAfterWrite(10, TimeUnit.MINUTES) // 寫入后過期時間.refreshAfterWrite(5, TimeUnit.MINUTES) // 寫入后刷新時間.build();public static String getData(String key) {// 嘗試從緩存獲取String value = cache.getIfPresent(key);if (value != null) {return value;}// 緩存未命中,從數據源獲取
        value = fetchFromDataSource(key);if (value != null) {
            cache.put(key, value);}return value;}private static String fetchFromDataSource(String key) {// 模擬從數據庫或其他數據源獲取數據System.out.println("Fetching data from data source for key: " + key);return "Data for " + key;}public static void main(String[] args) {System.out.println(getData("key1"));  // 第一次調用,從數據源獲取System.out.println(getData("key1"));  // 第二次調用,從緩存獲取System.out.println(getData("key2"));  // 新鍵,從數據源獲取}
}

5.零拷貝技術

1. 傳統數據傳輸流程

硬盤 --> 內核緩沖區 --> 用戶緩沖區 --> 內核套接字緩沖區 --> 網絡接口

2. 零拷貝數據傳輸流程

硬盤 --> 內核緩沖區 --> 網絡接口

3. Java零拷貝示例

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;public class ZeroCopyExample {public static void main(String[] args) {try (FileChannel fileChannel = new FileInputStream("large_file.dat").getChannel();SocketChannel socketChannel = SocketChannel.open()) {// 連接到服務器
            socketChannel.connect(new InetSocketAddress("example.com", 8080));// 使用transferTo實現零拷貝long transferred = 0;long size = fileChannel.size();while (transferred < size) {
                transferred += fileChannel.transferTo(transferred, size - transferred, socketChannel);}System.out.println("文件傳輸完成,總字節數: " + transferred);} catch (IOException e) {
            e.printStackTrace();}}
}

6.性能監控與調優

1. 關鍵監控指標

類別

指標

工具

系統

CPU 使用率、內存使用率

top, htop, jstat

網絡

帶寬利用率、連接數

iftop, netstat, ss

JVM

GC 頻率、堆內存使用

jstat, jmap, VisualVM

應用

請求響應時間、吞吐量

JMeter, Gatling, Prometheus

7.綜合優化示例

1. 優化后的HTTP服務器

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class OptimizedHttpServer {private static final int PORT = 8080;private static final int BUFFER_SIZE = 8192;private static final int THREAD_POOL_SIZE = 100;private final Selector selector;private final ServerSocketChannel serverChannel;private final ExecutorService threadPool;private final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE); // 直接內存緩沖區public OptimizedHttpServer() throws IOException {
        selector = Selector.open();
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(PORT));
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);        threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);System.out.println("服務器啟動,監聽端口: " + PORT);}public void start() {try {while (true) {
                selector.select();Iterator<SelectionKey> keys = selector.selectedKeys().iterator();while (keys.hasNext()) {SelectionKey key = keys.next();
                    keys.remove();if (key.isAcceptable()) {handleAccept(key);} else if (key.isReadable()) {handleRead(key);}}}} catch (IOException e) {
            e.printStackTrace();} finally {try {
                selector.close();
                serverChannel.close();
                threadPool.shutdown();} catch (IOException e) {
                e.printStackTrace();}}}private void handleAccept(SelectionKey key) throws IOException {ServerSocketChannel server = (ServerSocketChannel) key.channel();SocketChannel client = server.accept();
        client.configureBlocking(false);
        client.register(selector, SelectionKey.OP_READ);}private void handleRead(SelectionKey key) {SocketChannel client = (SocketChannel) key.channel();
        threadPool.submit(() -> {try {
                buffer.clear();int bytesRead = client.read(buffer);if (bytesRead == -1) {
                    client.close();return;}                buffer.flip();// 處理HTTP請求(實際應用中應該解析請求并生成響應)String response = "HTTP/1.1 200 OK\r\n" +"Content-Type: text/plain\r\n" +"Content-Length: 12\r\n" +"\r\n" +"Hello World!";ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes());while (responseBuffer.hasRemaining()) {
                    client.write(responseBuffer);}} catch (IOException e) {try {
                    client.close();} catch (IOException ex) {
                    ex.printStackTrace();}}});}public static void main(String[] args) {try {OptimizedHttpServer server = new OptimizedHttpServer();
            server.start();} catch (IOException e) {
            e.printStackTrace();}}
}

8.優化總結

技術

適用場景

性能提升點

連接池

頻繁創建和銷毀連接的場景

減少連接創建開銷

異步編程

I/O 密集型應用

提高線程利用率

數據緩存

數據讀取頻繁且變化不頻繁的場景

減少數據獲取時間

零拷貝

大文件傳輸或數據復制場景

減少 CPU 和內存開銷

直接內存

頻繁進行內存分配和釋放的場景

減少 GC 壓力

通過合理組合使用這些優化技術,可以顯著提高Java網絡應用的響應速度和吞吐量,更好地應對高并發場景。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/84660.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/84660.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/84660.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

react native搭建項目

React Native 項目搭建指南 React Native 是一個使用 JavaScript 和 React 構建跨平臺移動應用的框架。以下是搭建 React Native 項目的詳細步驟&#xff1a; 1. 環境準備 安裝 Node.js 下載并安裝 Node.js (推薦 LTS 版本) 安裝 Java Development Kit (JDK) 對于 Androi…

Redis 容器啟動失敗Fatal error loading the DB, check server logs. Exiting.的解決方法

? 問題分析&#xff1a;Redis 容器啟動失敗 根據提供的 Redis 啟動日志&#xff0c;關鍵信息如下&#xff1a; &#x1f50d; 模塊加載情況 模塊名稱狀態備注RedisCompat? 成功search? 成功RediSearch 模塊timeseries? 成功RedisTimeSeries 模塊ReJSON? 成功bf? 成功R…

chrome打不開axure設計的軟件產品原型問題解決辦法

1、打開原型文件夾&#xff0c;進入到其中的如下目錄中&#xff1a;resources->chrome->axure-chrome-extension.crx&#xff0c;找到 Axure RP Extension for Chrome插件。 2、axure-chrome-extension.crx文件修改擴展名.rar&#xff0c;并解壓到文件夾 axure-chrome-ex…

Java 各版本核心新特性的詳細說明

一、Java 8&#xff08;2014&#xff09;—— 函數式編程的里程碑 1. Lambda 表達式 作用&#xff1a;簡化匿名內部類&#xff0c;支持函數式編程。示例&#xff1a;// 傳統匿名內部類 Runnable r1 new Runnable() {Overridepublic void run() {System.out.println("He…

【md2html python 將 Markdown 文本轉換為 HTML】

測試md文本 md_text """ # title## subtitle\python print("Hello, World!") \- item 1| Header 1 | Header 2 | |----------|----------| | Row 1 Col 1 | Row 1 Col 2 |- item 2> This is a blockquote.### SubsubtitleThis is a paragraph wi…

Prompt Engineering 提示工程介紹與使用/調試技巧

1. 介紹 Prompt Engineering 是一種人工智能&#xff08;AI&#xff09;技術&#xff0c;它通過設計和改進 AI 的 prompt 來提高 AI 的表現。Prompt Engineering 的目標是創建高度有效和可控的 AI 系統&#xff0c;使其能夠準確、可靠地執行特定任務。 如果你從來沒有使用過Pr…

如何把 Microsoft Word 中所有的漢字字體替換為宋體?

Ctrl H &#xff0c;然后&#xff0c;點擊更多&#xff0c;勾選使用通配符&#xff0c;查找內容中填入 [一-龥]{1,}&#xff0c; 這是 Word 通配符匹配漢字的經典寫法&#xff08;匹配 Unicode 范圍內的 CJK 漢字&#xff09;。 然后&#xff0c; “替換為”留空&#xff0c;點…

CMake從入門到實戰:現代C++項目構建指南

CMake從入門到實戰&#xff1a;現代C項目構建指南 引言 在跨平臺開發成為主流的今天&#xff0c;CMake作為開源構建系統的標桿工具&#xff0c;憑借其跨平臺性、靈活性和可擴展性&#xff0c;已成為C/C項目的事實標準。本文將帶你系統掌握CMake的核心機制&#xff0c;通過實戰…

Web安全滲透之長城杯奪旗賽

Web-Git flag1 掃描WEB目錄發現存在Git泄露&#xff08;這里是隊友掃的&#xff0c;我這圖是拿的我后面掃的截圖&#xff0c;所以時間對不上。 使用GitHub - gakki429/Git_Extract: 提取遠程 git 泄露或本地 git 的工具拉取泄露代碼。 讀取到flag&#xff0c;全場一血捏。…

機器學習與深度學習:區別與聯系

機器學習與深度學習&#xff1a;區別與聯系 在人工智能領域&#xff0c;機器學習和深度學習是兩個最熱門的概念&#xff0c;它們既相互關聯又有所區別。本文將深入探討這兩者的核心差異與內在聯系&#xff0c;幫助讀者更好地理解它們在實際應用中的定位。 一、基本概念 **機…

Linux TCP與Socket與IO多路復用(Epoll)

目錄 一、背景 二、交互流程 2.1 數據流動 2.2 對象之間的關系 三、TCP 3.1 為什么需要三次握手 3.2 三次握手流程 3.3 三次握手后的產物 3.4 TCB 四、Socket 4.1 Java Socket和C Socket 4.2 Socket的本質 4.3 Socket和TCB的關系 4.4 通過文件描述符調用Socket的…

字節跳動旗下火山引擎都覆蓋哪些領域

首先&#xff0c;我需要確認火山引擎的主要業務范圍。根據之前的資料&#xff0c;火山引擎是字節跳動的企業技術服務平臺&#xff0c;可能包括云服務、人工智能、大數據分析等。不過需要更詳細的信息&#xff0c;比如具體的產品和服務&#xff0c;覆蓋的行業等。 接下來&#x…

如何配置jmeter做分布式壓測

問&#xff1a;為何需要做分布式 答&#xff1a;當我們本地機器jmeter進行壓測時&#xff0c;單臺JMeter機器通常無法穩定生成2000 QPS&#xff08;受限于CPU、內存、網絡帶寬&#xff09;&#xff0c;本地端口耗盡&#xff1a;操作系統可用的臨時端口&#xff08;Ephemeral P…

【算法提升】牛牛沖鉆五 最長無重復子數組 重排字符串 one_day

算法提升 1.牛牛沖鉆五1.2 解析 2.最長無重復子數組2.1解析 3.重排字符串3.1解析 1.牛牛沖鉆五 1.2 解析 后面的數據要根據前面兩個的狀態來確定&#xff0c;我的做法是使用動態規劃的方式 #include<iostream> #include<string> #include<vector> using n…

數學建模MathAI智能體-2025電工杯A題實戰

題目&#xff1a; 光伏電站發電功率日前預測問題 光伏發電是通過半導體材料的光電效應&#xff0c;將太陽能直接轉化為電能的技術。光伏電站是由眾多光伏發電單元組成的規模化發電設施。 光伏電站的發電功率主要由光伏板表面接收到的太陽輻射總量決定&#xff0c;不同季節太陽…

VR 展廳開啟一場穿越時空的邂逅?

在文化藝術領域&#xff0c;VR 展廳宛如一扇通往奇妙世界的大門&#xff0c;讓觀眾得以突破時間與空間的枷鎖&#xff0c;以一種前所未有的沉浸式體驗&#xff0c;與歷史文化和藝術作品展開親密無間的互動。博物館&#xff0c;作為承載著厚重歷史文化的璀璨寶庫&#xff0c;長久…

linux中使用make clean重新編譯

是的&#xff0c;在編譯完成后&#xff0c;你可以通過以下方式清除之前的編譯結果并重新編譯&#xff1a; 方法 1&#xff1a;直接刪除 build 目錄&#xff08;推薦&#xff09; 這是最徹底的清理方式&#xff0c;適用于需要完全重新配置或解決構建問題的情況。 # 進入項目根…

【Linux】的火墻管理及優化

目錄 iptables與firewalld服務 iptables的三表五鏈 iptables的安裝和啟用 iptables命令的格式及常用參數 命令格式 常用參數 編寫規則示例 firewalld的域 firewalld的啟用 firewalld-cmd命令的常用參數 firewalld的高級規則 firewalld的地址偽裝與端口轉發 iptable…

古文時空重構:當AI把課本詩詞做成4D電影

當青銅編鐘聲由遠及近&#xff0c;AI生成的水墨粒子逐漸凝聚成標題 當苔痕在石階上悄然蔓延時&#xff0c;你聽見劉禹錫筆下的呼吸了嗎&#xff1f; 當鏡頭突然穿透墨跡&#xff0c;3D古卷如星河鋪展&#xff01; 當AI把課本詩詞做成4D電影&#xff0c;這樣的視頻流量會不會高…

自動生成圖標小程序(iOS)

續上篇《iOS應用程序開發(圖片處理器&#xff09;》 這是一個圖片瀏覽器和處理器&#xff0c;增加一些功能&#xff0c;可以自動生成小圖標。 (This is a picture viewer and editor.You can add some functions,generate the icon automatically.You can select the object …