您的位置:首頁技術文章
文章詳情頁

asp.net core服務限制堆內存大小的操作方法

瀏覽:222日期:2022-06-08 18:04:38
目錄
  • 前言
  • 1、asp.net core是什么
  • 2、限制其堆內存最大大小
    • 2.1 設置.NET 運行時的配置
    • 2.2 在項目中創建runtimeconfig.json配置文件
    • 2.2 限制堆的大小
  • 3、測試配置是否生效
    • 4、在docker容器中限制堆內存大小

      前言

      在我們眾多的微服務項目中,都有限制其堆內存大小的需求,以免占用宿主機內存過高。

      在java中我們可以通過jvm參數來很好的控制堆內存以及其他參數。

      但是在asp.net core的web服務中,我們該如何去限制堆內存大小呢?

      提示:以下是本篇文章正文內容,下面案例可供參考

      1、asp.net core是什么

      微軟旗下支持跨平臺的開發框架,與springboot思想類似,支持ioc等,可以快速的開發web api等項目
      官方文檔:https://learn.microsoft.com/zh-cn/aspnet/core/introduction-to-aspnet-core?view=aspnetcore-6.0

      2、限制其堆內存最大大小

      建議熟讀官方文檔:https://learn.microsoft.com/zh-cn/dotnet/core/runtime-config/

      2.1 設置.NET 運行時的配置

      官網文檔:https://learn.microsoft.com/zh-cn/dotnet/core/runtime-config/#runtimeconfigjson

      .NET 提供了以下機制用于配置 .NET 運行時的行為:

      • runtimeconfig.json 文件
      • MSBuild 屬性
      • 環境變量

      通過使用環境變量來配置某個選項會將設置應用于所有的 .NET 應用。 在 runtimeconfig.json 或項目文件中配置某個選項則只會將設置應用于該應用程序。

      選擇 runtimeconfig.json文件作為.net運行時的配置文件。

      2.2 在項目中創建runtimeconfig.json配置文件

      構建項目時,將在打包的輸出目錄中生成 [appname].runtimeconfig.json 文件。

      如果項目文件所在的文件夾中存在 runtimeconfig.template.json 文件,它包含的任何配置選項都將插入到 [appname].runtimeconfig.json 文件中。

      如果自行構建應用,請將所有配置選項放在 runtimeconfig.template.json 文件中。 如果只是運行應用,請將其直接插入 [appname].runtimeconfig.template.json 文件中。

      2.2 限制堆的大小

      • 指定 GC 堆和 GC 簿記的最大提交大?。ㄒ宰止潪閱挝唬?/li>
      • 此設置僅適用于 64 位計算機。
      • 如果已配置每對象堆限制,則忽略此設置。
      • 默認值(僅在某些情況下適用)是 20 MB 或容器內存限制的 75%(以較大者為準)。 此默認值在以下情況下適用:
      • 進程正在具有指定內存限制的容器中運行。
      • HeapHardLimitPercent 未設置。

      示例:限制堆內存最大為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++)    {// 1mbbyte[] bytes = new byte[1024 * 1024];bytesList.Add(bytes);    }    Console.WriteLine("當前堆內存大小 -- " + GC.GetTotalMemory(false) / 1024 / 1024.0 + " MB");}    }}

      結果,可見配置生效,達到1g時報錯 System.OutOfMemoryException,然后系統強行gc,服務down,配置docker-compose的自動重啟即可完成gc后自動重啟

      當前堆內存大小 -- 102.0029296875 MB當前堆內存大小 -- 202.013671875 MB當前堆內存大小 -- 302.0166015625 MB當前堆內存大小 -- 402.0126953125 MB當前堆內存大小 -- 502.0166015625 MB當前堆內存大小 -- 602.02734375 MB當前堆內存大小 -- 702.044921875 MB當前堆內存大小 -- 802.046875 MB當前堆內存大小 -- 902.0498046875 MBinfo: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]      Executed action office_conver_server.Controllers.TestController.testMemory (office-conver-server) in 5924.7612msinfo: 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, Object[] 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 state, 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容器中限制堆內存大小

      可以采用上述配置,但是缺點就是不靈活,需要頻繁更新代碼,更新容器。。。

      添加容器環境變量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:      # 堆內存最大限制【十六進制】      DOTNET_GCHeapHardLimit: "40000000"      TZ: Asia/Shanghai   # deploy:     #  resources:      #   limits:       #    memory: 1G    restart: always    security_opt:      - seccomp:unconfined

      到此這篇關于asp.net core服務限制堆內存大小的文章就介紹到這了,更多相關asp.net core堆內存大小內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!

      標簽: ASP.NET
      国产综合久久一区二区三区