日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

《ASP.NET Core 微服务实战》-- 读书笔记(第5章)

發布時間:2023/12/4 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《ASP.NET Core 微服务实战》-- 读书笔记(第5章) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

第 5 章 創建數據服務

選擇一種數據存儲

由于我堅持要盡可能的跨平臺,所以我決定選用 Postgres,而不用 SQL Server 以照顧 Linux 或 Mac 電腦的讀者

構建 Postgres 倉儲

在本節,我們要升級位置服務讓它使用 Postgres

為了完成這一過程,需要創建一個新的倉儲實現,以封裝 PostgreSQL 的客戶端通信

回顧一下位置倉庫的接口

public interface ILocationRecordRepository {LocationRecord Add(LocationRecord locationRecord);LocationRecord Update(LocationRecord locationRecord);LocationRecord Get(Guid memberId, Guid recordId);LocationRecord Delete(Guid memberId, Guid recordId);LocationRecord GetLatestForMember(Guid memberId);ICollection<LocationRecord> AllForMember(Guid memberId); }

接下來要做的就是創建一個數據庫上下文

數據庫上下文的使用方式是創建與特定模型相關的類型,并從數據庫上下文繼承

由于與位置數據打交道,所以要創建一個 LocationDbContext 類

using Microsoft.EntityFrameworkCore; using StatlerWaldorfCorp.LocationService.Models; using Npgsql.EntityFrameworkCore.PostgreSQL;namespace StatlerWaldorfCorp.LocationService.Persistence {public class LocationDbContext : DbContext{public LocationDbContext(DbContextOptions<LocationDbContext> options) :base(options){}protected override void OnModelCreating(ModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);modelBuilder.HasPostgresExtension("uuid-ossp");}public DbSet<LocationRecord> LocationRecords {get; set;}} }

實現位置記錄倉儲接口

// using Microsoft.EntityFrameworkCore;using System; using System.Linq; using System.Collections.Generic; using StatlerWaldorfCorp.LocationService.Models; using Microsoft.EntityFrameworkCore;namespace StatlerWaldorfCorp.LocationService.Persistence {public class LocationRecordRepository : ILocationRecordRepository{private LocationDbContext context;public LocationRecordRepository(LocationDbContext context){this.context = context;}public LocationRecord Add(LocationRecord locationRecord){this.context.Add(locationRecord);this.context.SaveChanges();return locationRecord;}public LocationRecord Update(LocationRecord locationRecord){this.context.Entry(locationRecord).State = EntityState.Modified;this.context.SaveChanges();return locationRecord;}public LocationRecord Get(Guid memberId, Guid recordId){return this.context.LocationRecords.FirstOrDefault(lr => lr.MemberID == memberId && lr.ID == recordId);}public LocationRecord Delete(Guid memberId, Guid recordId){LocationRecord locationRecord = this.Get(memberId, recordId);this.context.Remove(locationRecord);this.context.SaveChanges();return locationRecord;}public LocationRecord GetLatestForMember(Guid memberId){LocationRecord locationRecord = this.context.LocationRecords.Where(lr => lr.MemberID == memberId).OrderBy(lr => lr.Timestamp).Last();return locationRecord;}public ICollection<LocationRecord> AllForMember(Guid memberId){return this.context.LocationRecords.Where(lr => lr.MemberID == memberId).OrderBy(lr => lr.Timestamp).ToList();}} }

為了實現以注入的方式獲取 Postgres 數據庫上下文,需要在 Startup 類的 ConfigureServices 方法里把倉儲添加到依賴注入系統

public void ConfigureServices(IServiceCollection services) {services.AddEntityFrameworkNpgsql().AddDbContext<LocationDbContext>(options =>options.UseNpgsql(Configuration));services.AddScoped<ILocationRecordRepository, LocationRecordRepository>();services.AddMvc(); }

數據庫是一種后端服務

在本例中,我們準備用環境變量來覆蓋由配置文件提供的默認配置

appsettings.json

{"transient": false,"postgres": {"cstr": "Host=localhost;Port=5432;Database=locationservice;Username=integrator;Password=inteword"} }

前面實現的倉儲需要一種數據庫上下文才能運作,為了給位置模型創建數據庫上下文,只需要創建一個類,并從 DbContext 繼承

using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using StatlerWaldorfCorp.LocationService.Models; using Npgsql.EntityFrameworkCore.PostgreSQL;namespace StatlerWaldorfCorp.LocationService.Persistence {public class LocationDbContext : DbContext{public LocationDbContext(DbContextOptions<LocationDbContext> options) :base(options){}protected override void OnModelCreating(ModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);modelBuilder.HasPostgresExtension("uuid-ossp");}public DbSet<LocationRecord> LocationRecords {get; set;}}public class LocationDbContextFactory : IDbContextFactory<LocationDbContext>{public LocationDbContext Create(DbContextFactoryOptions options){var optionsBuilder = new DbContextOptionsBuilder<LocationDbContext>();var connectionString = Startup.Configuration.GetSection("postgres:cstr").Value;optionsBuilder.UseNpgsql(connectionString);return new LocationDbContext(optionsBuilder.Options);}} }

創建了新的數據庫上下文后,需要讓它在依賴注入中可用,這樣位置倉儲才能使用它

public void ConfigureServices(IServiceCollection services) {//var transient = Boolean.Parse(Configuration.GetSection("transient").Value);var transient = true;if (Configuration.GetSection("transient") != null) {transient = Boolean.Parse(Configuration.GetSection("transient").Value);}if (transient) {logger.LogInformation("Using transient location record repository.");services.AddScoped<ILocationRecordRepository, InMemoryLocationRecordRepository>();} else {var connectionString = Configuration.GetSection("postgres:cstr").Value;services.AddEntityFrameworkNpgsql().AddDbContext<LocationDbContext>(options =>options.UseNpgsql(connectionString));logger.LogInformation("Using '{0}' for DB connection string.", connectionString);services.AddScoped<ILocationRecordRepository, LocationRecordRepository>();}services.AddMvc(); }

讓這些功能最終生效的奇妙之處在于對 AddEntityFrameworkNpgsql 以及 AddDbContext 兩個方法的調用

對真實倉儲進行集成測試

我們想要利用自動的構建流水線,每次運行構建時都啟動一個新的、空白的 Postgres 實例

然后,讓集成測試在這個新實例上運行,執行遷移以配置數據庫結構

每次提交代碼時,整個過程既要能在本地、團隊成員的機器上運行,又要能在云上自動運行

這就是我喜歡搭配使用 Wercker 和 Docker 的原因

試運行數據服務

使用特定參數啟動 Postgres

$ docker run -p 5432:5432 --name some-postgres \ -e POSTGRES_PASSWORD=inteword -e POSTGRES_USER=integrator \ -e POSTGRES_DB=locationservice -d postgres

這樣就以 some-postgres 為名稱啟動一個 Postgres 的 Docker 鏡像

為驗證能夠成功連接到 Postgres,可運行下面的 Docker 命令來啟動 psql

$ docker run -it --rm --link some-postgres:postgres postgres \ psql -h postgres -U integrator -d locationservice

數據庫啟動后,還需要表結構,順便設置了很快會用到的環境變量

$ exprot TRANSIENT=false $ export POSTGRES__CSTR=“Host=localhost;Username=integrator; \ Password=inteword;Database=locationservice;Port=5432" $ dotnet ef database update

我們期望位置服務能夠訪問到自己的容器之外,并進入 Postgres 容器之內

容器鏈接能夠實現這項能力,不過需要在啟動 Docker 鏡像之前就完成環境變量的修改

$ export POSTGRES__CSTR=“Host=localhost;Username=integrator; \ Password=inteword;Database=locationservice;Port=5432" $ docker run -p 5000:5000 --link some-postgres:psotgres \ -e TRANSIENT=false -e PORT=5000 \ -e POSTGRES__CSTR dotnetcoreservices/locationservice:latest

使用 psotgres 作為主機名鏈接 Postgres 容器后,位置服務就應該能夠正確連接到數據庫了

為親自驗證結果,可以提交一個位置記錄

$ curl -H "Content-Type:application/json" -X POST -d \ '{"id":"64c3e69f-1580-4b2f-a9ff-2c5f3b8f0elf","latitude":12.0, \ "longitude":10.0,"altitude":5.0,"timestamp":0, \ "memberId":"63e7acf8-8fae-42ec-9349-3c8593ac8292"}' \ http://localhost:5000/locations/63e7acf8-8fae-42ec-9349-3c8593ac8292

通過服務查詢我們虛構的團隊成員歷史位置

$ curl http://localhost:5000/locations/63e7acf8-8fae-42ec-9349-3c8593ac8292

為了再次確認,查詢 latest 端點并確保仍能獲取到期望的輸出

$ curl http://localhost:5000/locations/63e7acf8-8fae-42ec-9349-3c8593ac8292/latest

最后,為了證實確實在使用真實的數據庫實例,可以使用 docker ps 以及 docker kill 找到位置服務所在的 Docker 進程并終止它

然后通過之前用過的命令重新啟動服務

總結

以上是生活随笔為你收集整理的《ASP.NET Core 微服务实战》-- 读书笔记(第5章)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。