# How to Configure Redis Caching for Admin User Sessions in the Mall Project

> Configure Redis caching for admin user sessions in the mall project. Optimize stateless JWT sessions by caching user details and permissions, reducing database lookups.

- Repository: [macro/mall](https://github.com/macrozheng/mall)
- Tags: how-to-guide
- Published: 2026-02-28

---

**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`](https://github.com/macrozheng/mall/blob/main/mall-admin/src/main/resources/application.yml), the Redis configuration specifies the logical database name, key prefixes, and default expiration time:

```yaml
redis:
  database: mall
  key:
    admin: 'ums:admin'
    resourceList: 'ums:resourceList'
  expire:
    common: 86400 # 24 hours in seconds

```

This configuration establishes:
- **Logical database**: The name `mall` identifies the Redis database instance
- **Admin key prefix**: `ums:admin` for admin user objects
- **Resource key prefix**: `ums:resourceList` for 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`](https://github.com/macrozheng/mall/blob/main/mall-admin/src/main/resources/application-prod.yml) provides host-specific connectivity:

```yaml
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`](https://github.com/macrozheng/mall/blob/main/mall-common/src/main/java/com/macro/mall/common/config/BaseRedisConfig.java) file defines three critical beans:

```java
@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`](https://github.com/macrozheng/mall/blob/main/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`](https://github.com/macrozheng/mall/blob/main/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`](https://github.com/macrozheng/mall/blob/main/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:

```java
@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 lookup
- `delResourceList(Long adminId)` removes the specific admin's permission list
- `delResourceListByRole(Long roleId)` and `delResourceListByResource(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`](https://github.com/macrozheng/mall/blob/main/mall-admin/src/main/java/com/macro/mall/service/impl/UmsAdminServiceImpl.java), the `getAdminByUsername` method implements the cache-first strategy:

```java
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`:

1. Credentials are validated against the database
2. `getAdminByUsername` is called, which populates the Redis cache with the admin object
3. JWT token is generated and returned to the client (stateless, not stored in Redis)
4. 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:

1. **Configure Redis connectivity**: Set `spring.redis.host`, `port`, and `password` (if required) in [`application-prod.yml`](https://github.com/macrozheng/mall/blob/main/application-prod.yml) or your active profile.

2. **Customize key namespaces**: Modify `redis.key.admin` and `redis.key.resourceList` in [`application.yml`](https://github.com/macrozheng/mall/blob/main/application.yml) to match your naming conventions:

   ```yaml
   redis:
     key:
       admin: 'custom:admin'
       resourceList: 'custom:resources'
   ```

3. **Adjust TTL values**: Change `redis.expire.common` to control how long admin sessions remain cached (value in seconds).

4. **Verify bean initialization**: Ensure `BaseRedisConfig` is scanned by your Spring Boot application. The configuration auto-registers `RedisTemplate`, `RedisCacheManager`, and `RedisService` without additional dependencies beyond Spring Data Redis.

5. **Implement cache clearing on logout** (optional): Create a logout endpoint that calls `delAdmin` and `delResourceList` to immediately remove session data:

   ```java
   @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:admin` and `ums:resourceList`) with a 24-hour default TTL.
- Configuration is centralized in [`application.yml`](https://github.com/macrozheng/mall/blob/main/application.yml) for key patterns and [`application-prod.yml`](https://github.com/macrozheng/mall/blob/main/application-prod.yml) for connection details.
- `BaseRedisConfig` provides the JSON-serialized `RedisTemplate` and cache manager used across the application.
- `UmsAdminCacheServiceImpl` handles specific storage operations for admin entities and permission lists using the pattern `<database>:<prefix>:<identifier>`.
- The `UmsAdminServiceImpl` implements 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`](https://github.com/macrozheng/mall/blob/main/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`](https://github.com/macrozheng/mall/blob/main/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.