每次我部署一个MVC web应用程序,我的服务器都必须重新缓存所有js和css捆绑包。
因此,在部署后,第一次查看需要几秒钟才能呈现。
有什么方法可以预缓存捆绑包吗?毕竟,这些文件在编译时是静态的。
因此,在部署后,第一次查看需要几秒钟才能呈现。
有什么方法可以预缓存捆绑包吗?毕竟,这些文件在编译时是静态的。
为了解决问题,我们用能够持久化缓存的方式替代了默认内存缓存。
我们通过继承ScriptBundle
并重写CacheLookup()
和UpdateCache()
方法来实现这一点。
/// <summary>
/// override cache functionality in ScriptBundle to use
/// persistent cache instead of HttpContext.Current.Cache
/// </summary>
public class ScriptBundleUsingPersistentCaching : ScriptBundle
{
public ScriptBundleUsingPersistentCaching(string virtualPath)
: base(virtualPath)
{ }
public ScriptBundleUsingPersistentCaching(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{ }
public override BundleResponse CacheLookup(BundleContext context)
{
//custom cache read
}
public override void UpdateCache(BundleContext context, BundleResponse response)
{
//custom cache save
}
}
值得一提的另一个问题与我们持久缓存工具有关。为了进行缓存,我们必须拥有一个可序列化对象。不幸的是,BundleResponse
没有标记为 Serializable
。
我们的解决方案是创建一个小型实用程序类,将BundleResponse
分解为其值类型。这样做后,我们就可以序列化实用程序类。然后,在从缓存中检索时,我们会重建 BundleResponse
。