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
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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Scaling Databases With EclipseLink And Redis
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Common Performance Management Mistakes
  • Hibernate, Redis, and L2 Cache Performance

Trending

  • Data Processing in GCP With Apache Airflow and BigQuery
  • Modern Digital Authentication Protocols
  • Implement RAG Using Weaviate, LangChain4j, and LocalAI
  • How to Query XML Files Using APIs in Java
  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
Like (1)
Save
Tweet
Share
2.5K 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
  • Enhancing Performance With Amazon Elasticache Redis: In-Depth Insights Into Cluster and Non-Cluster Modes
  • Common Performance Management Mistakes
  • Hibernate, Redis, and L2 Cache Performance

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: