Part2️⃣ - Caching | ๐ Mastering Microservices: Using YARP as Your Ultimate API Gateway & Reverse Proxy! ๐๐ก
Memory Cache Service Description
This code provides a robust implementation of an in-memory caching service using the IMemoryCache
interface from the Microsoft.Extensions.Caching.Memory
namespace. The implementation is divided into an interface and a concrete class to promote abstraction and dependency injection.
IMemoryCacheService Interface
The IMemoryCacheService
interface defines the contract for the caching service, ensuring that any implementation of this interface will provide the following methods:
SetCache:
- Parameters:
string key
: The unique identifier for the cached item.object value
: The object to be stored in the cache.int expirationInSeconds
: The time in seconds after which the cached item will expire.
- Description: This method stores a value in the cache with the specified key and sets an expiration time for the cached item.
- Parameters:
GetCache:
- Parameters:
string key
: The unique identifier for the cached item.
- Returns:
string
- Description: This method retrieves the cached value associated with the specified key. If the key does not exist in the cache, it returns null.
- Parameters:
MemoryCacheService Class
The MemoryCacheService
class provides a concrete implementation of the IMemoryCacheService
interface. It uses an instance of IMemoryCache
to manage the caching operations. The class is designed to be instantiated through dependency injection, promoting loose coupling and making it easier to test and maintain.
Constructor:
- Parameters:
IMemoryCache memoryCache
: An instance ofIMemoryCache
injected via the constructor.
- Description: The constructor initializes the
MemoryCacheService
with anIMemoryCache
instance, enabling it to perform caching operations.
- Parameters:
GetCache Method:
- Parameters:
string key
: The unique identifier for the cached item.
- Returns:
string
- Description: This method retrieves the cached value associated with the specified key from the
IMemoryCache
instance. If the key does not exist in the cache, it returns null.
- Parameters:
SetCache Method:
- Parameters:
string key
: The unique identifier for the cached item.object value
: The object to be stored in the cache.int expirationInSeconds
: The time in seconds after which the cached item will expire.
- Description: This method stores the specified value in the cache with the given key and sets the expiration time based on the provided
expirationInSeconds
parameter. The expiration time is calculated from the current time plus the specified number of seconds.
- Parameters:
Benefits
- Improved Performance: By caching frequently accessed data, the system can reduce the load on backend services and decrease response times for end-users.
- Scalability: Efficient caching mechanisms help in scaling applications by minimizing redundant data processing and network latency.
- Flexibility: The use of an interface allows for easy swapping of different caching implementations if needed, enhancing the flexibility and maintainability of the codebase.
Usage
To utilize this caching service, you would typically register the MemoryCacheService
in your dependency injection container and then inject it into your controllers or services where caching is required. This setup allows you to efficiently manage cached data, improving the overall performance and responsiveness of your application.
Configuring the YARP Middleware Description
This code sets up in-memory caching for an API gateway using the YARP reverse proxy. It registers the necessary services and configures the middleware to handle caching of responses based on request paths.
Service Registration
- AddMemoryCache: Registers the in-memory caching service, enabling the application to store and retrieve cache entries.
- AddSingleton: Registers the
IMemoryCacheService
implementation,MemoryCacheService
, as a singleton, ensuring a single instance is used throughout the application's lifetime.
Application Pipeline Configuration
- MapReverseProxy: Maps the YARP reverse proxy middleware to the application pipeline, enabling request forwarding to backend services.
- Custom Middleware: Adds custom middleware to the proxy pipeline for handling caching:
- Retrieve Caching Service: The middleware retrieves the
IMemoryCacheService
instance from the request's service provider. - Check Cache: Attempts to get a cached response using the request path as the key.
- Return Cached Response: If a cached response is found, it sets the response content type to JSON and writes the cached response to the response body.
- Cache Response: If no cached response is found:
- Temporarily replaces the response body stream with a memory stream.
- Calls the next middleware in the pipeline.
- Reads the response body into a string and caches it with the request path as the key and a 60-second expiration time.
- Restores the original response body stream and copies the cached response into it.
- Retrieve Caching Service: The middleware retrieves the
This setup allows the API gateway to efficiently cache and serve responses, reducing load on backend services and improving response times for clients.
Comments
Post a Comment