Abp小试牛刀之 图片上传
圖片上傳是很常見的功能,里面有些固定的操作也可以沉淀下來。
本文記錄使用Abp vNext做圖片上傳的姿勢(shì)。
目標(biāo)
上傳圖片----->預(yù)覽圖片----->確定保存
支持集群部署
實(shí)現(xiàn)思路:
1. 上傳圖片要使用WebAPI特定媒體類型:multipart/form-data;
2. 因?yàn)橐鰣D片預(yù)覽,故在上傳時(shí)利用AbpCache做一個(gè)臨時(shí)緩存,返回圖片Id;
3. 前端利用FileReader渲染預(yù)覽圖;
4.? [確定]: 發(fā)起持久化WebAPI(利用第2步返回的圖片Id)
為什么強(qiáng)調(diào)支持集群部署?
就這個(gè)功能而言,[上傳預(yù)覽]和[確定保存]是兩次Http WebAPI請(qǐng)求。
如果服務(wù)端使用的是Redis等進(jìn)程外緩存: 那這正好是一個(gè)Stateless應(yīng)用功能,集群環(huán)境無懼!
如果服務(wù)端使用的是進(jìn)程內(nèi)緩存:在集群環(huán)境,前后兩次請(qǐng)求有可能打到不同的App服務(wù),后置的[確定保存]WebAPI因此可能報(bào)錯(cuò), 此處需要做 [會(huì)話親和性] Session affinity
實(shí)踐
利用Abp做圖片上傳
IFormFile能力如下紅框:
下面將圖片二進(jìn)制流轉(zhuǎn)化為?base64字符串,注入Abp緩存組件IDistributedCache<string>;緩存圖片字符串1小時(shí)。
[上傳預(yù)覽], [確定保存]的API完整代碼如下:
///?<summary>///?上傳預(yù)覽,?返回待上傳的圖片id,Content-Type:multipart/form-data///?</summary>///?<returns></returns>[Consumes("multipart/form-data")][Route("upload/preview")][ProducesResponseType(typeof(Guid),200)][HttpPost]public?async?Task<Guid>?UploadPicPreviewAsync(IFormFile?uploadedFile){var?formFileName?=?uploadedFile.FileName;if?(!new[]?{?".png",?".jpg",?".bmp"?}.Any((item)?=>?formFileName.EndsWith(item))){throw?new?AbpValidationException("您上傳的文件格式必須為png、jpg、bmp中的一種");}byte[]?bytes;using?(var?bodyStream?=?uploadedFile.OpenReadStream()){using?(var?m?=?new?MemoryStream()){await?bodyStream.CopyToAsync(m);bytes?=?m.ToArray();}}string?base64?=?Convert.ToBase64String(bytes);var?bgId?=?Guid.NewGuid();_cache.Set($"{CurrentUser.TenantId}:bg:{bgId}",?base64,?new?DistributedCacheEntryOptions?{?SlidingExpiration?=?new?TimeSpan(1,?0,?0)?});return?bgId;}///?<summary>///?保存圖片,要使用到前置API的預(yù)覽圖片id///?</summary>///?<param?name="createPictureInput"></param>///?<returns></returns>[Route("upload/")][HttpPost]public?async?Task<bool>?UploadPicAsync([FromBody]?CreatePictureInput?createPictureInput){var?based64?=?await?_cache.GetAsync($"{CurrentUser.TenantId}:bg:{createPictureInput.PreviewPicId}");if?(string.IsNullOrEmpty(based64))throw??new?AbpException("Cache?Hotmap?Picture?do?not?find");var?model?=?ObjectMapper.Map<CreatePictureInput,?Picture>(createPictureInput);model.ProfileId?=?CurrentUser.TenantId;model.BlobStorage?=?Convert.FromBase64String(based64);return?await?_pictures.InsertAsync(model)!=?null;}Default implementation of the IDistributedCache interface is the MemoryDistributedCache which works in-memory.?
The Distributed Memory Cache (AddDistributedMemoryCache) is a framework-provided implementation of IDistributedCache that stores items in memory. The Distributed Memory Cache isn't an actual distributed cache. Cached items are stored by the app instance on the server where the app is running.
以上兩段文字來自 Abp和ASP.NET Core官方文檔:
Abp默認(rèn)的IDistributedCache實(shí)現(xiàn)是分布式內(nèi)存緩存;
ASP.NETCore 分布式內(nèi)存緩存是框架內(nèi)置的,是一個(gè)假的分布式緩存,實(shí)際是單純的內(nèi)存緩存。
在沒有使用真實(shí)分布式緩存的情況下, 需要對(duì)前后兩個(gè)API配置會(huì)話親和性。
會(huì)話親和性
下面從nginx、Azure、k8s ingress 三角度配置[會(huì)話親和性],(全站生效)??
會(huì)話親和性的實(shí)現(xiàn)原理,是在接受客戶端首次請(qǐng)求時(shí)響應(yīng)某個(gè)cookie,服務(wù)器會(huì)認(rèn)定使用同一個(gè)cookie的請(qǐng)求為一個(gè)會(huì)話。
1. nginx
屬于nginx負(fù)載均衡的范疇:https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/
示例如下:
upstream?backend?{server?backend1.example.com;server?backend2.example.com;sticky?cookie?srv_id?expires=1h?domain=.example.com?path=/; }2. Azure App Service
Azure pp Service是Azure云平臺(tái)提供的App托管服務(wù),具備多實(shí)例自動(dòng)縮放的能力, 其有關(guān)會(huì)話親和性的配置如圖:
3. K8S nginx-ingress
注解nginx.ingress.kubernetes.io/affinity在入口的所有上游中啟用和設(shè)置親和性類型。
這樣,請(qǐng)求將總是被定向到相同的上游服務(wù)器。
https://kubernetes.github.io/ingress-nginx/examples/affinity/cookie/
That's All
本文以常見的圖片上傳功能為例,實(shí)戰(zhàn)演練了Abp的緩存和持久化能力;引申出對(duì)有狀態(tài)應(yīng)用(集群)配置會(huì)話親和性。
部署配置要結(jié)合業(yè)務(wù)功能,希望對(duì)大家有所幫助!
關(guān)注并星標(biāo)我們
更多干貨及最佳實(shí)踐分享
總結(jié)
以上是生活随笔為你收集整理的Abp小试牛刀之 图片上传的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Select.HtmlToPdf 把
- 下一篇: .Net Conf 2020 之回顾