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 (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>
  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. 检查一下现在的工程目录结构:

  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


微信公众号:老王Plus

扫描二维码,关注个人公众号,可以第一时间得到最新的个人文章和内容推送

本文版权归作者所有,转载请保留此声明和原文链接

原文地址:https://www.cnblogs.com/tiger-wang/p/12833849.html