头图

Author: Read more

A few days ago, WeChat upgraded the cloud hosting in the applet developer tool to WeChat cloud hosting, adding many new capabilities such as OpenApi, MySql database, pipeline construction, and web console. It is quite exciting to read the documentation, which is really good news for developers, because most of the previous business logic is written in cloud functions or deployed in the server, and several sets of management have to be managed. After reading this release of WeChat Cloud Hosting, I was a little tempted to do a migration. Compared with other models, WeChat Cloud Hosting still has advantages and prospects. Regarding the comparison of WeChat cloud hosting and cloud functions as well as servers and Kubernetes, this link is enough: https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/basic/intro.html

This time I will use a small demo to practice hands. Not much to say, out of curiosity, let everyone experience it today:

The first step: open the environment

First log in to the WeChat cloud hosting creation environment, the address of cloud hosting is: 160ee4c31263c4 https://cloud.weixin.qq.com/

First, you need to create an environment. The creation environment is divided into system creation and private network. Selecting private network will list the previously created environments of the Tencent Cloud account corresponding to the applet. Here I choose the private network and my current applet The same environment used.

This time, let’s also look at mysql. WeChat Cloud Hosting has added MySql service compared to before, and it is very convenient to activate. As shown in the figure below, you can successfully activate and support automatic suspension in a few simple steps:

After opening, it is like this. It supports internal and external network access to the database, and provides an automatic suspension service, which will help you to suspend it when it is idle.

Since the project needs to use the "cloud call" to obtain the small program code service, so here is to install the OpenApi provided by WeChat Cloud Hosting. It must be noted here that if you want to use the "cloud call" service, the WeChat token permission setting must be here. Add the interface to be used to the whitelist first.

Small tips: When you use the OpenApi interface, you can open the public domain name access during the test and development, and you can enable the intranet access in the online environment, which is relatively safe. Because the interface you call OpenApi is no longer the same as before, you need to exchange for Access_Token, and the risk of public network exposure is high.

Step 2: Create a new service

Pipeline release

If you choose a pipeline release, the first step is to create a new pipeline. The code to choose a pipeline release must include the container.config.json file. The writing method can be defined according to the document: https://developers.weixin.qq.com/miniprogram /dev/wxcloudrun/src/basic/guide.html

After GitHub authorizes access and includes the container.config.json file in the warehouse, and then selects other configurations according to your actual situation, such a pipeline will be defined. When the code push triggers the main branch, it will automatically build the mirror and build it. After that, don't forget to deploy and release the latest version at the end. The pipeline will not automatically release the latest version for you.

Version release

Version release is also very convenient. After defining the Dockerfile file, you can configure the pull from GitHub or locally build the docker image in the Tencent Cloud personal warehouse build configuration and push it to Tencent Cloud. What I chose here is WeChat Cloud managed code pull:

Select the new version in the version list, pull it from the code base, and pull down the program we wrote:

After the code is pulled, it will automatically help us build the image in the WeChat cloud hosting. Click to view the log to see the detailed construction process, which is a familiar operation.

After the version is built, it is released afterwards. Whether it is to choose a pipeline release or a version release, the final step must be to choose to release and go online.

Step 3: Development

Here I create a .Net Core project and select the WebApp template.

Next edit the Dockerfile file:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
​
FROM mcr.microsoft.com/dotnet/aspnet:3.1 AS base
​
WORKDIR /app
​
EXPOSE 80
​
FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
​
WORKDIR /src
​
COPY ["HtArtGoWebApp.csproj", "."]
​
RUN dotnet restore "./HtArtGoWebApp.csproj"
​
COPY . .
​
WORKDIR "/src/."
​
RUN dotnet build "HtArtGoWebApp.csproj" -c Release -o /app/build

FROM build AS publish
​
RUN dotnet publish "HtArtGoWebApp.csproj" -c Release -o /app/publish
​
FROM base AS final
​
WORKDIR /app
​
COPY --from=publish /app/publish .
​
ENTRYPOINT ["dotnet", "HtArtGoWebApp.dll"]

Then install the database driver

​<ItemGroup>

<PackageReference Include="FreeSql" Version="2.5.200" />

<PackageReference Include="FreeSql.Provider.MySql" Version="2.5.200" />

</ItemGroup>

Inject FreeSql and define entities. First define the entities. I created a new Models folder in the project. The entities are placed in the Models folder. First define a basic class BaseEntity.cs

public class BaseEntity where TKey : IEquatable
{
  [Column(IsPrimary = true, IsIdentity = true)]
  public TKey Id { get; set; }
  [Column(ServerTime = DateTimeKind.Utc, CanUpdate = false)]
  public DateTime CreateTime { get; set; }
  [Column(ServerTime = DateTimeKind.Utc)]
  public DateTime UpdateTime { get; set; }
  public string OperatorId { get; set; }
  public bool IsDelete { get; set; }
  public bool Status { get; set; }
​
}

Then define a class for testing Exhibitions.cs class, let it inherit BaseEntity, the primary key can be customized type:

public class Exhbitions:BaseEntity
{
  public string Title { get; set; }
}

Next is the configuration and injection of FreeSql, which is injected in the Stratup.cs file:

public Startup(IConfiguration configuration)
{
​
  Configuration = configuration;
  //FreeSql配置
  fsql = new FreeSql.FreeSqlBuilder()
  //链接字符串
   .UseConnectionString(FreeSql.DataType.MySql,
    Configuration.GetConnectionString("MySql"))
      //自动同步实体打开
​ .UseAutoSyncStructure(true)
   //SQL日志也打开
   .UseMonitorCommand(cmd =>      Console.WriteLine(cmd.CommandText))
    .Build();
​
}
public IConfiguration Configuration { get; }
public IFreeSql fsql;

Finally, perform injection in ConfigureServices. The injection method is singleton mode: services.AddSingleton<IFreeSql>(fsql)

In this way, the database part is configured and injected successfully, and then the database is called to query the data, and an Index.cshtml page is selected for data query display:

public class IndexModel : PageModel
{
​
  private readonly ILogger _logger;
  private IFreeSql _freeSql;
  //前端要展示的数据定义为属性
  public IList ExhbitionListList { get; set; }
​
  public IndexModel(ILogger logger,IFreeSql freeSql)
  {
​
     _logger = logger;
​
    _freeSql = freeSql;
​
  }
​
  //页面初始化的时候查询数据
​
  public async Task OnGetAsync()
  {
    var data = await _freeSql.Select().ToListAsync();
    //赋值
   ExhbitionListList = data;
  }
}

Use a table to display in the front-end Index.cshtml:

<table style="margin-left: 30%">

<thead>

<tr>

<th>ID</th>

<th>名称</th>

<th>创建日期</th>

</tr>

</thead>

<tbody>

@foreach (var item in this.Model.ExhbitionListList)

{

<tr>

<td>@item.Id</td>

<td>@item.Title</td>

<td>@item.CreateTime</td>

</tr>

}

</tbody>

</table>

The above is the database part. Next, we will use the OpenApi hosted by WeChat Cloud to call. The part about OpenApi is placed in the OpenApiService class in the RestService folder.

In this folder, I only wrote an interface to obtain the small program code for testing. The code is as follows:

public class OpenApiService
{
  private HttpClient _client;
  public OpenApiService(HttpClient client)
  {
​
    client.BaseAddress =new Uri("http://替换成大家自己的");
    _client = client;
  }
​
  public async Task GetgetUnlimited()
  {
   var body = new StringContent(JsonSerializer.Serialize(new
      {
        scene = "index",
      page = "pages/index/index"
   }),   Encoding.UTF8, "application/json");
​
    var response =   await _client.PostAsync("/wxa/getwxacodeunlimit", body);
​
   if (response.IsSuccessStatusCode)
​   {
​
      MemoryStream ms = new MemoryStream();
​
     await response.Content.CopyToAsync(ms);
​
    return ms;
​
    }
​   return null;
​
  }
​
}

Then inject it into ConfigureService: services.AddHttpClient<OpenApiService>();

To call the service, we write a Controller interface for the front end to call. Here we need to configure two places in Startup.cs:

After configuration, you can call it in the controller:

[ApiController]
[Route("api/[controller]")]
public class WxController : Controller
{
  private OpenApiService _openApiService;
  public WxController(OpenApiService openApiService)
  {
    _openApiService = openApiService;
  }
  [HttpGet]
  public async Task GetgetUnlimited()
  {
​
    var data = await _openApiService.GetgetUnlimited();
   return new FileContentResult(data.ToArray(), "image/jpeg");
  }
​
}

Don't forget to add the whitelist of the interface for obtaining the applet code in WeChat Cloud Hosting:

Alright, the code part is over here. Debug it locally and release it if there is no problem:

Obtaining the applet code is normal

Database access is normal

The page looks a bit ugly, use Vue and ElementUI to optimize the homepage, introduce the related libraries of Vue and ElementUI in _Layout.cshtml, and then make the following changes in the front-end Index.cshtml.cs:

public class IndexModel : PageModel
{
​
  private readonly ILogger _logger;
​
  private IFreeSql _freeSql;
​
  public IList ExhbitionListList { get; set; }
​
  public IndexModel(ILogger logger,IFreeSql freeSql)
  {
​
    _logger = logger;
​
   _freeSql = freeSql;
  }
​
  // public async Task OnGetAsync()
​
  // {
​
  //   var data = await        _freeSql.Select().ToListAsync();
​
  //   ExhbitionListList = data;
​
  // }
​
   public async Task OnGetList()
​
  {
​
   var data = await _freeSql.Select().ToListAsync();
​
    return new  JsonResult(data);
​
  }
​
}

Use the Table component of element to optimize the Html page:

<div id="app">

<el-table v-bind:data="list" border style="width: 100%">

<el-table-column fixed prop="id" label="id">

</el-table-column>

<el-table-column prop="title" label="标题">

</el-table-column>

<el-table-column prop="createTime" label="创建时间">

</el-table-column>

<el-table-column

fixed="right"

label="操作"

width="100">

<template slot-scope="scope">

<el-button v-on:click="handleClick(scope.row)" type="text" size="small">查看</el-button>

<el-button type="text" size="small">编辑</el-button>

</template>

</el-table-column>

</el-table>

</div>

@section Scripts

{

<script type="text/javascript">

var app=new Vue({

el:'#app',

data:{

title:'主页',

list:[]

},

async created(){

const list= await this.loadData();

this.list = list

},

methods:{

loadData(){

return new Promise(((resolve, reject) =>

$.ajax({

url:'?handler=List',

success:(res)=>{

resolve(res)

},fail:(err)=>{

reject(err)

}

})

))

},

handleClick(row) {

console.log(row);

}}

})

</script>
}

The displayed page is as follows, and CURD related operations will be added later:



Then add an API management tool Swagger, here in order to demonstrate adding a Swagger that is the easiest to configure, adding Swagger first needs to install the Swagger package Swashbuckle.AspNetCore on Nuget. After injecting services.AddSwaggerGen(); into the ConfigureServices method, register the Swagger middleware in Configure: app.UseSwagger();

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

Then visit localhost:5000//swagger/index.html

After the final release, everything is normal. I feel that the future can be expected, and the log query is also very convenient. This must be praised:

to sum up

To sum up, the direction of WeChat cloud hosting is very good. It is very suitable for rapid development and verification of business models. I hope to support environment sharing and custom domain names as soon as possible in the future. There will be a second chapter on how to integrate CMS into the project. Please look forward to it. ~

Experience now

Please use the PC browser to visit the following address: https://cloud.weixin.qq.com/ to start the experience and enjoy the free quota for the first month.

Exchange group


CloudBase云开发
425 声望438 粉丝

云开发(Tencent CloudBase,TCB)是云端一体化的后端云服务 ,采用 serverless 架构,免去了移动应用构建中繁琐的服务器搭建和运维。同时云开发提供的静态托管、命令行工具(CLI)、Flutter SDK 等能力极大的降...