asp.net core服務限制堆內(nèi)存大小的操作方法
前言
在我們眾多的微服務項目中,都有限制其堆內(nèi)存大小的需求,以免占用宿主機內(nèi)存過高。
在java中我們可以通過jvm參數(shù)來很好的控制堆內(nèi)存以及其他參數(shù)。
但是在asp.net core的web服務中,我們該如何去限制堆內(nèi)存大小呢?
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
1、asp.net core是什么
微軟旗下支持跨平臺的開發(fā)框架,與springboot思想類似,支持ioc等,可以快速的開發(fā)web api等項目
官方文檔:https://learn.microsoft.com/zh-cn/aspnet/core/introduction-to-aspnet-core?view=aspnetcore-6.0
2、限制其堆內(nèi)存最大大小
建議熟讀官方文檔:https://learn.microsoft.com/zh-cn/dotnet/core/runtime-config/
2.1 設置.NET 運行時的配置
官網(wǎng)文檔:https://learn.microsoft.com/zh-cn/dotnet/core/runtime-config/#runtimeconfigjson
.NET 提供了以下機制用于配置 .NET 運行時的行為:
- runtimeconfig.json 文件
- MSBuild 屬性
- 環(huán)境變量
通過使用環(huán)境變量來配置某個選項會將設置應用于所有的 .NET 應用。 在 runtimeconfig.json 或項目文件中配置某個選項則只會將設置應用于該應用程序。
選擇 runtimeconfig.json文件作為.net運行時的配置文件。
2.2 在項目中創(chuàng)建runtimeconfig.json配置文件
構(gòu)建項目時,將在打包的輸出目錄中生成 [appname].runtimeconfig.json 文件。
如果項目文件所在的文件夾中存在 runtimeconfig.template.json 文件,它包含的任何配置選項都將插入到 [appname].runtimeconfig.json 文件中。
如果自行構(gòu)建應用,請將所有配置選項放在 runtimeconfig.template.json 文件中。 如果只是運行應用,請將其直接插入 [appname].runtimeconfig.template.json 文件中。

2.2 限制堆的大小
- 指定 GC 堆和 GC 簿記的最大提交大?。ㄒ宰止?jié)為單位)。
- 此設置僅適用于 64 位計算機。
- 如果已配置每對象堆限制,則忽略此設置。
- 默認值(僅在某些情況下適用)是 20 MB 或容器內(nèi)存限制的 75%(以較大者為準)。 此默認值在以下情況下適用:
- 進程正在具有指定內(nèi)存限制的容器中運行。
- HeapHardLimitPercent 未設置。
示例:限制堆內(nèi)存最大為1G
{
"configProperties": {
"System.GC.HeapHardLimit": 1073741824
}
}
3、測試配置是否生效
測試控制器:
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public void testMemory()
{
List<byte[]> bytesList = new List<byte[]>();
while (true)
{
Console.ReadKey();
// 100m
for (int i = 0; i < 100; i++)
{
// 1mb
byte[] bytes = new byte[1024 * 1024];
bytesList.Add(bytes);
}
Console.WriteLine("當前堆內(nèi)存大小 -- " + GC.GetTotalMemory(false) / 1024 / 1024.0 + " MB");
}
}
}
結(jié)果,可見配置生效,達到1g時報錯 System.OutOfMemoryException,然后系統(tǒng)強行g(shù)c,服務down,配置docker-compose的自動重啟即可完成gc后自動重啟
當前堆內(nèi)存大小 -- 102.0029296875 MB
當前堆內(nèi)存大小 -- 202.013671875 MB
當前堆內(nèi)存大小 -- 302.0166015625 MB
當前堆內(nèi)存大小 -- 402.0126953125 MB
當前堆內(nèi)存大小 -- 502.0166015625 MB
當前堆內(nèi)存大小 -- 602.02734375 MB
當前堆內(nèi)存大小 -- 702.044921875 MB
當前堆內(nèi)存大小 -- 802.046875 MB
當前堆內(nèi)存大小 -- 902.0498046875 MB
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action office_conver_server.Controllers.TestController.testMemory (office-conver-server) in 5924.7612ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'office_conver_server.Controllers.TestController.testMemory (office-conver-server)'
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at office_conver_server.Controllers.TestController.testMemory() in D:\BaiduSyncdisk\項目目錄\ItemProjects\dotnet\office-conver-server\Controllers\TestController.cs:line 49
at Microsoft.Extensions.Internal.ObjectMethodExecutor.<>c__DisplayClass33_0.<WrapVoidMethod>b__0(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.VoidResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Obje
ct[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object sta
te, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
4、在docker容器中限制堆內(nèi)存大小
可以采用上述配置,但是缺點就是不靈活,需要頻繁更新代碼,更新容器。。。
添加容器環(huán)境變量DOTNET_GCHeapHardLimit: "value"
注意value是十六進制
version: "3"
services:
officeConverServer:
image: l-4.1-office-conver-server:test
ports:
- 8079:80
volumes:
- ./uploadFile:/uploadFile
#- ./office-conver-server.runtimeconfig.json:/app/office-conver-server.runtimeconfig.json
- ./appsettings.json:/app/appsettings.json
environment:
# 堆內(nèi)存最大限制【十六進制】
DOTNET_GCHeapHardLimit: "40000000"
TZ: Asia/Shanghai
# deploy:
# resources:
# limits:
# memory: 1G
restart: always
security_opt:
- seccomp:unconfined到此這篇關(guān)于asp.net core服務限制堆內(nèi)存大小的文章就介紹到這了,更多相關(guān)asp.net core堆內(nèi)存大小內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
.Net?Core3.0?WebApi?項目框架搭建之使用Serilog替換掉Log4j
Serilog 是一個用于.NET應用程序的日志記錄開源庫,配置簡單,接口干凈,并可運行在最新的.NET平臺上,這篇文章主要介紹了.Net?Core3.0?WebApi?項目框架搭建之使用Serilog替換掉Log4j,需要的朋友可以參考下2022-02-02
asp.net(C#)生成Code39條形碼實例 條碼槍可以掃描出
這篇文章主要介紹了asp.net(C#)生成Code39條形碼實例 條碼槍可以掃描出。需要的朋友可以過來參考下,希望對大家有所幫助2014-02-02
MVC4制作網(wǎng)站教程第三章 刪除用戶組操作3.4
這篇文章主要為大家詳細介紹了MVC4制作網(wǎng)站教程,刪除用戶組功能的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-08-08
asp.net(c#)有關(guān) Session 操作的幾個誤區(qū)
asp.net(c#)有關(guān) Session 操作的幾個誤區(qū)...2007-06-06
asp.net為網(wǎng)頁動態(tài)添加關(guān)鍵詞的方法
這篇文章主要介紹了asp.net為網(wǎng)頁動態(tài)添加關(guān)鍵詞的方法,可實現(xiàn)動態(tài)添加keyword meta的功能,非常具有實用價值,需要的朋友可以參考下2015-04-04
ASP.NET中實現(xiàn)把form表單元素轉(zhuǎn)為實體對象或集合
這篇文章主要介紹了ASP.NET中實現(xiàn)把form表單元素轉(zhuǎn)為實體對象或集合,本文又是一個對重復數(shù)據(jù)處理的一個封裝,非常實用的開發(fā)技巧,需要的朋友可以參考下2015-06-06

