2月 26

公司的项目用到的了Redis,还是很好用的,引用了,但是还是有些麻烦的地方,自己写了一个类封装了一些操作,相对方便一点,记录一下Code

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using ServiceStack.Redis; 
      
namespace Com.QFGame.QNX.Community.Redis 
{ 
    public class RedisBase 
    { 
      
        private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"]; 
      
        #region -- 连接信息 -- 
        //10.0.18.8:6379 
        public static PooledRedisClientManager prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath }); 
        private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts) 
        {  
            // 支持读写分离,均衡负载  
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig 
            { 
                MaxWritePoolSize = 5, // “写”链接池链接数  
                MaxReadPoolSize = 5, // “读”链接池链接数  
                AutoStart = true, 
            }); 
        } 
        #endregion 
      
      
      
      
      
      
      
      
      
      
        #region -- Item -- 
        /// <summary> 
        /// 设置单体 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="t"></param> 
        /// <param name="timeSpan"></param> 
        /// <returns></returns> 
        public static bool Item_Set<T>(string key, T t) 
        { 
            try
            { 
                using (IRedisClient redis = prcm.GetClient()) 
                { 
                    return redis.Set<T>(key, t, new TimeSpan(1, 0, 0)); 
                } 
            } 
            catch (Exception ex) 
            { 
                // LogInfo 
            } 
            return false; 
        } 
      
        /// <summary> 
        /// 获取单体 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <returns></returns> 
        public static T Item_Get<T>(string key) where T : class
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.Get<T>(key); 
            } 
        } 
      
        /// <summary> 
        /// 移除单体 
        /// </summary> 
        /// <param name="key"></param> 
        public static bool Item_Remove(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.Remove(key); 
            } 
        } 
      
        #endregion 
      
        #region -- List -- 
      
        public static void List_Add<T>(string key, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var redisTypedClient = redis.GetTypedClient<T>(); 
                redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t); 
            } 
        } 
      
              
      
        public static bool List_Remove<T>(string key, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var redisTypedClient = redis.GetTypedClient<T>(); 
                return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0; 
            } 
        } 
        public static void List_RemoveAll<T>(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var redisTypedClient = redis.GetTypedClient<T>(); 
                redisTypedClient.Lists[key].RemoveAll(); 
            } 
        } 
      
        public static int List_Count(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.GetListCount(key); 
            }  
        } 
      
        public static List<T> List_GetRange<T>(string key, int start, int count) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var c = redis.GetTypedClient<T>(); 
                return c.Lists[key].GetRange(start, start + count - 1); 
            } 
        } 
      
      
        public static List<T> List_GetList<T>(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var c = redis.GetTypedClient<T>(); 
                return c.Lists[key].GetRange(0, c.Lists[key].Count); 
            } 
        } 
      
        public static List<T> List_GetList<T>(string key, int pageIndex, int pageSize) 
        { 
            int start = pageSize * (pageIndex - 1); 
            return List_GetRange<T>(key, start, pageSize); 
        } 
      
        /// <summary> 
        /// 设置缓存过期 
        /// </summary> 
        /// <param name="key"></param> 
        /// <param name="datetime"></param> 
        public static void List_SetExpire(string key, DateTime datetime) 
        { 
                using (IRedisClient redis = prcm.GetClient()) 
                { 
                        redis.ExpireEntryAt(key, datetime); 
                } 
        } 
        #endregion 
      
        #region -- Set -- 
        public static void Set_Add<T>(string key, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var redisTypedClient = redis.GetTypedClient<T>(); 
                redisTypedClient.Sets[key].Add(t); 
            } 
        } 
        public static bool Set_Contains<T>(string key, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var redisTypedClient = redis.GetTypedClient<T>(); 
                return redisTypedClient.Sets[key].Contains(t); 
            } 
        } 
        public static bool Set_Remove<T>(string key, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var redisTypedClient = redis.GetTypedClient<T>(); 
                return redisTypedClient.Sets[key].Remove(t); 
            } 
        } 
        #endregion 
      
      
        #region -- Hash -- 
        /// <summary> 
        /// 判断某个数据是否已经被缓存 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="dataKey"></param> 
        /// <returns></returns> 
        public static bool Hash_Exist<T>(string key, string dataKey) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.HashContainsEntry(key, dataKey); 
            } 
        } 
      
        /// <summary> 
        /// 存储数据到hash表 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="dataKey"></param> 
        /// <returns></returns> 
        public static bool Hash_Set<T>(string key, string dataKey, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 
                return redis.SetEntryInHash(key, dataKey, value); 
            } 
        } 
        /// <summary> 
        /// 移除hash中的某值 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="dataKey"></param> 
        /// <returns></returns> 
        public static bool Hash_Remove(string key, string dataKey) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.RemoveEntryFromHash(key, dataKey); 
            } 
        } 
        /// <summary> 
        /// 移除整个hash 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="dataKey"></param> 
        /// <returns></returns> 
        public static bool Hash_Remove(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.Remove(key); 
            } 
        } 
        /// <summary> 
        /// 从hash表获取数据 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="dataKey"></param> 
        /// <returns></returns> 
        public static T Hash_Get<T>(string key, string dataKey) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                string value = redis.GetValueFromHash(key, dataKey); 
                return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(value); 
            } 
        } 
        /// <summary> 
        /// 获取整个hash的数据 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <returns></returns> 
        public static List<T> Hash_GetAll<T>(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var list = redis.GetHashValues(key); 
                if (list != null && list.Count > 0) 
                { 
                    List<T> result = new List<T>(); 
                    foreach (var item in list) 
                    { 
                        var value = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item); 
                        result.Add(value); 
                    } 
                    return result; 
                } 
                return null; 
            } 
        } 
        /// <summary> 
        /// 设置缓存过期 
        /// </summary> 
        /// <param name="key"></param> 
        /// <param name="datetime"></param> 
        public static void Hash_SetExpire(string key, DateTime datetime) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                redis.ExpireEntryAt(key, datetime); 
            } 
        } 
        #endregion 
      
      
      
        #region -- SortedSet -- 
        /// <summary> 
        ///  添加数据到 SortedSet 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="t"></param> 
        /// <param name="score"></param> 
        public static bool SortedSet_Add<T>(string key, T t, double score) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 
                return redis.AddItemToSortedSet(key, value, score); 
            } 
        } 
        /// <summary> 
        /// 移除数据从SortedSet 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="t"></param> 
        /// <returns></returns> 
        public static bool SortedSet_Remove<T>(string key, T t) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 
                return redis.RemoveItemFromSortedSet(key, value); 
            } 
        } 
        /// <summary> 
        /// 修剪SortedSet 
        /// </summary> 
        /// <param name="key"></param> 
        /// <param name="size">保留的条数</param> 
        /// <returns></returns> 
        public static int SortedSet_Trim(string key, int size) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.RemoveRangeFromSortedSet(key, size, 9999999); 
            } 
        } 
        /// <summary> 
        /// 获取SortedSet的长度 
        /// </summary> 
        /// <param name="key"></param> 
        /// <returns></returns> 
        public static int SortedSet_Count(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                return redis.GetSortedSetCount(key); 
            } 
        } 
      
        /// <summary> 
        /// 获取SortedSet的分页数据 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="pageIndex"></param> 
        /// <param name="pageSize"></param> 
        /// <returns></returns> 
        public static List<T> SortedSet_GetList<T>(string key, int pageIndex, int pageSize) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);  
                if (list != null && list.Count > 0) 
                { 
                    List<T> result = new List<T>(); 
                    foreach (var item in list) 
                    { 
                        var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item); 
                        result.Add(data); 
                    } 
                    return result; 
                } 
            } 
            return null; 
        } 
      
      
        /// <summary> 
        /// 获取SortedSet的全部数据 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="pageIndex"></param> 
        /// <param name="pageSize"></param> 
        /// <returns></returns> 
        public static List<T> SortedSet_GetListALL<T>(string key) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                var list = redis.GetRangeFromSortedSet(key, 0, 9999999); 
                if (list != null && list.Count > 0) 
                { 
                    List<T> result = new List<T>(); 
                    foreach (var item in list) 
                    { 
                        var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item); 
                        result.Add(data); 
                    } 
                    return result; 
                } 
            } 
            return null; 
        } 
      
        /// <summary> 
        /// 设置缓存过期 
        /// </summary> 
        /// <param name="key"></param> 
        /// <param name="datetime"></param> 
        public static void SortedSet_SetExpire(string key, DateTime datetime) 
        { 
            using (IRedisClient redis = prcm.GetClient()) 
            { 
                redis.ExpireEntryAt(key, datetime); 
            } 
        } 
      
        //public static double SortedSet_GetItemScore<T>(string key,T t) 
        //{ 
        //    using (IRedisClient redis = prcm.GetClient()) 
        //    { 
        //        var data = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t); 
        //        return redis.GetItemScoreInSortedSet(key, data); 
        //    } 
        //    return 0; 
        //} 
      
        #endregion 
      
    } 
}

written by ocean

2月 06

首先简单说一下倒排序索引实现原理

0)设有两篇文章1和2

  文章1的内容为:Tom lives in Guangzhou,I live in Guangzhou too.

  文章2的内容为:He once lived in Shanghai.

  

  1)由于lucene是基于关键词索引和查询的,首先我们要取得这两篇文章的关键词,通常我们需要如下处理措施

  a.我们现在有的是文章内容,即一个字符串,我们先要找出字符串中的所有单词,即分词。英文单词由于用空格分隔,比较好处理。中文单词间是连在一起的需要特殊的分词处理。

  b.文章中的”in”, “once” “too”等词没有什么实际意义,中文中的“的”“是”等字通常也无具体含义,这些不代表概念的词可以过滤掉

  c.用户通常希望查“He”时能把含“he”,“HE”的文章也找出来,所以所有单词需要统一大小写。

  d.用户通常希望查“live”时能把含“lives”,“lived”的文章也找出来,所以需要把“lives”,“lived”还原成“live”

  e.文章中的标点符号通常不表示某种概念,也可以过滤掉

  在lucene中以上措施由Analyzer类完成

  

  经过上面处理后

   文章1的所有关键词为:[tom] [live] [guangzhou] [i] [live] [guangzhou]

   文章2的所有关键词为:[he] [live] [shanghai]

  

  2) 有了关键词后,我们就可以建立倒排索引了。上面的对应关系是:“文章号”对“文章中所有关键词”。倒排索引把这个关系倒过来,变成:“关键词”对“拥有该关键词的所有文章号”。文章1,2经过倒排后变成

  关键词 文章号

  guangzhou 1

  he 2

  i 1

  live 1,2

  shanghai 2

  tom 1

那么实现就很简单了,只要按字反查就行了

下面的代码是记录一下 www.wx6.org 在开发初期实现的查询方式,只做代码备忘

创建索引方法

    /// <summary> 
            /// 合并索引 
            /// </summary> 
            public void Step3_HeBingIndex() 
            { 
                List<Tuple<string, string>> list = this.GetIndexData(); 
                StringBuilder sb = new StringBuilder(); 
                StringBuilder sbIndex = new StringBuilder(); 
                int total = 3; 
  
                foreach (var item in list) 
                { 
                    string current = item.Item2; 
                    int length = System.Text.Encoding.UTF8.GetBytes(current).Length; 
  
                    string indexString = item.Item1 + "," + total + "," + length + ","; 
                    indexString = BuQiIndex2FixLength(indexString, FIX_LENGTH_IndexIndex); 
                    sb.Append(current); 
                    sbIndex.Append(indexString); 
                    total += length; 
                } 
                File.WriteAllText(Path_Index, sb.ToString(), Encoding.UTF8); 
                File.WriteAllText(Path_IndexIndex, sbIndex.ToString(), Encoding.UTF8); 
            } 
  
            /// <summary> 
            /// 获取索引的数据 
            /// </summary> 
            /// <returns></returns> 
            private List<Tuple<string, string>> GetIndexData() 
            { 
                List<Tuple<string, string>> list = new List<Tuple<string, string>>(); 
                var xjw = File.ReadAllLines(@"f:\X字结尾的诗句.txt", Encoding.UTF8); 
                foreach (var item in xjw) 
                { 
                    if (item.Length > 5) 
                    { 
                        string key = item.Split(',')[0]; 
                        list.Add(new Tuple<string, string>(key, item)); 
                    } 
                }  
                list.Sort((a, b) => a.Item1.CompareTo(b.Item1)); 
                return list; 
            } 
  
  
  
            /// <summary> 
            /// 补齐定长 
            /// </summary> 
            /// <param name="word"></param> 
            /// <param name="lenth"></param> 
            /// <returns></returns> 
            private string BuQiIndex2FixLength(string word, int lenth) 
            { 
                int currentLength = System.Text.Encoding.UTF8.GetBytes(word).Length; 
                if (currentLength > lenth) 
                    throw new Exception("超过最长索引"); 
  
                int n = lenth - currentLength; 
                for (int i = 0; i < n; i++) 
                { 
                    word += "="; 
                } 
                return word; 
            } 
        }

查询索引方法

            /// <summary> 
    /// 合并索引 
    /// </summary> 
    public void Step3_HeBingIndex() 
    { 
        List<Tuple<string, string>> list = this.GetIndexData(); 
        StringBuilder sb = new StringBuilder(); 
        StringBuilder sbIndex = new StringBuilder(); 
        int total = 3; 
 
        foreach (var item in list) 
        { 
            string current = item.Item2; 
            int length = System.Text.Encoding.UTF8.GetBytes(current).Length; 
 
            string indexString = item.Item1 + "," + total + "," + length + ","; 
            indexString = BuQiIndex2FixLength(indexString, FIX_LENGTH_IndexIndex); 
            sb.Append(current); 
            sbIndex.Append(indexString); 
            total += length; 
        } 
        File.WriteAllText(Path_Index, sb.ToString(), Encoding.UTF8); 
        File.WriteAllText(Path_IndexIndex, sbIndex.ToString(), Encoding.UTF8); 
    } 
 
    /// <summary> 
    /// 获取索引的数据 
    /// </summary> 
    /// <returns></returns> 
    private List<Tuple<string, string>> GetIndexData() 
    { 
        List<Tuple<string, string>> list = new List<Tuple<string, string>>(); 
        var xjw = File.ReadAllLines(@"f:\X字结尾的诗句.txt", Encoding.UTF8); 
        foreach (var item in xjw) 
        { 
            if (item.Length > 5) 
            { 
                string key = item.Split(',')[0]; 
                list.Add(new Tuple<string, string>(key, item)); 
            } 
        }  
        list.Sort((a, b) => a.Item1.CompareTo(b.Item1)); 
        return list; 
    } 
 
 
 
    /// <summary> 
    /// 补齐定长 
    /// </summary> 
    /// <param name="word"></param> 
    /// <param name="lenth"></param> 
    /// <returns></returns> 
    private string BuQiIndex2FixLength(string word, int lenth) 
    { 
        int currentLength = System.Text.Encoding.UTF8.GetBytes(word).Length; 
        if (currentLength > lenth) 
            throw new Exception("超过最长索引"); 
 
        int n = lenth - currentLength; 
        for (int i = 0; i < n; i++) 
        { 
            word += "="; 
        } 
        return word; 
    } 
} 
#endregion 
 
 
public class Query 
{ 
 
 
    /// <summary> 
    /// 通过索引获取诗句 
    /// </summary> 
    /// <param name="start"></param> 
    /// <param name="length"></param> 
    /// <returns></returns> 
    public string GetDataSourceByIndex(int start, int length) 
    { 
        using (FileStream fs = File.OpenRead(PoetryIndex.Path_Source)) 
        { 
            byte[] b = new byte[length]; 
            UTF8Encoding temp = new UTF8Encoding(); 
            fs.Seek(start, SeekOrigin.Begin); 
            fs.Read(b, 0, length); 
            return temp.GetString(b); 
        } 
    } 
 
    /// <summary> 
    /// 通过ID获取诗句索引 
    /// </summary> 
    /// <param name="id"></param> 
    /// <returns></returns> 
    public string GetDataSourceIndexById(int id) 
    { 
        int start = id * FIX_LENGTH_DataSourceIndex + 3; 
        return this.GetStringFromStreamSeek(start, FIX_LENGTH_DataSourceIndex, PoetryIndex.Path_SourceIndex); 
    } 
 
    /// <summary> 
    /// 获取古诗实体,根据ID 
    /// </summary> 
    /// <param name="id"></param> 
    /// <returns></returns> 
    public PoetryStoreInfo GetDataSourceById(int id) 
    { 
        if (id < 0 || id > DATASOURCE_COUNT - 1)//无效ID 
            return null; 
        string[] indexString = this.GetDataSourceIndexById(id).Split(','); 
        string dataScoure = this.GetDataSourceByIndex(int.Parse(indexString[1]), int.Parse(indexString[2])); 
        if (dataScoure != null) 
        { 
            var data = dataScoure.Split('|'); 
            PoetryStoreInfo poetryStoreInfo = new PoetryStoreInfo(); 
            poetryStoreInfo.Id = id; 
            poetryStoreInfo.Content = data[3]; 
            poetryStoreInfo.Name = data[1]; 
            poetryStoreInfo.Author = data[2]; 
            poetryStoreInfo.Url = data[0]; 
            return poetryStoreInfo; 
        } 
        return null; 
    } 
 
 
 
 
 
    /// <summary> 
    /// 搜索 
    /// </summary> 
    /// <param name="word"></param> 
    /// <returns></returns> 
    public List<PoetryStoreInfo> Search(string word) 
    { 
        string indexIndexStream = this.ErFenFaSearch(word); 
        if (indexIndexStream == null)//没找到 
            return null; 
        var tmp = indexIndexStream.Split(','); 
        string indexStream = this.GetStringFromStreamSeek(int.Parse(tmp[1]), int.Parse(tmp[2]), Path_Index); 
        var ids = indexStream.Split(','); 
        List<PoetryStoreInfo> result = new List<PoetryStoreInfo>(); 
        for (int i = 1; i < ids.Length; i++) 
        { 
            PoetryStoreInfo poetryStoreInfo = this.GetDataSourceById(int.Parse(ids[i])); 
            if (poetryStoreInfo != null) 
            { 
                result.Add(poetryStoreInfo); 
            } 
        } 
        return result; 
    } 
    /// <summary> 
    /// 搜索,带分页 
    /// </summary> 
    /// <param name="word"></param> 
    /// <param name="pageIndex"></param> 
    /// <param name="pageSize"></param> 
    /// <param name="totalRec"></param> 
    /// <returns></returns> 
    public List<PoetryStoreInfo> Search(string word, int pageIndex, int pageSize, out int totalRec) 
    { 
        totalRec = 0; 
        string indexIndexStream = this.ErFenFaSearch(word); 
        if (indexIndexStream == null)//没找到 
            return null; 
        var tmp = indexIndexStream.Split(','); 
        string indexStream = this.GetStringFromStreamSeek(int.Parse(tmp[1]), int.Parse(tmp[2]), Path_Index); 
        var ids = indexStream.Split(','); 
        totalRec = ids.Length - 1; 
        List<PoetryStoreInfo> result = new List<PoetryStoreInfo>(); 
        int start = (pageIndex - 1) * pageSize + 1; 
        int end = pageSize * pageIndex + 1; 
        for (int i = start; i < ids.Length && i < end; i++) 
        { 
            PoetryStoreInfo poetryStoreInfo = this.GetDataSourceById(int.Parse(ids[i])); 
            if (poetryStoreInfo != null) 
            { 
                result.Add(poetryStoreInfo); 
            } 
        } 
        return result; 
    } 
 
 
    /// <summary> 
    /// 通过二分法查找索引的文件流信息 
    /// </summary> 
    /// <param name="word"></param> 
    /// <returns></returns> 
    private string ErFenFaSearch(string word) 
    { 
        int low, high, mid; 
        low = 0; 
        high = DATAINDEX_COUNT - 1; 
        while (low <= high) 
        { 
            mid = (low + high) / 2; 
            string current = this.GetStringFromStreamSeek(3 + mid * FIX_LENGTH_IndexIndex, FIX_LENGTH_IndexIndex, PoetryIndex.Path_IndexIndex); 
 
            if (current.Length > 0) 
            { 
                int flag = word.CompareTo((current.Split(',')[0])); 
                if (flag > 0) 
                { 
                    low = mid + 1; 
                } 
                else if (flag < 0) 
                { 
                    high = mid - 1; 
                } 
                else
                { 
                    return current; 
                } 
            } 
            else
            { 
                break; 
            } 
        } 
        return null; 
    } 
 
 
    /// <summary> 
    /// 通过指针定位获取文件流字符串 
    /// </summary> 
    /// <param name="start"></param> 
    /// <param name="length"></param> 
    /// <param name="path"></param> 
    /// <returns></returns> 
    public string GetStringFromStreamSeek(int start, int length, string path) 
    { 
        using (FileStream fs = File.OpenRead(path)) 
        { 
            byte[] b = new byte[length]; 
            UTF8Encoding temp = new UTF8Encoding(); 
            fs.Seek(start, SeekOrigin.Begin); 
            fs.Read(b, 0, length); 
            return temp.GetString(b); 
        } 
    }
    


written by ocean

2月 05

发现自己做个博客的话还是挺有好处的,最主要是一切完全自己可控,需要什么功能只要加上就可以了

先说一下今天发现的问题吧

我用的ueditor,后台本身有代码插入的功能,用的是SyntaxHighlighter的组件,后台显示OK的,但是到了前台就没有了

是少引用了shCore.js和shCoreDefault.css的文件

前台添加一下引用,OK,代码着色了

但是等等,每个页面都需要这样加载这两个文件么?如果某篇文章没有代码,这不是浪费掉了么?

于是想起以前写过的一篇博客 Javascript,CSS动态加载 OK

那么思路就很简单了,判断代码中是否含有pre,也就是代码着色的块,如果有的话就动态加载代码着色的文件实现着色

这一段很简单就不写了,另外如果真要看的话

右键查看一下本文的源代码就好啦

另外,压缩只是为了节省流量

还是记录一下

    function Import(path, type, title) { 
    var s, i; 
    if (!type) type = path.substr(path.lastIndexOf(".") + 1); 
    if (type == "js") { 
        var ss = document.getElementsByTagName("script"); 
        for (i = 0; i < ss.length; i++) { 
            if (ss[i].src && ss[i].src.indexOf(path) != -1 || ss[i].title == title) return ss[i]; 
        } 
        s = document.createElement("script"); 
        s.type = "text/javascript"; 
        s.src = path; 
        if (title) s.title = title; 
    } 
    else if (type == "css") { 
        var ls = document.getElementsByTagName("link"); 
        for (i = 0; i < ls.length; i++) { 
            if (ls[i].href && ls[i].href.indexOf(path) != -1 || ls[i].title == title) return ls[i]; 
        } 
        s = document.createElement("link"); 
        s.rel = "stylesheet"; 
        s.type = "text/css"; 
        s.href = path; 
        if (title) s.title = title; 
        s.disabled = false; 
    } 
    else return; 
    var head = document.getElementsByTagName("head")[0]; 
    head.appendChild(s); 
    return s; 
} 
if (document.getElementsByTagName("pre")!=null) { 
    Import("/template/syntaxhighlighter/shcoredefault.css", "css"); 
    Import("/template/syntaxhighlighter/shcore.js", "js");  
}

written by ocean

2月 05

FileStream 可以随机读写文件 使用 Seek 方法

Seek() ———-有两个参数 第一参数规定文件指针以字节为单位移动的距离。第二个参数规定开始计算的位置

用 SeekOrigin 枚举的一个值表示 : SeekOrigin 有三个值:Begin Current End。

aFile.Seek(8,SeekOrigin.Begin)———将文件的指针移动到第八个字节。起始位置就是文件的第一个字节。

aFile.Seek(-5,SeekOrigin.End); 从文件的末尾向前查找五个字节。。

aFile.Seek(2,SeekOrigin.Current);

封装了一个函数,知道文本首位就可以快速读取

    /// <summary> 
         /// 通过指针定位获取文件流字符串 
         /// </summary> 
         /// <param name="start"></param> 
         /// <param name="length"></param> 
         /// <param name="path"></param> 
         /// <returns></returns> 
         public string GetStringFromStreamSeek(int start, int length, string path) 
         { 
             using (FileStream fs = File.OpenRead(path)) 
             { 
                 byte[] b = new byte[length]; 
                 UTF8Encoding temp = new UTF8Encoding(); 
                 fs.Seek(start, SeekOrigin.Begin); 
                 fs.Read(b, 0, length); 
                 return temp.GetString(b); 
             } 
         }

written by ocean

2月 04

之前一直用的百度Hi的,可惜非要强制升级.

升级也就算了,最最关键的居然自己的博客自己不能搜,太扯淡了

那个产品经理就该拉出去毙了

博客独立了,不用之前的了

庆祝一下

域名 http://blog.wx6.org

 

written by ocean