Code Usage
Learn how to leverage Redis caching in BoxLang applications using built-in functions and components for objects, queries, and content.
🎯 Overview
Once you have configured your Redis cache provider in your Application.bx or boxlang.json, you can leverage BoxLang's built-in caching BIFs and components to interact with Redis. This page demonstrates practical examples of caching various types of data using the standard BoxLang caching API.
📦 Cache BIFs
BoxLang provides several Built-In Functions for cache operations:
cache()
Get a cache instance by name
ICacheProvider
cacheFilter()
Create pattern filters for bulk operations
ICacheKeyFilter
cacheNames()
List all registered cache names
Array
cacheProviders()
List all registered cache providers
Array
cacheService()
Access the cache service directly
CacheService
The cache() BIF returns an instance of ICacheProvider which provides a rich interface for working with caches. See the complete BoxLang Cache API Documentation for all available methods.
🗄️ Caching Objects
Basic Object Caching
// Store user data in Redis
userData = {
"userID": 123,
"name": "John Doe",
"email": "[email protected]",
"preferences": { "theme": "dark", "language": "en" }
};
// Cache for 30 minutes (1800 seconds)
cache( "redis" ).set( "user:123", userData, 1800 );
// Retrieve from cache
userAttempt = cache( "redis" ).get( "user:123" );
// Handle the Attempt safely
if ( userAttempt.isPresent() ) {
user = userAttempt.get();
writeOutput( "Welcome back, #user.name#!" );
} else {
// Load from database if not cached
user = loadUserFromDatabase( 123 );
cache( "redis" ).set( "user:123", user, 1800 );
}Functional Approach with Attempt
Complex Object Caching
Bulk Object Operations
Get-or-Set Pattern
The getOrSet() method provides an atomic operation that retrieves a cached value or computes and stores it if not found - eliminating race conditions and double-lookup patterns:
📊 Caching Queries
Basic Query Caching
Manual Query Caching
Query Caching Function
Query Invalidation
📄 Caching Content/HTML
Using the Cache Component
Manual Content Caching
Component-Based Content Caching
🎨 Advanced Caching Patterns
Cache-Aside Pattern
Write-Through Caching
Lazy Loading with Locking
Time-Based Invalidation
Fragment Caching
🧹 Cache Management
Clearing Cache Entries
Cache Statistics
Listing Cache Keys
Cache Metadata
Last updated
Was this helpful?
