DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Scaling Databases With EclipseLink And Redis
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Graph API for Entra ID (Azure AD) Object Management
  • Caching RESTful API Requests With Heroku Data for Redis

Trending

  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Simple Sophisticated Object Cache Service Using Azure Redis

Simple Sophisticated Object Cache Service Using Azure Redis

Cache service has been an integral part of major distributed systems. So let's dive deep into how to build a sophisticated object cache service using Redis.

By 
Srivatsan Balakrishnan user avatar
Srivatsan Balakrishnan
·
Jan. 23, 23 · Code Snippet
Likes (1)
Comment
Save
Tweet
Share
2.9K Views

Join the DZone community and get the full member experience.

Join For Free

The usage of cache has evolved a long way from simple string key-value pair to a string key to any object. Each application scenario demands the usage of cache in a different way. Most of the applications want to partition cache and reuse in other microservices or other parts of the system at the granular level. We will dive into detail about implementing a sophisticated object cache service at a granular level using Azure Redis in C#.

Prerequisites:

  1. Access to the Azure portal.
  2. Azure Redis provisioned of desired SKU.

The main objective of object storing is to set and get objects. But depending on application scenarios, usage of cache needs to be partitioned at the granular level. So let's define three variants of object store API.

API to: 

  1. Global cache
  2. Partition cache by single key to add more distribution and uniqueness.
  3. Partition cache by double key to add even more distribution and uniqueness.
C#
 
[ApiController]
[Route("api/objectcache")]
public class ObjectCacheController : ControllerBase
{
  
  
 // Simple global cache to set
  [HttpPost]
  public async Task<bool> Set ([FromBody] object value, [FromQuery] string key)
  {
  }

  // Simple global cache to get
  [HttpGet]
  public async Task<object> Get ([FromuQuery] string key)
  {
  }

  // Global cache partitioned by single record
  [HttpPost(“/pk1/{partitionkey1}”)]
  public async Task<bool> SetBySinglePartition ([FromBody] object value, [FromuQuery] string key, string partitionkey1)
  {
  }

  // Global cache partitioned by single entity
  [HttpGet(“/pk1/{partitionkey1}”)]
  public async Task<object> GetBySingleParititon ([FromuQuery] string key, string partitionkey1)
  {
  }

  // Global cache partitioned by two entities for more uniqueness
  [HttpPost(“/pk1/{partitionkey1}/pk2/{partitionkey2}”)]
  public async Task<bool> SetByDoublePartition ([FromBody] object value, [FromuQuery] string key, string partitionkey1, string partitionkey2)
  {
  }

  // Global cache partitioned by two entities for more uniqueness
  [HttpGet(“/pk1/{partitionkey1}/pk2/{partitionkey2}”)]
  public async Task<object> GetByDoublePartition ([FromQuery] string key, string partitionkey1, string partitionkey2)
  {
  }
}


To implement an object store, let's use Azure Redis as our backend storage. 

To leverage Redis, we need to provide a common interface for API to access.

Let's put backend storage as an enum option. Example:

C#
 
public enum ObjectStoreHandlerType
    {
        Redis,
	CosmosDb,
	PostGre
    }


Let's define the interface IObjectsStoreHandler that provides abstraction and functionalities toward backend storage.

C#
 
public interface IObjectStoreHandler
    {
        Task<T> GetObjectAsync(string key);

        Task<bool> SetObjectAsync<T>( string key, T value);

        Task<T> GetObjectBySinglePartitionAsync<T>(string key, string partitionkey1);

        Task<bool> SetObjectBySinglePartitionAsync<T>(string key, string partitionkey1, T value);

        Task<T> GetObjectByDoublePartitionAsync<T>(string key, string partitionkey1, string partitionkey2);

        Task<bool> SetObjectBySinglePartitionAsync<T>(string key, string partitionkey1, string partitionkey2, T value);


        ObjectStoreHandlerType Type { get; }
    }


To follow OOD paradigms, let's define an ObjectStoreHandlerfactory to create different ObjectStores based on the handler type.

C#
 
public interface IObjectStoreHandlerFactory
    {
        IObjectStoreHandler CreateObjectStoreHandler(ObjectStoreHandlerType objectStoreProviderType = ObjectStoreHandlerType.Redis);
    }

public class ObjectStoreHandlerFactory : IObjectStoreHandlerFactory
    {
        private readonly IEnumerable<IObjectStoreHandlers> _objectStorehandlers;

        public ObjectStoreProviderFactory(IEnumerable<IObjectStoreHandlers> objectStorehandlers)
        {
            _objectStorehandlers = objectStorehandlers;
        }

        public IObjectStoreHandler CreateObjectStoreHandler(ObjectStoreProviderType requestedHandlerType)
        {
            return _objectStorehandlers.SingleOrDefault(handlers => handlers.Type == requestedHandlerType);
        }
    }


Let's define Redis ObjectStoreHandler. Then, you can create a simple RedisClient.

C#
 
public class RedisObjectStoreHander : IObjectStoreHandler
    {
        private readonly RedisClient _redisClient;

        public RedisObjectStoreProvider(RedisClient redisClient)
        {
            _redisClient= redisClient;
        }

        public ObjectStoreHandlerType  Type  => ObjectStoreHandlerType.Redis;

        public async Task<T> GetObjectAsync<T>(string key)
        {
            RedisKey redisKey = $"{key}";

            try
            {
                    var redisValue = await _redisClient.GetConnectedDatabase().StringGetAsync(redisKey);
                    string strValue = redisValue.ToString();
                    if (!string.IsNullOrWhiteSpace(strValue))
                    {
                        return JsonConvert.DeserializeObject<T>(strValue);
                    }
            }
            catch (Exception ex)
            {
            }

            return default;
        }

	public async Task<bool> SetObjectAsync<T>(string key, T value)
        {
            RedisKey redisKey = $"{key}";
            RedisValue redisValue = JsonConvert.SerializeObject(value);
            try
            {
await _redisConnection.GetConnectedDatabase().StringSetAsync(redisKey, redisValue, flags: ComandFlags.DemandMaster); 
               
return true;
            }
            catch (Exception ex)
            {
            }

            return false;
        }
public async Task<T> GetObjectBySinglePartitionAsync<T>(string key, string partitionkey1);        {
            RedisKey redisKey = $" {{partitionkey1}}_{key}";

            try
            {
                    var redisValue = await _redisClient.GetConnectedDatabase().StringGetAsync(redisKey);
                    string strValue = redisValue.ToString();
                    if (!string.IsNullOrWhiteSpace(strValue))
                    {
                        return JsonConvert.DeserializeObject<T>(strValue);
                    }
            }
            catch (Exception ex)
            {
            }

            return default;
        }

	public async Task<bool> SetObjectBySinglePartitionAsync <T>( string key, string partitionkey1, T value)
        {
            RedisKey redisKey = $" {{partitionkey1}}_{key}";
            RedisValue redisValue = JsonConvert.SerializeObject(value);
            try
            {
await _redisConnection.GetConnectedDatabase().StringSetAsync(redisKey, redisValue, flags: ComandFlags.DemandMaster); 
               
return true;
            }
            catch (Exception ex)
            {
            }

            return false;
        }
public async Task<T> GetObjectByDoublePartitionAsync<T>(string key, string partitionkey1, string partitionkey2);        {
            RedisKey redisKey = $"{{{partitionkey1}_{partitionkey2}}}_{key}";

            try
            {
                    var redisValue = await _redisClient.GetConnectedDatabase().StringGetAsync(redisKey);
                    string strValue = redisValue.ToString();
                    if (!string.IsNullOrWhiteSpace(strValue))
                    {
                        return JsonConvert.DeserializeObject<T>(strValue);
                    }
            }
            catch (Exception ex)
            {
            }

            return default;
        }

	public async Task<bool> SetObjectByDoublePartitionAsync <T>( string key, string partitionkey1, string partitionkey2, T value)
        {
            RedisKey redisKey = $"{{{partitionkey1}_{partitionkey2}}}_{key}";
            RedisValue redisValue = JsonConvert.SerializeObject(value);
            try
            {
await _redisConnection.GetConnectedDatabase().StringSetAsync(redisKey, redisValue, flags: ComandFlags.DemandMaster); 
               
return true;
            }
            catch (Exception ex)
            {
            }

            return false;
        }

}


That's it. You can now integrate RedisObjectStoreHandler with the API layer. 

C#
 
private readonly IObjectStoreHandler _objectStoreHandler;

public ObjectCacheController(IObjectStoreHandlerFactory objectStoreHandlerFactory)
  {
      _objectStoreHandler = objectStoreHandlerFactory.Create(ObjectStoreHandlerType.Redis);
  }


You can now have a robust object store service that can take in unique keys with granular level partitions and can store/retrieve objects of the desired type.

azure Cache (computing) Object (computer science) Redis (company)

Opinions expressed by DZone contributors are their own.

Related

  • Scaling Databases With EclipseLink And Redis
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Graph API for Entra ID (Azure AD) Object Management
  • Caching RESTful API Requests With Heroku Data for Redis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!