How to Configure Redis Caching for Admin User Sessions in the Mall Project
The mall project uses Redis to cache admin user details and permission resource lists, storing them with configurable key prefixes and a 24-hour TTL to eliminate repeated database lookups during stateless JWT sessions.
The mall e-commerce platform implements Redis as a high-performance key-value store to maintain admin session data. While authentication relies on stateless JWT tokens, the admin user object and its associated permission lists are cached in Redis to optimize performance. This guide explains how to configure and customize Redis caching for admin user sessions based on the actual source code implementation in the macrozheng/mall repository.
Configuring Redis Connection and Key Prefixes
The Redis configuration for admin sessions is defined in the mall-admin module's YAML files. These settings control connection parameters, logical database selection, and the naming conventions for cached keys.
Application YAML Configuration
In mall-admin/src/main/resources/application.yml, the Redis configuration specifies the logical database name, key prefixes, and default expiration time:
redis:
database: mall
key:
admin: 'ums:admin'
resourceList: 'ums:resourceList'
expire:
common: 86400 # 24 hours in seconds
This configuration establishes:
- Logical database: The name
mallidentifies the Redis database instance - Admin key prefix:
ums:adminfor admin user objects - Resource key prefix:
ums:resourceListfor permission lists - Default TTL: 86400 seconds (24 hours) for cache entries
Production Environment Settings
For production deployments, mall-admin/src/main/resources/application-prod.yml provides host-specific connectivity:
spring:
redis:
host: redis
port: 6379
database: 0
Adjust the host value to point to your Redis instance hostname or IP address. The database: 0 parameter selects the specific Redis logical database index.
Core Redis Beans in Mall-Common
The foundational Redis infrastructure is provided by the mall-common module, which declares the connection factory, serialization strategy, and template configuration used throughout the admin services.
BaseRedisConfig.java
The mall-common/src/main/java/com/macro/mall/common/config/BaseRedisConfig.java file defines three critical beans:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory,
RedisSerializer<Object> serializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
This configuration uses JSON serialization (via Jackson) for all values, enabling readable storage and proper type information for deserialization. The RedisCacheManager bean configures Spring Cache with a default TTL matching the common expiration value (24 hours) defined in the YAML.
RedisService Abstraction
The mall-common/src/main/java/com/macro/mall/common/service/RedisService.java interface declares standardized operations (set, get, del, expire) that wrap the RedisTemplate. The implementation in mall-common/src/main/java/com/macro/mall/common/service/impl/RedisServiceImpl.java provides the concrete logic used by admin-specific cache services.
Implementing Admin Session Caching
Admin session data is managed by UmsAdminCacheServiceImpl in the mall-admin module, which provides specific methods for storing and retrieving admin entities and their permission lists.
UmsAdminCacheServiceImpl Structure
Located at mall-admin/src/main/java/com/macro/mall/service/impl/UmsAdminCacheServiceImpl.java, this service implements the following caching patterns:
| Method | Cached Key Pattern | Data Stored | Expiration |
|---|---|---|---|
setAdmin(admin) / getAdmin(username) |
mall:ums:admin:<username> |
UmsAdmin entity |
86400 seconds |
setResourceList(adminId, list) / getResourceList(adminId) |
mall:ums:resourceList:<adminId> |
List<UmsResource> |
86400 seconds |
The implementation constructs keys by concatenating the database name, configured prefix, and identifier:
@Override
public void setAdmin(UmsAdmin admin) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + admin.getUsername();
redisService.set(key, admin, REDIS_EXPIRE);
}
@Override
public UmsAdmin getAdmin(String username) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + username;
return (UmsAdmin) redisService.get(key);
}
Cache Invalidation Methods
When admin data changes, the service provides deletion methods to purge stale entries:
delAdmin(Long adminId)removes the admin object by username lookupdelResourceList(Long adminId)removes the specific admin's permission listdelResourceListByRole(Long roleId)anddelResourceListByResource(Long resourceId)purge lists when role-resource mappings change
How Admin Session Caching Works in Practice
The admin session flow integrates Redis as a cache-aside pattern, checking the cache before querying the database during authenticated requests.
Cache-First Retrieval in UmsAdminServiceImpl
In mall-admin/src/main/java/com/macro/mall/service/impl/UmsAdminServiceImpl.java, the getAdminByUsername method implements the cache-first strategy:
public UmsAdmin getAdminByUsername(String username) {
// Attempt Redis lookup first
UmsAdmin admin = getCacheService().getAdmin(username);
if (admin != null) {
return admin; // Cache hit
}
// Database fallback on cache miss
UmsAdmin adminFromDb = adminMapper.selectByUsername(username);
if (adminFromDb != null) {
getCacheService().setAdmin(adminFromDb); // Populate cache
}
return adminFromDb;
}
Login Flow and Session Establishment
During the login method in UmsAdminServiceImpl:
- Credentials are validated against the database
getAdminByUsernameis called, which populates the Redis cache with the admin object- JWT token is generated and returned to the client (stateless, not stored in Redis)
- Subsequent requests use the cached admin data for permission checks via
getResourceList
Permission Verification
Security interceptors call getResourceList(adminId) to retrieve the cached permission tree. If present, the list returns immediately from Redis; otherwise, the system queries the database, builds the resource list, and caches it for subsequent requests.
Step-by-Step Configuration Guide
Follow these steps to enable or modify Redis caching for admin sessions in your deployment:
-
Configure Redis connectivity: Set
spring.redis.host,port, andpassword(if required) inapplication-prod.ymlor your active profile. -
Customize key namespaces: Modify
redis.key.adminandredis.key.resourceListinapplication.ymlto match your naming conventions:redis: key: admin: 'custom:admin' resourceList: 'custom:resources' -
Adjust TTL values: Change
redis.expire.commonto control how long admin sessions remain cached (value in seconds). -
Verify bean initialization: Ensure
BaseRedisConfigis scanned by your Spring Boot application. The configuration auto-registersRedisTemplate,RedisCacheManager, andRedisServicewithout additional dependencies beyond Spring Data Redis. -
Implement cache clearing on logout (optional): Create a logout endpoint that calls
delAdminanddelResourceListto immediately remove session data:@PostMapping("/logout") public CommonResult logout(@RequestHeader("Authorization") String authHeader) { String token = authHeader.substring(7); Long adminId = jwtTokenUtil.getUserIdFromToken(token); cacheService.delAdmin(adminId); cacheService.delResourceList(adminId); return CommonResult.success(null); }
Summary
- The mall project caches admin session data in Redis using configurable key prefixes (
ums:adminandums:resourceList) with a 24-hour default TTL. - Configuration is centralized in
application.ymlfor key patterns andapplication-prod.ymlfor connection details. BaseRedisConfigprovides the JSON-serializedRedisTemplateand cache manager used across the application.UmsAdminCacheServiceImplhandles specific storage operations for admin entities and permission lists using the pattern<database>:<prefix>:<identifier>.- The
UmsAdminServiceImplimplements a cache-first retrieval strategy, falling back to database queries only on cache misses. - Cache invalidation occurs automatically when role permissions change, or manually via deletion methods during logout.
Frequently Asked Questions
Does the mall project store JWT tokens in Redis?
No, JWT tokens remain stateless and are not stored in Redis. The cache stores only the UmsAdmin entity and the List<UmsResource> permission lists associated with the admin ID. The JWT token contains all necessary claims for authentication, while Redis eliminates repeated database lookups for user details and permissions during the token's valid lifetime.
How do I change the cache expiration time for admin sessions?
Modify the redis.expire.common value in mall-admin/src/main/resources/application.yml. The value is specified in seconds (default 86400 for 24 hours). For example, to set a 12-hour expiration, use common: 43200. This TTL applies to both admin objects and resource lists.
What happens when an admin's permissions are updated in the database?
When role-resource relationships change, UmsAdminCacheServiceImpl provides specific invalidation methods such as delResourceListByRole and delResourceListByResource. These methods delete the affected resource list keys from Redis, forcing a fresh database query and cache repopulation on the next request. The admin object itself remains cached unless explicitly cleared via delAdmin.
Can I use Redis Cluster with the mall admin caching implementation?
Yes, the configuration supports Redis Cluster. Update application-prod.yml with cluster-specific properties under spring.redis.cluster instead of single-node host and port settings. The RedisTemplate and RedisService beans automatically adapt to cluster topology without requiring changes to UmsAdminCacheServiceImpl or other cache-related classes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →