Esempio n. 1
0
        /// <summary>
        ///根据url生成短链接id
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string Generate(string url)
        {
            var         errorCount  = 0;
            var         postfix     = string.Empty;
            var         shortId     = string.Empty;
            ShortUrlMap shortUrlMap = null;

            // 违反唯一索引异常
            Func <DbUpdateException, bool> duplicateKeyPredict = ex =>
                                                                 ex.InnerException != null &&
                                                                 ex.InnerException.Message.Contains("duplicate key");

            Policy.Handle <DbUpdateException>(duplicateKeyPredict).Retry(2).Execute(() =>
            {
                // 在违反唯一索引的情况下,判断是否真实的重复提交
                if (errorCount == 1 && _storeService.Exist(shortId, url))
                {
                    shortUrlMap = new ShortUrlMap {
                        ShortId = shortId, LongUrl = url
                    };
                    return;
                }
                // hash冲突
                else
                {
                    // 计数错误次数
                    errorCount++;
                    // 追加自定义后缀(首次不需要追加,所以为空)
                    url += postfix;
                    // 首次完成后,开始追加真正的后缀
                    if (string.IsNullOrWhiteSpace(postfix))
                    {
                        postfix = GlobalConfig.CONFLICT_POSTFIX;
                    }

                    shortId     = _shortIdService.Generate(url);
                    shortUrlMap = new ShortUrlMap {
                        ShortId = shortId, LongUrl = url
                    };
                    _storeService.Add(shortUrlMap);
                }
            });

            return(shortUrlMap.ShortId);
        }
Esempio n. 2
0
 /// <summary>
 /// 增加短长链接映射
 /// </summary>
 /// <param name="shortUrlMap"></param>
 public void Add(ShortUrlMap shortUrlMap)
 {
     //if (Exist(shortUrlMap.ShortId, shortUrlMap.LongUrl)) throw new UniqueException();
     _context.ShortUrlMaps.Add(shortUrlMap);
     _context.SaveChanges();
 }