c#使用redis 存取dataset数据集

//1.下面是关于c# 使用redis数据库 对dataset进行存取操作的方法
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;

namespace redisHelper
{
    public class RedisHelper 
    {
        private static RedisClient Redis =null;

        static RedisHelper()
        {
            Redis = new RedisClient("127.0.0.1", 6379);
        }
        /// 
        /// 插入DATASET缓存
        /// 
        /// 缓存键
        /// 缓存对象
        /// 过期时间(分钟)
        public static void SetMemByDataSet(string key, DataSet ds, int minute)
        {

            DateTime expiryTime = DateTime.Now.AddMinutes(minute);
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();//定义BinaryFormatter以序列化DataSet对象   
            System.IO.MemoryStream ms = new System.IO.MemoryStream();//创建内存流对象   
            formatter.Serialize(ms, ds);//把DataSet对象序列化到内存流   
            byte[] buffer = ms.ToArray();//把内存流对象写入字节数组   
            ms.Close();//关闭内存流对象   
            ms.Dispose();//释放资源   
            Redis.Set(key, buffer, expiryTime);
        }
        public static object Get(string key)
        {
            byte[] buffer = Redis.Get(key);

            return GetObjFromBytes(buffer);
        }
        /// 
        /// 从二进制流得到对象(data专用,data数据要序列化为二进制才可保存)
        /// 
        /// 
        /// 
        private static object GetObjFromBytes(byte[] buffer)
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer))
            {
                stream.Position = 0;
                System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                Object reobj = bf.Deserialize(stream);
                return reobj;
            }
        }
        public static DataSet GetMemByDataSet(string key)
        {
            var item = Get(key);
            return (DataSet)item;
        }

        
        
    }
}

下面是页面进行gridview绑定数据的代码

  protected void btnQuery_Click(object sender, EventArgs e)
    {
        String enableFlag = DropFlag.SelectedValue.ToString();
      
        DataSet ds = null;
        try
        {
           // ds = GetMemByDataSet(enableFlag);
            ds = redisHelper.RedisHelper.GetMemByDataSet(enableFlag);
        }
      
        catch(Exception ex)
        {
           ds = Coeno.Vocation.VocationTypes.QueryColTypeList(enableFlag);
           //SetMemByDataSet(enableFlag, ds, 1);
           redisHelper.RedisHelper.SetMemByDataSet(enableFlag, ds, 60);
        }
        GridView2.DataSource = ds;
        GridView2.DataBind();           
    }



你可能感兴趣的:(数据库操作,编程,数据库,redis,c#,dataset)