GroupDocs.Conversion implements caching to local drive out of the box. For flexibility GroupDocs.Conversion provides and extension point which allows you to cache conversion result in your own way. You can do this by using ICache interface implementation. Let’s see how to implement some custom cache implementation using this extension point.
Using Redis cache
To implement the Redis cache, follow these steps:
Create RedisCache class which implements ICache interface
Instantiate the RedisCache class
Declare a delegate which will be used from Converter classes factory of ConverterSettings. In the body of this delegate, instantiate ConverterSettings class and set property Cache with the RedisCache class instance from previous step
Instantiate Converter class with path to source document and the delegate from the previous step as constructor’s parameters
Below is the code that demonstrates how to use custom caching for GroupDocs.Conversion.
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.IO;usingSystem.Linq;usingSystem.Reflection;usingSystem.Runtime.Serialization;usingSystem.Runtime.Serialization.Formatters.Binary;usingGroupDocs.Conversion.Caching;usingGroupDocs.Conversion.Options.Convert;usingStackExchange.Redis;namespaceGroupDocs.Conversion.Examples.CSharp.AdvancedUsage.Caching{internalclassHowToUseCustomCacheImplementation{/// <summary>/// This example demonstrates how to implement custom cache when rendering document./// </summary>publicstaticvoidRun(){stringoutputDirectory=Constants.GetOutputDirectoryPath();RedisCachecache=newRedisCache("sample_");Contracts.Func<ConverterSettings>settingsFactory=()=>newConverterSettings{Cache=cache};using(Converterconverter=newConverter(Constants.SAMPLE_DOCX,settingsFactory)){PdfConvertOptionsoptions=newPdfConvertOptions();StopwatchstopWatch=Stopwatch.StartNew();converter.Convert("converted.pdf",options);stopWatch.Stop();Console.WriteLine("Time taken on first call to Convert method {0} (ms).",stopWatch.ElapsedMilliseconds);stopWatch.Restart();converter.Convert("converted-1.pdf",options);stopWatch.Stop();Console.WriteLine("Time taken on second call to Convert method {0} (ms).",stopWatch.ElapsedMilliseconds);}Console.WriteLine($"\nSource document rendered successfully.\nCheck output in {outputDirectory}.");}}publicclassRedisCache:ICache,IDisposable{privatereadonlystring_cacheKeyPrefix;privatereadonlyConnectionMultiplexer_redis;privatereadonlyIDatabase_db;privatereadonlystring_host="192.168.0.1:6379";publicRedisCache(stringcacheKeyPrefix){_cacheKeyPrefix=cacheKeyPrefix;_redis=ConnectionMultiplexer.Connect(_host);_db=_redis.GetDatabase();}publicvoidSet(stringkey,objectdata){if(data==null)return;stringprefixedKey=GetPrefixedKey(key);using(MemoryStreamstream=GetStream(data)){_db.StringSet(prefixedKey,RedisValue.CreateFrom(stream));}}publicboolTryGetValue(stringkey,outobjectvalue){varprefixedKey=GetPrefixedKey(key);varredisValue=_db.StringGet(prefixedKey);if(redisValue.HasValue){vardata=Deserialize(redisValue);value=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}";privateobjectDeserialize(RedisValueredisValue){objectdata;using(MemoryStreamstream=newMemoryStream(redisValue)){BinaryFormatterformatter=newBinaryFormatter{Binder=newIgnoreAssemblyVersionSerializationBinder()};try{data=formatter.Deserialize(stream);}catch(SerializationException){data=null;}}returndata;}privateMemoryStreamGetStream(objectdata){MemoryStreamresult=newMemoryStream();if(dataisStreamstream){stream.Position=0;stream.CopyTo(result);}else{BinaryFormatterformatter=newBinaryFormatter();formatter.Serialize(result,data);}returnresult;}publicvoidDispose(){_redis.Dispose();}privateclassIgnoreAssemblyVersionSerializationBinder:SerializationBinder{publicoverrideTypeBindToType(stringassemblyName,stringtypeName){stringassembly=Assembly.GetExecutingAssembly().FullName;Typetype=Type.GetType($"{typeName}, {assembly}");returntype;}}}}
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.