By default, GroupDocs.Viewer implements caching to local. But you can cache rendering result in your own way, for example, using Redis Cache. To do this, use the ICache interface implementation.
The following code snippet shows how to implement a custom caching using Redis Cache:
usingSystem;usingSystem.IO;usingSystem.Linq;usingSystem.Diagnostics;usingSystem.Collections.Generic;usingSystem.Xml.Serialization;usingGroupDocs.Viewer.Caching;usingGroupDocs.Viewer.Options;usingGroupDocs.Viewer;usingStackExchange.Redis;// ...// Specify the cache parameters.varserverAddress="127.0.0.1:6379";varfilePath="sample.docx";// Create the cache.RedisCachecache=newRedisCache(serverAddress,filePath);ViewerSettingssettings=newViewerSettings(cache);using(Viewerviewer=newViewer(filePath,settings)){// Create HTML files.HtmlViewOptionsviewOptions=HtmlViewOptions.ForEmbeddedResources();// Display rendering time.PrintTimeTaken(()=>viewer.View(viewOptions),"The first call to View method took {0} ms.");// Display time to get cached results.PrintTimeTaken(()=>viewer.View(viewOptions),"The second call to View method took {0} ms.");}// Get and display time taken.staticvoidPrintTimeTaken(Actionaction,stringformat){Stopwatchstopwatch=newStopwatch();stopwatch.Start();action.Invoke();stopwatch.Stop();Console.WriteLine(format,stopwatch.ElapsedMilliseconds);}publicclassRedisCache:ICache,IDisposable{privatereadonlystring_cacheKeyPrefix;privatereadonlyConnectionMultiplexer_redis;privatereadonlyIDatabase_db;privatereadonlystring_host;publicRedisCache(stringhost,stringcacheKeyPrefix){_host=host;_cacheKeyPrefix=cacheKeyPrefix;_redis=ConnectionMultiplexer.Connect(_host);_db=_redis.GetDatabase();}publicvoidSet(stringkey,objectdata){if(data==null)return;stringprefixedKey=GetPrefixedKey(key);MemoryStreammemoryStream=null;if(dataisStream){memoryStream=dataisMemoryStream?dataasMemoryStream:CopyToMemoryStream(dataasStream);}else{memoryStream=newMemoryStream();XmlSerializerserializer=newXmlSerializer(data.GetType());serializer.Serialize(memoryStream,data);}_db.StringSet(prefixedKey,RedisValue.CreateFrom(memoryStream));}privateMemoryStreamCopyToMemoryStream(Streamdata){MemoryStreamresult=newMemoryStream();data.Position=0;data.CopyTo(result);returnresult;}publicboolTryGetValue<TEntry>(stringkey,outTEntryvalue){varprefixedKey=GetPrefixedKey(key);varredisValue=_db.StringGet(prefixedKey);if(redisValue.HasValue){vardata=typeof(TEntry)==typeof(Stream)?ReadStream(redisValue):Deserialize<TEntry>(redisValue);value=(TEntry)data;returntrue;}value=default;returnfalse;}publicIEnumerable<string>GetKeys(stringfilter){return_redis.GetServer(_host).Keys(pattern:$"*{filter}*").Select(x=>x.ToString().Replace(_cacheKeyPrefix,string.Empty)).Where(x=>x.StartsWith(filter,StringComparison.InvariantCultureIgnoreCase)).ToList();}privatestringGetPrefixedKey(stringkey)=>$"{_cacheKeyPrefix}{key}";privateobjectReadStream(RedisValueredisValue)=>newMemoryStream(redisValue);privateTDeserialize<T>(RedisValueredisValue){objectdata;using(MemoryStreamstream=newMemoryStream(redisValue)){XmlSerializerserializer=newXmlSerializer(typeof(T));try{data=serializer.Deserialize(stream);}catch(InvalidOperationException){data=null;}catch(NullReferenceException){data=null;}}return(T)data;}publicvoidDispose(){_redis.Dispose();}}
ImportsSystemImportsSystem.IOImportsSystem.LinqImportsSystem.DiagnosticsImportsSystem.Collections.GenericImportsSystem.Runtime.InteropServicesImportsSystem.Xml.SerializationImportsGroupDocs.Viewer.CachingImportsGroupDocs.Viewer.OptionsImportsGroupDocs.ViewerImportsStackExchange.RedisModuleProgramPublicSubMain()' Specify the cache parameters.
DimserverAddressAsString="127.0.0.1:6379"DimfilePathAsString="sample.docx"' Create the cache.
DimcacheAsRedisCache=NewRedisCache(serverAddress,filePath)DimsettingsAsViewerSettings=NewViewerSettings(cache)UsingviewerAsViewer=NewViewer(filePath,settings)' Create HTML files.
DimviewOptionsAsHtmlViewOptions=HtmlViewOptions.ForEmbeddedResources()' Display rendering time.
PrintTimeTaken(Sub()viewer.View(viewOptions),"The first call to View method took {0} ms.")' Display time to get cached results.
PrintTimeTaken(Sub()viewer.View(viewOptions),"The second call to View method took {0} ms.")EndUsingEndSub' Get and display time taken.
PrivateSubPrintTimeTaken(actionAsAction,formatAsString)DimstopwatchAsStopwatch=NewStopwatch()stopwatch.Start()action.Invoke()stopwatch.Stop()Console.WriteLine(format,stopwatch.ElapsedMilliseconds)EndSubPublicClassRedisCacheImplementsICache,IDisposablePrivateReadOnly_cacheKeyPrefixAsStringPrivateReadOnly_redisAsConnectionMultiplexerPrivateReadOnly_dbAsIDatabasePrivateReadOnly_hostAsStringPublicSubNew(hostAsString,cacheKeyPrefixAsString)_host=host_cacheKeyPrefix=cacheKeyPrefix_redis=ConnectionMultiplexer.Connect(_host)_db=_redis.GetDatabase()EndSubPrivateFunctionCopyToMemoryStream(dataAsStream)AsMemoryStreamDimresultAsNewMemoryStream()data.Position=0data.CopyTo(result)ReturnresultEndFunctionPublicSub[Set](keyAsString,valueAsObject)ImplementsICache.[Set]IfvalueIsNothingThenReturnEndIfDimprefixedKeyAsString=GetPrefixedKey(key)DimmemoryStreamAsMemoryStream=NothingIfTypeOfvalueIsStreamThenmemoryStream=If(TypeOfvalueIsMemoryStream,DirectCast(value,MemoryStream),CopyToMemoryStream(DirectCast(value,Stream)))ElsememoryStream=NewMemoryStream()DimserializerAsNewXmlSerializer(value.GetType())serializer.Serialize(memoryStream,value)EndIf_db.StringSet(prefixedKey,RedisValue.CreateFrom(memoryStream))EndSubPublicFunctionTryGetValue(OfTEntry)(keyAsString,<Out>ByRefvalueAsTEntry)AsBooleanImplementsICache.TryGetValueDimprefixedKeyAsString=GetPrefixedKey(key)DimredisValueAsRedisValue=_db.StringGet(prefixedKey)IfredisValue.HasValueThenDimdataAsObject=If(GetType(TEntry)=GetType(Stream),ReadStream(redisValue),Deserialize(OfTEntry)(redisValue))value=DirectCast(data,TEntry)ReturnTrueEndIfvalue=NothingReturnFalseEndFunctionPublicFunctionICache_GetKeys(filterAsString)AsIEnumerable(OfString)ImplementsICache.GetKeysReturn_redis.GetServer(_host).Keys(pattern:=$"*{filter}*").Select(Function(x)x.ToString().Replace(_cacheKeyPrefix,String.Empty)).Where(Function(x)x.StartsWith(filter,StringComparison.InvariantCultureIgnoreCase)).ToList()EndFunctionPrivateFunctionGetPrefixedKey(keyAsString)AsStringReturn$"{_cacheKeyPrefix}{key}"EndFunctionPrivateFunctionReadStream(redisValueAsRedisValue)AsObjectReturnNewMemoryStream(redisValue)EndFunctionPrivateFunctionDeserialize(OfT)(redisValueAsRedisValue)AsTDimdataAsObjectUsingstreamAsNewMemoryStream(redisValue)DimserializerAsNewXmlSerializer(GetType(T))Trydata=serializer.Deserialize(stream)CatchexAsInvalidOperationExceptiondata=NothingCatchexAsNullReferenceExceptiondata=NothingEndTryEndUsingReturnDirectCast(data,T)EndFunctionPublicSubDispose()_redis.Dispose()EndSubPublicSubIDisposable_Dispose()ImplementsIDisposable.DisposeThrowNewNotImplementedExceptionEndSubEndClassEndModule
The following image shows a sample console output:
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.