Creates a new Redis local storage provider and establishes a connection.
The constructor sets up the ioredis client with automatic reconnection,
error handling, and optional logging. The client connects lazily on the
first command, so construction itself does not block.
Redis connection and behavior configuration.
At minimum, provide either url or options.
If neither is provided, connects to localhost:6379.
// Connect to local Redis
const provider = new RedisLocalStorageProvider({});
// Connect to Azure Managed Redis with TLS
const provider = new RedisLocalStorageProvider({
url: 'rediss://default:ACCESS_KEY@myredis.redis.cache.windows.net:6380',
defaultTTLSeconds: 600
});
// Connect to AWS ElastiCache
const provider = new RedisLocalStorageProvider({
options: {
host: 'my-cluster.abc123.use1.cache.amazonaws.com',
port: 6379,
tls: {}
}
});
Returns the underlying ioredis client instance for advanced operations.
Use with caution — direct client access bypasses key prefixing and
category tracking. Prefer the ILocalStorageProvider methods for
standard operations.
Whether the Redis client currently has an active connection.
Note: ioredis automatically reconnects on failure, so a false value
here is usually transient. The provider continues to accept commands
(they queue until reconnection succeeds or retry limit is hit).
Whether the pub/sub subscriber connection is currently active.
Clears all keys belonging to a specific category.
Uses the category tracking Set to find all member keys, deletes them in a single pipeline call, then removes the tracking Set itself.
The category to clear. If empty, clears the "default" category.
Gracefully disconnects from Redis.
Sends a QUIT command and waits for pending replies. After calling this
method, the provider should not be used for further operations.
Call this during application shutdown to ensure clean disconnection.
Checks if a key exists in the specified category.
This is more efficient than GetItem() when you only need to check
existence without retrieving the value (avoids transferring the value
over the network).
The key to check
Optionalcategory: stringOptional category for key isolation (defaults to "default")
true if the key exists and has not expired
Returns all keys belonging to a specific category.
Reads from the category tracking Set, so the result reflects keys
that were added via SetItem (some may have expired via TTL but
will still appear in the set until cleaned up).
The category to list keys from
Array of original key names (without the Redis prefix/category prefix)
Retrieves a value from Redis by key and optional category.
Redis stores values as strings — this method JSON-deserializes the stored value
internally so callers see a typed object back. Returns null for missing keys,
Redis unavailability, or corrupt JSON.
Expected type of the stored value. Caller-controlled.
The key to look up
Optionalcategory: stringOptional category for key isolation (defaults to "default")
Batched read using Redis MGET — one command, one network round-trip,
N values returned. For N keys this is ~N× faster than individual GETs
which each pay full RTT.
Inputs are deduplicated (same key requested twice → one Redis fetch, one
map entry). Missing keys, corrupt JSON entries, and Redis errors all map
to null for the affected key — callers see them as cache misses.
Expected type of all stored values. Caller-controlled.
The keys to retrieve.
Optionalcategory: stringOptional category for key isolation.
Returns the remaining time-to-live (in seconds) for a key.
The key to check
Optionalcategory: stringOptional category for key isolation (defaults to "default")
TTL in seconds, -1 if no expiration is set, -2 if the key doesn't exist,
or null if Redis is unavailable
Registers a callback for cache change events from other servers.
The callback fires whenever another server instance modifies a cached entry
(via SetItem, Remove, or ClearCategory).
Events from this server instance (identified by MJGlobal.ProcessUUID) are automatically filtered out.
Function invoked with the CacheChangedEvent
A function that, when called, removes this callback registration
Stores a value in Redis under the given key and optional category.
Redis stores values as strings — this method JSON-serializes the value internally. Callers should pass plain data (objects/arrays/primitives). Class instances will lose their prototype on retrieval; functions, Maps, Sets, and Dates have JSON's usual limitations.
If a ttlSeconds is provided, the key will automatically expire after that
duration. Otherwise, the configured defaultTTLSeconds is used. If neither
is set, the key persists indefinitely.
The key is also added to a Redis Set that tracks all keys in the category,
enabling efficient ClearCategory() and GetCategoryKeys() operations.
Type of the value being stored. Caller-controlled.
The key to store under
The value to store (will be JSON-serialized internally)
Optionalcategory: stringOptional category for key isolation (defaults to "default")
OptionalttlSeconds: numberOptional time-to-live in seconds. Overrides defaultTTLSeconds from config.
Starts listening for cache change events from other server instances. Creates a dedicated Redis connection for pub/sub (required by Redis protocol — a client in subscribe mode cannot execute other commands).
Must be called explicitly after construction. No-op if enablePubSub is false
in the config, or if already listening.
Redis-backed implementation of the MemberJunction ILocalStorageProvider interface.
Provides persistent, shared caching for server-side environments using Redis. This is a drop-in replacement for
InMemoryLocalStorageProvider— all consumers (likeLocalCacheManager,ProviderBasemetadata caching, etc.) work without any code changes.Key Structure
All keys follow the pattern:
{prefix}:{category}:{key}"mj"to isolate MJ data in shared Redis instancesRunViewCache,Metadata,DatasetCache, etc.)Categories are tracked in a Redis Set at
{prefix}:__categories__:{category}so thatClearCategory()andGetCategoryKeys()operations are efficient.TTL Support
Redis has native key expiration. The provider supports TTL at two levels:
defaultTTLSecondsin config — applied to allSetItemcallsttlSecondsparameter onSetItem— overrides the default per-callError Handling
Redis operations are wrapped in try/catch blocks. Connection errors are logged via
LogError()but do not throw — the provider gracefully returnsnullfor reads and silently skips writes. This prevents a Redis outage from crashing the application. Theioredisclient handles automatic reconnection.Example