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.

Important: Cache get() operations return an Attempt object - a functional wrapper that elegantly handles the presence or absence of cached data without null-related issues. Other operations like set(), clear(), and lookup() return their respective types (void, boolean, etc.).

📦 Cache BIFs

BoxLang provides several Built-In Functions for cache operations:

BIF
Purpose
Returns

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

🗄️ 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?