上一篇文章,介紹了這個架構中,WebServer的選擇,以及整個架構中擴展時的思路。
五、架構實踐
前邊用了三篇文章,詳細介紹了這個架構的各個部分的選擇以及安裝。
這篇文章,我會用一個Demo項目,從開發到部署,包括MongoDB數據的訪問。用這種方式過一遍這個架構。
Demo項目,我們用Dotnet Core開發。我們選擇最新版的Dotnet Core 3.1做為系統的主框架。
開發環境用MacOS + VS Code,生產環境用雲服務器。
第一步:環境檢查和搭建
- 先看看各個環境的版本情況
生產環境:
$ cat /proc/version
Linux version 4.9.0-12-amd64 (debian-kernel@lists.debian.org) (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>
- 安裝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
- 生產環境安裝MongoDB
詳細步驟參見:15分鍾從零開始搭建支持10w+用戶的生產環境(二)
- 生產環境安裝Jexus
詳細步驟參見:15分鍾從零開始搭建支持10w+用戶的生產環境(三)
第二步:開發環境創建Demo項目
- 找個目錄,創建解決方案(這一步不是必須,不過我習慣這么做。總要有個解決方案來存放工程):
% dotnet new sln -o demo
The template "Solution File" was created successfully.
這一步完成后,會在當前目錄建立一個新目錄demo,同時,在demo目錄下創建文件demo.sln。
- 在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.
- 把新建的工程加到解決方案中:
% dotnet sln add demo/demo.csproj
Project `demo/demo.csproj` added to the solution.
- 檢查一下現在的目錄和文件結構:
其中有一個WeatherForecast,包含兩個文件:WeatherForecast.cs和WeatherForecastController.cs,是創建工程時自帶的演示類。
現在我們運行一下工程。可以用VSC的「運行」,也可以命令行:
% dotnet run
運行Demo工程。
運行后,從瀏覽器訪問:http://localhost:5000/WeatherForecast,會得到一串演示數據。這就是上面這個演示類的效果。
正式項目中,這兩個文件要刪掉。
到這一步,基礎工程就搭好了。
我們要做一個API服務,這個服務里要有幾個API,要用到數據庫訪問。為了測試API,我們需要裝個Swagger。當然用Postman也可以,不過我習慣用Swagger。
- 增加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();
});
}
}
}
- 增加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": "*"
}
- 建立數據庫操作類
在工程中創建一個目錄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數據的操作全在這個類中進行。
- 創建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的詳細說明。
- 檢查一下現在的工程目錄結構:
- 測試運行
在VSC中點擊運行,或者命令行輸入:
% dotnet run
等程序加載完成,可以訪問http://localhost:5000/swagger,進行訪問,並測試兩個API。
第三步:發布到生產環境
- 發布應用
前邊說了,開發環境是MAC,生產環境是Debian 9 x64,所以會涉及到一個跨平台的發布。
事實上,跨平台發布也很簡單。這個應用的目的環境是Linux-64,所以,發布命令是:
% dotnet publish -r linux-x64
發布完成后,系統會顯示發布的目錄。這個項目,發布目錄在demo/bin/Debug/netcoreapp3.1/linux-x64/publish。
- 打包傳到服務器,並解包到一個目錄。在這個演示中,我解包到了服務器的/var/demo。
- 在服務器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
![]() |
微信公眾號:老王Plus 掃描二維碼,關注個人公眾號,可以第一時間得到最新的個人文章和內容推送 本文版權歸作者所有,轉載請保留此聲明和原文鏈接 |