在web应用程序中,我们可以使用Session与Application对象来缓存数据,但是有时session多了,会出现session丢失的情况,而且当访问量大时,服务器会不堪重负。
这时我们可以考虑用磁盘来作为缓存,但是这样做的前提是,同时访问的用户不能过多,对于企业内部的基于WEB的应用程序,这样的做法还是可行的。
在此例子中,数据的格式以DataSet为例,其它的数据可以序列化后,再保存
具体的实现代码如下:
public class SessionXML
{
private string cachePath;
/// <summary>
/// 缓存所在的路径,不要以“/”结尾
/// </summary>
public string CachePath
{
get{return this.cachePath;}
set
{
if(!Directory.Exists(value))
System.IO.Directory.CreateDirectory(value);
this.cachePath = value;
}
}
private string cacheFileName;
/// <summary>
/// 缓存所用的文件,也可以
/// </summary>
public string CacheFileName
{
get{return this.cacheFileName;}
set
{
if(this.cachePath=="")
throw(new System.IO.DirectoryNotFoundException("对于SessionXML对象,没有先指定
CachePath属性"));
//创建新缓存文件
if(!File.Exists(this.cachePath + "//" + value))
File.Create(this.cachePath + "//" + value).Close();
//删掉旧的缓存文件
if(!File.Exists(this.cachePath + "//" + this.cacheFileName))
{
try
{
File.Delete(this.cachePath + "//" + this.cacheFileName);
}
catch(System.Exception)
{}
}
this.cacheFileName = value;
}
}
private System.Data.DataSet sourceDataSet;
/// <summary>
/// 当前要缓存的数据,以DATASET来保存,有些对象也可以序列化后再保存
/// </summary>
public System.Data.DataSet SourceDataSet
{
get{return this.sourceDataSet;}
set{this.sourceDataSet = value;}
}
/// <summary>
/// 当前缓存文件的完整的含路径的文件名[只读]
/// </summary>
public string FullPath
{
get{return this.cachePath + "//" + this.cacheFileName;}
}
/// <summary>
/// 创建磁盘文件来缓存
/// </summary>
public SessionXML()
{
this.sourceDataSet = new DataSet();
}
/// <summary>
///
/// </summary>
/// <param name="cachefilename">指定的缓存的路径</param>
/// <param name="sname">指定的缓存名称</param>
public SessionXML(string cachepath,string cachefilename)
{
this.sourceDataSet = new DataSet();
this.CachePath = cachepath;
this.CacheFileName = cachefilename;
}
/// <summary>
/// 取回缓存
/// </summary>
public void GetCacheData()
{
this.sourceDataSet.ReadXml(this.cachePath + "//" + this.cacheFileName);
}
/// <summary>
/// 保存缓存
/// </summary>
/// <param name="sourcedataset">要保存的数据集</param>
public void SetCacheData(System.Data.DataSet sourcedataset)
{
this.sourceDataSet = sourcedataset;
this.sourceDataSet.WriteXml(this.cachePath + "//" + this.cacheFileName);
}
/// <summary>
/// 保存缓存
/// </summary>
public void SetCacheData()
{
this.sourceDataSet.WriteXml(this.cachePath + "//" + this.cacheFileName);
}
/// <summary>
/// 清除当前缓存
/// </summary>
public void Clear()
{
File.Delete(this.cachePath + "//" + this.cacheFileName);
}
}