天天看點

15分鐘從零開始搭建支援10w+使用者的生産環境(四)

上一篇文章,介紹了這個架構中,WebServer的選擇,以及整個架構中擴充時的思路。

原文位址:15分鐘從零開始搭建支援10w+使用者的生産環境(三)

五、架構實踐

前邊用了三篇文章,詳細介紹了這個架構的各個部分的選擇以及安裝。

這篇文章,我會用一個Demo項目,從開發到部署,包括MongoDB資料的通路。用這種方式過一遍這個架構。

Demo項目,我們用Dotnet Core開發。我們選擇最新版的Dotnet Core 3.1做為系統的主架構。

開發環境用MacOS + VS Code,生産環境用雲伺服器。

第一步:環境檢查和搭建

  1. 先看看各個環境的版本情況

生産環境:

$ cat /proc/version
Linux version 4.9.0-12-amd64 ([email protected]) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ) #1 SMP Debian 4.9.210-1 (2020-01-20)

$ lsb_release -a
No LSB modules are available.
Distributor ID:    Debian
Description:    Debian GNU/Linux 9.12 (stretch)
Release:    9.12
Codename:    stretch
           

開發環境:

$ cat /System/Library/CoreServices/SystemVersion.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>ProductBuildVersion</key>
    <string>19E287</string>
    <key>ProductCopyright</key>
    <string>1983-2020 Apple Inc.</string>
    <key>ProductName</key>
    <string>Mac OS X</string>
    <key>ProductUserVisibleVersion</key>
    <string>10.15.4</string>
    <key>ProductVersion</key>
    <string>10.15.4</string>
    <key>iOSSupportVersion</key>
    <string>13.4</string>
</dict>
</plist>
           
  1. 安裝Dotnet Core 3.1

Dotnet Core官方下載下傳位址:https://aka.ms/dotnet-download

Mac上邊是以前裝好的,看一下:

$ dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.201
 Commit:    b1768b4ae7

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.15
 OS Platform: Darwin
 RID:         osx.10.15-x64
 Base Path:   /usr/local/share/dotnet/sdk/3.1.201/

Host (useful for support):
  Version: 3.1.3
  Commit:  4a9f85e9f8

.NET Core SDKs installed:
  3.1.201 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.App 3.1.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 3.1.3 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
           

生産環境上邊,安裝步驟如下:

$ wget -O- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.asc.gpg
$ sudo mv microsoft.asc.gpg /etc/apt/trusted.gpg.d/
$ wget https://packages.microsoft.com/config/debian/9/prod.list
$ sudo mv prod.list /etc/apt/sources.list.d/microsoft-prod.list
$ sudo chown root:root /etc/apt/trusted.gpg.d/microsoft.asc.gpg
$ sudo chown root:root /etc/apt/sources.list.d/microsoft-prod.list
$ sudo apt-get update
$ sudo apt-get install apt-transport-https
$ sudo apt-get update
$ sudo apt-get install dotnet-sdk-3.1
           

安裝很簡單,這要感謝Microsoft,沒有誤導,也不需要刨坑。

安裝完檢查一下:

$ dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.201
 Commit:    b1768b4ae7

Runtime Environment:
 OS Name:     debian
 OS Version:  9
 OS Platform: Linux
 RID:         debian.9-x64
 Base Path:   /usr/share/dotnet/sdk/3.1.201/

Host (useful for support):
  Version: 3.1.3
  Commit:  4a9f85e9f8

.NET Core SDKs installed:
  3.1.201 [/usr/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.App 3.1.3 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 3.1.3 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
           

指令寫順手了,沒有分SDK和Runtime,正常應用時,生産環境可以隻裝Runtime。指令是在最後裝Dotnet的一步,用以下指令:

$ sudo apt-get install aspnetcore-runtime-3.1
$ sudo apt-get install dotnet-runtime-3.1
           
  1. 生産環境安裝MongoDB

詳細步驟參見:15分鐘從零開始搭建支援10w+使用者的生産環境(二)

  1. 生産環境安裝Jexus

詳細步驟參見:15分鐘從零開始搭建支援10w+使用者的生産環境(三)

第二步:開發環境建立Demo項目

  1. 找個目錄,建立解決方案(這一步不是必須,不過我習慣這麼做。總要有個解決方案來存放工程):
% dotnet new sln -o demo
The template "Solution File" was created successfully.
           

這一步完成後,會在目前目錄建立一個新目錄demo,同時,在demo目錄下建立檔案demo.sln。

  1. 在demo目錄下,建立工程:
% dotnet new webapi -o demo
The template "ASP.NET Core Web API" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on demo/demo.csproj...
  Restore completed in 16.79 ms for /demo/demo/demo.csproj.

Restore succeeded.
           
  1. 把建立的工程加到解決方案中:
% dotnet sln add demo/demo.csproj 
Project `demo/demo.csproj` added to the solution.
           
  1. 檢查一下現在的目錄和檔案結構:

其中有一個WeatherForecast,包含兩個檔案:WeatherForecast.cs和WeatherForecastController.cs,是建立工程時自帶的示範類。

現在我們運作一下工程。可以用VSC的「運作」,也可以指令行:

% dotnet run
           

運作Demo工程。

運作後,從浏覽器通路:http://localhost:5000/WeatherForecast,會得到一串示範資料。這就是上面這個示範類的效果。

正式項目中,這兩個檔案要删掉。

到這一步,基礎工程就搭好了。

我們要做一個API服務,這個服務裡要有幾個API,要用到資料庫通路。為了測試API,我們需要裝個Swagger。當然用Postman也可以,不過我習慣用Swagger。

  1. 增加Swagger包引用。在demo.csproj的同級目錄下運作:
% dotnet add package Swashbuckle.AspNetCore
           

Swagger裝好後,需要在Startup.cs中注冊。

在ConfigureServices中加入以下代碼:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "V1" });
});
           

在Configure中加入以下代碼:

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
           

完成後,Startup.cs的代碼:

namespace demo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "V1" });
            });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
           
  1. 增加MongoDB支援

選擇一:引用官方包MongoDB.Driver:

% dotnet add package MongoDB.Driver
           

後面用包提供的SDK進行開發。

選擇二:引用包Lib.Core.Mongodb.Helper:

% dotnet add package Lib.Core.Mongodb.Helper
           

這是我自己維護的一個Helper開源包,對官方的MongoDB.Driver做了一定程式的包裝和簡化操作。這個包目前在我公司的生産環境中用着。

這個包的開源位址:https://github.com/humornif/Lib.Core.Mongodb.Helper

引用完成後,需要在appsettings.json中增加資料庫連接配接串:

"MongoConnection": "mongodb://localhost:27017/admin?wtimeoutMS=2000"
           

完成後,appsettings.json的代碼如下:

{
  "MongoConnection": "mongodb://localhost:27017/admin?wtimeoutMS=2000",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
           
  1. 建立資料庫操作類

在工程中建立一個目錄Models,在目錄下建立一個類檔案Demo.cs:

using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace demo.Models
{
    public class Demo
    {
        public const string DATABASE = "DemoDB";
        public const string COLLECTION = "DemoCollection";

        public ObjectId _id { get; set; }
        public string demo_user_name { get; set; }
        public int demo_user_age { get; set; }
    }
}
           

在同一目錄下,再建立另一個Dto類DemoDto.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace demo.Models
{
    public class DemoDto
    {
        public string demo_user_name { get; set; }
        public int demo_user_age { get; set; }
    }
}
           

在工程中建立另一個目錄DBContext,在目錄下建立一個對應Demo類的資料庫操作類DemoDBContext.cs:

using demo.Models;
using Lib.Core.Mongodb.Helper;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace demo.DBContext
{
    public class DemoDBContext : MongoHelper<Demo>
    {
        //建立資料庫操作索引
        protected override async Task CreateIndexAsync()
        {
        }
        public DemoDBContext() : base(Demo.DATABASE, Demo.COLLECTION)
        {

        }

        //儲存資料到資料庫
        internal async Task<bool> saveData(DemoDto data)
        {
            Demo new_item = new Demo()
            {
                _id = ObjectId.GenerateNewId(),
                demo_user_name = data.demo_user_name,
                demo_user_age = data.demo_user_age,
            };

            bool result = await CreateAsync(new_item);
            return result;
        }

        //從資料庫查詢全部資料
        internal async Task<IEnumerable<DemoDto>> getAllData()
        {
            var fetch_data = await SelectAllAsync();

            List<DemoDto> result_list = new List<DemoDto>();
            fetch_data.ForEach(p =>
            {
                DemoDto new_item = new DemoDto()
                {
                    demo_user_name = p.demo_user_name,
                    demo_user_age = p.demo_user_age,
                };
                result_list.Add(new_item);
            });
            return result_list;
        }
    }
}
           

這三個類的關系是:

  • Demo類是資料類,對應MongoDB資料庫中儲存的資料。Demo.DATABASE是資料庫中的DB名稱,Demo.COLLECTION是資料庫中的Collection名稱。這個類決定資料在資料庫中的儲存位置和儲存内容。
  • DemoDta是Dta的映射類,在正式使用時,可以用AutoMap與Demo關聯。在這個Demo中,我用它來做資料從前端到API的傳遞。
  • DemoDBContext是對Demo結構資料的資料庫操作。這個類派生自Lib.Core.MongoDB.Helper中的父類MongoHelper。所有對Demo資料的操作全在這個類中進行。
  1. 建立API控制器

在Controller目錄中,建立DemoController.cs:

using demo.DBContext;
using demo.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace demo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DemoController : ControllerBase
    {
        [HttpPost]
        [Route("savedata")]
        public ActionResult<string> saveData(DemoDto data)
        {
            DemoDBContext dc = new DemoDBContext();
            bool result = dc.saveData(data).GetAwaiter().GetResult();

            if(result)
                return "OK";
            return "ERROR";
        }

        [HttpGet]
        [Route("getdata")]
        public IEnumerable<DemoDto> getData()
        {
            DemoDBContext dc = new DemoDBContext();
            return dc.getAllData().GetAwaiter().GetResult();
        }
    }
}
           

在這個控制器中,做了兩個API:

  • 基于POST的savedata,用來寫入資料到資料庫;
  • 基于GET的getdata,用來從資料庫讀取資料到前端。

資料庫的操作,調用了DemoDBContext中寫好的兩個資料庫操作方法。

資料庫操作的完整方法,可以參見https://github.com/humornif/Lib.Core.Mongodb.Helper的詳細說明。

  1. 檢查一下現在的工程目錄結構:
15分鐘從零開始搭建支援10w+使用者的生産環境(四)
  1. 測試運作

在VSC中點選運作,或者指令行輸入:

% dotnet run
           

等程式加載完成,可以通路http://localhost:5000/swagger,進行通路,并測試兩個API。

第三步:釋出到生産環境

  1. 釋出應用

前邊說了,開發環境是MAC,生産環境是Debian 9 x64,是以會涉及到一個跨平台的釋出。

事實上,跨平台釋出也很簡單。這個應用的目的環境是Linux-64,是以,釋出指令是:

% dotnet publish -r linux-x64
           

釋出完成後,系統會顯示釋出的目錄。這個項目,釋出目錄在demo/bin/Debug/netcoreapp3.1/linux-x64/publish。

  1. 打包傳到伺服器,并解包到一個目錄。在這個示範中,我解包到了伺服器的/var/demo。
  2. 在伺服器Jexus中配置網站。

在/usr/jexus/siteconf中建立網站配置檔案demo.80(檔案名可以随便起,我的習慣是網站名稱+端口号):

######################
# Web Site: DEMO
########################################

port=80
root=/ /var/demo
hosts=*    #OR your.com,*.your.com

# User=www-data

# AspNet.Workers=2  # Set the number of asp.net worker processes. Defauit is 1.

# addr=0.0.0.0
# CheckQuery=false
NoLog=true

AppHost={cmd=dotnet demo.dll; root=/var/demo; port=5000}

# NoFile=/index.aspx
# Keep_Alive=false
# UseGZIP=false

# UseHttps=true
# ssl.certificate=/x/xxx.crt  #or pem
# ssl.certificatekey=/x/xxx.key
# ssl.protocol=TLSv1.0 TLSv1.1 TLSv1.2
# ssl.ciphers=ECDHE-RSA-AES256-GCM-SHA384:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE 

# DenyFrom=192.168.0.233, 192.168.1.*, 192.168.2.0/24
# AllowFrom=192.168.*.*
# DenyDirs=~/cgi, ~/upfiles
# indexes=myindex.aspx

# Deny asp ...
rewrite=^/.+?\.(asp|cgi|pl|sh|bash|dll)(\?.*|)$  /.deny->$1
rewrite=.*/editor/.+                             /.deny->editor
# reproxy=/bbs/ http://192.168.1.112/bbs/
# host.Redirect=abc.com www.abc.com  301
# ResponseHandler.Add=myKey:myValue
ResponseHandler.Add=X-Frame-Options:SAMEORIGIN

# Jexus php fastcgi address is '/var/run/jexus/phpsvr'
#######################################################
# fastcgi.add=php|socket:/var/run/jexus/phpsvr

# php-fpm listen address is '127.0.0.1:9000'
############################################
# fastcgi.add=php|tcp:127.0.0.1:9000
           

在這個示範項目裡,起作用的配置其實就一行:

AppHost={cmd=dotnet demo.dll; root=/var/demo; port=5000}
           

這一行配置了三件事:

  • 應用的運作指令是:dotnet demo.dll
  • 應用的運作目錄是:/var/demo
  • 應用的運作端口是:5000

這樣配置就完成了。

接下來,啟動網站,在/usr/jexus中運作:

$ sudo ./jws start
           

網站就啟動起來了。

第四步:測試

在本地浏覽器中,輸入:http://server_ip/swagger,跟在開發環境測試效果完全一樣,可以進行資料庫的寫入和讀取操作。

Done !!!

我把上面的代碼,傳到了Github上,需要了可以拉下來直接使用。

代碼位址:https://github.com/humornif/Demo-Code/tree/master/0005/demo

15分鐘從零開始搭建支援10w+使用者的生産環境(四)

微信公衆号:老王Plus

掃描二維碼,關注個人公衆号,可以第一時間得到最新的個人文章和内容推送

本文版權歸作者所有,轉載請保留此聲明和原文連結

繼續閱讀