First, you need to be sure that you have the latest version of Cosmos SDK in your solution. Currently, preview version has the integrated cache options. Other versions will work too as long as you use Eventual Consistency for you request. You can not change Integrated Cache options with the older versions of SDK.
Next, you want to be sure that you are using dedicated gateway server connection string. You can find them in Keys section. If you do not see dedicated gateway connection strings, that means you haven't enabled the dedicated gateway server. Check out my older post to see how to enable it.
We are ready to write some code now. Integrated Cache works only in Eventual Consistency for now. So, we need to send requests in Eventual consistency to test the Integrated Cache. To do that, we need to use requestOptions parameter in SDK. You can change your database consistency level to Eventual too for testing if you like. Don't forget to change it back later!
static async Task<List<StackOverflowPost>> TestCaching(int postid=0)
{
var cosmosClient = new CosmosClient(connectionString,
new CosmosClientOptions { ConnectionMode= ConnectionMode.Gateway});
Container container = cosmosClient.GetContainer("Stackoverflow", "Posts");
var cmd = "SELECT * FROM Posts o WHERE o.PostId < 500";
var query = new QueryDefinition(cmd);
var queryResultSetIterator = container.GetItemQueryIterator<StackOverflowPost>(query,
requestOptions: new QueryRequestOptions
{
ConsistencyLevel = ConsistencyLevel.Eventual,
DedicatedGatewayRequestOptions = new DedicatedGatewayRequestOptions
{
MaxIntegratedCacheStaleness = TimeSpan.FromMinutes(30)
}
}
);
var posts = new List<StackOverflowPost>();
double rq = 0;
try
{
while (queryResultSetIterator.HasMoreResults)
{
FeedResponse<StackOverflowPost> currentResultSet = await queryResultSetIterator.ReadNextAsync();
rq += currentResultSet.RequestCharge;
foreach (StackOverflowPost current in currentResultSet)
{
posts.Add(current);
}
}
Console.WriteLine("Number of Posts : " + posts.Count);
Console.WriteLine("Request Units : " + rq);
return posts;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
return null;
}
}
This code runs a query and returns 592 documents. To cache this data, first you need to be sure that you are using your dedicated gateway server's connection string and use the ConnectionMode.Gateway when you declare CosmosClient object. Then you need to change your request's consistency level to Eventual.
If you like to control how long data should be cached in Dedicated Gateway server, you can use the DedicatedGatewayRequestedOptions to control the amount of time.
First time I run the code and it costed 32.95 Request Units
Next 30 minutes, this request will cost me 0 Request Units thanks to Integrated Cache.
No comments:
Post a Comment