Cache Documentation - Cache Strategy and Performance Optimization
Overview
This document details the cache strategy and performance optimization mechanisms of the VJSP Vue3 framework. The framework adopts a multi-level cache architecture, combined with modern frontend technology stack, providing efficient cache solutions and performance optimization strategies for enterprise-level applications.
Cache Architecture
Core Features
- Multi-level Cache Strategy: Supports local storage, session storage, component cache, and other multi-level cache mechanisms
- Secure Storage: Provides encrypted storage functionality to protect sensitive data security
- Intelligent Expiration Management: Automatically cleans expired cache, optimizing storage space
- Component Cache: Component-level cache based on Vue keep-alive, improving page switching performance
- Performance Monitoring: Built-in performance monitoring tools, real-time tracking of application performance metrics
Technology Stack
- Web Storage API: localStorage and sessionStorage for basic storage
- CryptoJS: Data encryption and decryption, improving storage security
- Pinia State Management: Cache state and performance state management
- Vue keep-alive: Component-level cache mechanism
- ECharts: Performance monitoring data visualization
Cache Management Mechanism
Cache Utility Class (CacheUtil)
The framework provides a unified cache operation interface, supporting multiple storage modes and configuration options.
Cache Option Configuration
The cache utility supports rich configuration options:
- Expiration Time: Set the validity period of cached data
- Storage Mode: Choose between localStorage or sessionStorage
- Encrypted Storage: Enable data encryption to protect sensitive information
- Custom Key: Support for custom encryption keys
Core Function Methods
The cache utility class provides complete CRUD operations:
- Set Cache: Supports multiple storage modes and encryption options
- Get Cache: Automatically checks expiration and returns valid data
- Cache Management: Supports delete, clear, check, and other operations
- Performance Optimization: Provides cache size calculation and expiration cleanup functionality
Secure Storage Utility (SecurityStorage)
Specifically designed for secure storage of sensitive data, providing additional security protection mechanisms.
Security Features
- Dynamic Key Generation: Generates unique encryption keys combined with browser fingerprint
- Session-level Storage: Uses sessionStorage by default for improved security
- Token Management: Specialized secure Token storage methods
- User Information Protection: Encrypted storage of sensitive user information
Application Scenarios
- Secure storage of user login tokens
- Encrypted protection of sensitive user information
- Implementation of "Remember Me" functionality
- Secure session management
Component Cache Mechanism
keep-alive Component Cache
The framework implements component-level cache based on Vue keep-alive, improving page switching performance.
Cache Strategy
- Dynamic Cache Management: Dynamically manages cached components based on route configuration
- Intelligent Cache Cleanup: Automatically cleans unnecessary cached components
- Cache View Management: Manages cached views through tagsView state management
Configuration Method
Control component cache through meta properties in route configuration:
// Route configuration example
{
path: '/product/list',
name: 'ProductList',
component: () => import('@/views/product/List.vue'),
meta: {
title: 'Product List',
noCache: false // Enable cache (default)
}
}Tab Page Cache Management
Implements tab page-level cache control through tagsView state management.
Cache View Management
- Cache View Collection: Maintains collection of component names that need to be cached
- Dynamic Cache Update: Dynamically updates cache strategy based on tab operations
- Cache State Synchronization: Ensures cache state synchronization with user operations
Performance Optimization Strategies
1. Route Lazy Loading
Implement on-demand loading of route components using dynamic imports:
- Code Splitting: Automatically splits code chunks, reducing initial bundle size
- On-demand Loading: Dynamically loads corresponding components when users access them
- Preloading Optimization: Intelligently preloads components that might be accessed
2. Component Optimization
Computed Property Cache
Properly use computed properties, leveraging Vue's reactive cache mechanism:
- Dependency Tracking: Automatically tracks dependency relationships, avoiding repeated calculations
- Cache Reuse: Reuses calculation results under same dependencies
- Performance Monitoring: Monitors performance of computed properties
Debounce and Throttle Optimization
Apply debounce and throttle processing to high-frequency operations:
- Search Optimization: Debounce processing for search input boxes
- Scroll Optimization: Throttle control for scroll events
- Form Optimization: Prevent duplicate form submissions
3. Data Cache Strategy
Dictionary Data Cache
Optimize cache for commonly used dictionary data:
- Preload Cache: Preload commonly used dictionaries when application starts
- Cache Update: Regularly update cached data to maintain freshness
- Memory Optimization: Reasonably control cache size to avoid memory leaks
API Response Cache
Cache responses for frequently requested APIs:
- Request Deduplication: Avoid duplicate sending of same requests
- Cache Expiration: Set reasonable cache expiration times
- Cache Invalidation: Actively clear related cache when data changes
Product Module Development Guide
1. Product Data Cache Implementation
In Product module development, properly use cache strategy to improve performance.
Product List Cache
// src/views/product/List.vue
import { CacheUtil } from '@/utils/cache'
// Product list data cache
const PRODUCT_LIST_CACHE_KEY = 'product_list_cache'
const PRODUCT_LIST_CACHE_EXPIRE = 5 * 60 * 1000 // 5-minute cache
// Get product list (with cache)
const getProductList = async () => {
// First check cache
const cachedData = CacheUtil.getLocal(PRODUCT_LIST_CACHE_KEY)
if (cachedData) {
return cachedData
}
// Cache miss, request API
const response = await getProductListApi()
// Set cache
CacheUtil.setLocal(PRODUCT_LIST_CACHE_KEY, response.data, PRODUCT_LIST_CACHE_EXPIRE)
return response.data
}Product Detail Cache
// src/views/product/Detail.vue
// Product detail cache (based on product ID)
const getProductDetail = async (productId: string) => {
const cacheKey = `product_detail_${productId}`
const cacheExpire = 10 * 60 * 1000 // 10-minute cache
// Check cache
const cachedDetail = CacheUtil.getLocal(cacheKey)
if (cachedDetail) {
return cachedDetail
}
// Request API
const response = await getProductDetailApi(productId)
// Set cache
CacheUtil.setLocal(cacheKey, response.data, cacheExpire)
return response.data
}2. Component Cache Configuration
Configure reasonable component cache strategy for Product module.
Product List Page Cache
// src/router/modules/product.ts
{
path: '/product/list',
name: 'ProductList',
component: () => import('@/views/product/List.vue'),
meta: {
title: 'Product List',
noCache: false, // Enable cache
keepAliveName: 'ProductList' // Cached component name
}
}Product Detail Page Cache
// Product detail page (usually doesn't need cache, maintain data real-time)
{
path: '/product/detail/:id',
name: 'ProductDetail',
component: () => import('@/views/product/Detail.vue'),
meta: {
title: 'Product Detail',
noCache: true // Disable cache
}
}3. Performance Optimization Practices
Image Lazy Loading
<!-- src/views/product/List.vue -->
<template>
<div class="product-list">
<div v-for="product in products" :key="product.id" class="product-item">
<el-image :src="product.image" :alt="product.name" lazy :scroll-container="scrollContainer" />
<div class="product-info">
<h3>{{ product.name }}</h3>
<p>{{ product.description }}</p>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const scrollContainer = ref<HTMLElement | null>(null)
</script>Virtual Scroll Optimization
For displaying large amounts of product data, use virtual scroll to optimize performance:
<!-- src/views/product/List.vue -->
<template>
<el-table-v2 :columns="columns" :data="products" :width="800" :height="400" fixed />
</template>
<script setup lang="ts">
import { ref } from 'vue'
const columns = [
{
key: 'name',
title: 'Product Name',
width: 200,
},
{
key: 'price',
title: 'Price',
width: 100,
},
// ... more column definitions
]
const products = ref([])
</script>Cache Monitoring and Debugging
1. Cache State Monitoring
The framework provides cache state monitoring tools to help developers understand cache usage.
Cache Statistics Information
// Get cache statistics information
const getCacheStats = () => {
const localKeys = CacheUtil.keys(false)
const sessionKeys = CacheUtil.keys(true)
return {
localCache: {
count: localKeys.length,
size: CacheUtil.size(false),
keys: localKeys,
},
sessionCache: {
count: sessionKeys.length,
size: CacheUtil.size(true),
keys: sessionKeys,
},
}
}Cache Cleanup Tool
// Regularly clean expired cache
const scheduleCacheCleanup = () => {
// Clean expired cache every hour
setInterval(
() => {
CacheUtil.cleanupExpired(false) // Clean local cache
CacheUtil.cleanupExpired(true) // Clean session cache
},
60 * 60 * 1000
)
}2. Performance Monitoring Tools
The framework has built-in performance monitoring functionality to help identify performance bottlenecks.
Performance Metrics Monitoring
// Performance monitoring configuration
const performanceMonitor = {
// Monitor FPS (frame rate)
monitorFPS: () => {
let lastTime = performance.now()
let frames = 0
const loop = () => {
frames++
const currentTime = performance.now()
if (currentTime - lastTime >= 1000) {
const fps = Math.round((frames * 1000) / (currentTime - lastTime))
console.log(`Current FPS: ${fps}`)
frames = 0
lastTime = currentTime
}
requestAnimationFrame(loop)
}
loop()
},
// Monitor memory usage
monitorMemory: () => {
if ('memory' in performance) {
const memory = (performance as any).memory
console.log(`Memory usage: ${Math.round(memory.usedJSHeapSize / 1024 / 1024)}MB`)
}
},
}Best Practices
1. Cache Strategy Selection
Choose Cache Strategy Based on Data Characteristics
- Static Data: Long-term cache (e.g., dictionary data, configuration information)
- Semi-static Data: Medium-term cache (e.g., product categories, user information)
- Dynamic Data: Short-term cache or real-time fetching (e.g., product inventory, order status)
Cache Level Design
- Memory Cache: Temporary data for current session
- Session Cache: Data valid during user session
- Local Cache: Configuration data valid for long term
2. Performance Optimization Techniques
Code Splitting Optimization
// Dynamic import optimization
const ProductEditor = defineAsyncComponent({
loader: () => import('@/views/product/Editor.vue'),
loadingComponent: LoadingComponent,
delay: 200, // Delay showing loading component
timeout: 3000, // Timeout duration
})Image Optimization Strategy
- Format Selection: Choose appropriate formats like WebP, JPEG, PNG based on scenario
- Size Optimization: Provide appropriately sized images based on display size
- Lazy Loading: Delay loading of non-first-screen images
- CDN Acceleration: Use CDN to accelerate image loading
3. Error Handling and Degradation
Cache Failure Handling
// Fault-tolerant handling for cache retrieval
const getCachedDataWithFallback = async (key: string, fallback: () => Promise<any>) => {
try {
const cached = CacheUtil.getLocal(key)
if (cached) return cached
const data = await fallback()
CacheUtil.setLocal(key, data)
return data
} catch (error) {
console.error('Cache processing failed:', error)
// Degrade to directly calling fallback
return fallback()
}
}Performance Monitoring Alerts
// Performance threshold monitoring
const performanceThresholds = {
fps: 30, // Minimum FPS threshold
memory: 100, // Maximum memory usage (MB)
loadTime: 3000, // Maximum load time (ms)
}
// Monitor performance and trigger alerts
const checkPerformance = () => {
const currentFPS = getCurrentFPS()
if (currentFPS < performanceThresholds.fps) {
console.warn('FPS too low, potential performance issue')
}
}Summary
The VJSP Vue3 framework provides a complete cache strategy and performance optimization solution. Through multi-level cache architecture, secure storage mechanisms, component cache optimization, and performance monitoring tools, it helps developers build high-performance enterprise-level applications.
In Product (demo) module development, properly applying cache strategies can significantly improve user experience and system performance. It's recommended to choose appropriate cache strategies based on specific business scenarios and continuously monitor and optimize application performance.
