예제 #1
0
        public ShortUrlResult Create(string longUrl, string baseUrl)
        {
            var result = new ShortUrlResult {
                Code = 0
            };
            var md5    = Md5(longUrl);
            var hadMap = _dictMaps.FirstOrDefault(d => d.Value.Md5 == md5);

            if (hadMap.Value != null)
            {
                result.ShortUrl = $"{baseUrl}/{hadMap.Value.ShortUrl}";
                return(result);
            }

            lock (Locker) {
                using (var dc = new ShortUrlContext()) {
                    var umTmp = dc.UrlMaps.FirstOrDefault(d => d.Md5 == md5);
                    if (umTmp != null)
                    {
                        ChangeRate(umTmp);
                        result.ShortUrl = umTmp.ShortUrl;
                        return(result);
                    }

                    if (_maxRecord == null)
                    {
                        _maxRecord = new MaxRecord {
                            Id         = Guid.NewGuid(),
                            Status     = 0,
                            No         = 1,
                            LastChange = DateTime.Now
                        };
                        dc.MaxRecords.Add(_maxRecord);
                    }
                    else
                    {
                        _maxRecord.No        += 1;
                        _maxRecord.LastChange = DateTime.Now;
                        var old = dc.MaxRecords.Find(_maxRecord.Id);
                        dc.Entry(old).CurrentValues.SetValues(_maxRecord);
                    }

                    var um = new UrlMap {
                        Id         = Guid.NewGuid(),
                        LongUrl    = longUrl,
                        ShortUrl   = Encrypt(_maxRecord.No),
                        Md5        = md5,
                        Status     = (int)EntityStatus.Init,
                        LastChange = DateTime.Now
                    };
                    dc.UrlMaps.Add(um);
                    dc.SaveChanges();
                    ChangeRate(um);
                    result.ShortUrl = $"{baseUrl}/{um.ShortUrl}";
                    return(result);
                }
            }
        }
예제 #2
0
 private Service()
 {
     using (var dc = new ShortUrlContext()) {
         _maxRecord = dc.MaxRecords.FirstOrDefault();
         _dictMaps  = new Dictionary <string, UrlMap>();
         var maps = dc.UrlMaps.Where(d => d.Status < 1000).OrderByDescending(d => d.LastChange).Take(100);
         foreach (var map in maps)
         {
             _dictMaps.Add(map.ShortUrl, map);
         }
     }
 }