zoukankan      html  css  js  c++  java
  • C# net部署图片分布式存储服务器的小案例

    如果web服务用户多了,访问多了,用户上传的图片,文件等内容放在一块,想必服务器是承受不住的,这个时候,我们就需要考虑分布式存储的方法了。

    如图所示:一个web服务器拖2个图片服务器

    如何做到用户上传的图片 比较均衡的存放到两个图片器上----简单的能想到 随机数

    在这儿 ,咱们就基于随机数演示一下;

    设计存储方案的数据库

    要有一张表来存放图片服务器的信息,还有一张表用来存放图片的路径;

    VS2013中创建的项目目录,大家看到创建了两个ImageService的一般处理程序,既然图片服务器要接收web服务器发送的图片请求,那么就要实现其程序,部署在2个图片服务器上的程序其实是一样的,这儿需要在一台电脑上演示两台图片服务器,所以创建了多个程序

    首先Model层  使用EF,直接从数据库生成

    2、图片服务器 处理程序在这儿使用一般处理程序ashx 

       首先添加对model 成的引用

       接着新建一般处理程序  FileUp.ashx,两个图片服务器是一样的

    namespace QAU.DFS.ImageService1
    {
        /// <summary>
        /// FileUp 的摘要说明
        /// </summary>
        public class FileUp : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                int serverId = int.Parse(context.Request["serverId"]);
                string ext = context.Request["ext"];
                string dir = "/Image/" + DateTime.Now.Day + "/";
                Directory.CreateDirectory(Path.GetDirectoryName(context.Request.MapPath(dir)));
                string newFileName = Guid.NewGuid().ToString();
                string fullDir = dir + newFileName + ext;
                using (FileStream fileStream = File.OpenWrite(context.Request.MapPath(fullDir)))
                {
                    context.Request.InputStream.CopyTo(fileStream);
                    ImageInfo imageInfo = new ImageInfo();
                    imageInfo.ImageName = fullDir;
                    imageInfo.ImageServerId = serverId;
                    ImageServerEntities db = new ImageServerEntities();
                    db.ImageInfo.Add(imageInfo);
                    db.SaveChanges();
    
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    

      3、新建web 项目 DFS.web,使用空的MVC4,  

    新建Home 控制器  代码如下:

    HomeController.cs

    public class HomeController : Controller
        {
            //
            // GET: /Home/
            ImageServerEntities db = new ImageServerEntities();
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult FileUp()
            {
                
                HttpPostedFileBase file = Request.Files["fileUp"];
                string fileName = Path.GetFileName(file.FileName);
                string fileExt = Path.GetExtension(fileName);
                if (fileExt == ".png" ||fileExt== ".jpg")
                {
                    //从服务器状态表筛选出可用的图片服务器集合记作C,并获取集合的总记录数N,然后用随机函数产生一个随机数R1,并用R1与N进行取余运算记作I=R1%N。 则C[I]即为要保存图片的图片服务器 
                    
                    List<ImageServerInfo> list = db.ImageServerInfo.Where(c => c.FlgUsable == true).ToList();
                    int count = list.Count();
                    Random random = new Random();
                    int r = random.Next();
                    int i = r % count;
                    ImageServerInfo imageService = list[i];
                    string url = imageService.ServerUrl;//图片服务器的地址
                    int serverId = imageService.ServerId;//图片服务器编号
                    string address = "http://"+url+"/FileUp.ashx?serverId="+serverId+"&ext="+fileExt;
    
                    WebClient client = new WebClient();
                    client.UploadData(address, StreamToByte(file.InputStream));
                    
                }
                return Content("ok");
                
            }
            private byte[] StreamToByte(Stream stream)
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Seek(0, SeekOrigin.Begin);
                return buffer;
            }
    
            public ActionResult ShowImage()
            {
                var imageServerInfo = db.ImageServerInfo.Where(c => c.FlgUsable == true).ToList();
                ViewData["imageServerList"] = imageServerInfo;
                return View();
            }
    
        }
    }
    

      

    4、上传页面 Index.cshtml

    <div>
            <form method="post" action="/Home/FileUp" enctype="multipart/form-data">
                <input type="file" name="fileUp" />
                <input type="submit" value="上传" />
            </form>
        </div>
    

      5、显示上传的图片

    ShowImage.cshtml

    <div>
            <h1>显示分布式服务器中 所有图片信息</h1>
            <ul>
                @foreach (ImageServerInfo imageService in (List<ImageServerInfo>)ViewData["imageServerList"])
                {
                    foreach (var imageInfo in imageService.ImageInfo)
                    {<li>
                        <img src="@string.Format("http://{0}{1}",imageService.ServerUrl,imageInfo.ImageName)" width="200" height="200" />
                    </li>
                    }
                
                }
            </ul>
        </div>
    

      至此,完成,项目demo  下载地址 在下面:

          分布式图片存储小demo

  • 相关阅读:
    62. Unique Paths
    102. Binary Tree Level Order Traversal
    3、公共接口不应该使用太过频繁,当有大量类型实现公共接口时,应当避免通过公共接口调用对象
    2、Task 使用 ContinueWith 而不要使用 Wait
    1、使用 as 而不要用 is
    VS 超级好用的 Ctrl E E
    一个好用的分组算法2
    java 字典 map 和 list.forEach
    mongo windows 安装
    mongo repository
  • 原文地址:https://www.cnblogs.com/lastcode/p/4924233.html
Copyright © 2011-2022 走看看