当前位置: 首页 > news >正文

php+网站开发案例教程wordpress 好用插件推荐

php+网站开发案例教程,wordpress 好用插件推荐,做网站内容,wordpress标题字体大小二级缓存在项目中的应用 目录 1. 二级缓存简介2. 应用场景3. 重难点分析4. 结合SpringBoot使用5. 最佳实践与案例6. 总结 1. 二级缓存简介 1.1 什么是二级缓存 二级缓存#xff08;Second-Level Cache#xff09; 是Hibernate框架中的一个重要特性#xff0c;它提供了应…二级缓存在项目中的应用 目录 1. 二级缓存简介2. 应用场景3. 重难点分析4. 结合SpringBoot使用5. 最佳实践与案例6. 总结 1. 二级缓存简介 1.1 什么是二级缓存 二级缓存Second-Level Cache 是Hibernate框架中的一个重要特性它提供了应用程序级别的缓存机制。与一级缓存Session级别不同二级缓存是SessionFactory级别的缓存可以在多个Session之间共享数据。 1.2 缓存层次结构 应用层缓存架构 ├── 一级缓存 (L1 Cache) │ ├── Session级别 │ ├── 生命周期短 │ └── 自动管理 ├── 二级缓存 (L2 Cache) │ ├── SessionFactory级别 │ ├── 生命周期长 │ └── 需要配置 └── 查询缓存 (Query Cache)├── 查询结果缓存├── 依赖二级缓存└── 需要显式启用1.3 二级缓存的特点 跨Session共享: 多个Session可以共享缓存数据生命周期长: 与SessionFactory生命周期一致可配置性: 支持多种缓存提供者透明性: 对应用程序透明无需修改业务代码选择性缓存: 可以指定哪些实体需要缓存 1.4 支持的缓存提供者 缓存提供者特点适用场景EHCache成熟稳定功能丰富单机应用Redis分布式高性能集群环境Hazelcast内存网格分布式微服务架构Caffeine高性能低延迟高并发场景Infinispan企业级事务支持复杂业务场景2. 应用场景 2.1 适用场景 2.1.1 读多写少的场景 // 用户信息查询 - 读多写少 Entity Cacheable public class User {Idprivate Long id;private String username;private String email;// 用户信息变化不频繁适合缓存 }2.1.2 数据变化不频繁 // 字典数据 - 变化不频繁 Entity Cacheable public class Dictionary {Idprivate Long id;private String type;private String code;private String value;// 字典数据相对稳定适合缓存 }2.1.3 复杂查询结果 // 统计报表数据 - 复杂查询 Entity Cacheable public class ReportData {Idprivate Long id;private String reportType;private LocalDate reportDate;private BigDecimal amount;// 报表数据计算复杂适合缓存 }2.2 不适用场景 2.2.1 频繁更新的数据 // 实时数据 - 频繁更新 Entity public class RealTimeData {Idprivate Long id;private BigDecimal price;private LocalDateTime updateTime;// 价格数据实时变化不适合缓存 }2.2.2 敏感数据 // 用户密码 - 敏感数据 Entity public class UserCredentials {Idprivate Long id;private String password;private String salt;// 密码等敏感信息不应缓存 }2.3 典型应用案例 2.3.1 电商系统 // 商品信息缓存 Entity Cacheable Cache(usage CacheConcurrencyStrategy.READ_WRITE) public class Product {Idprivate Long id;private String name;private BigDecimal price;private String description;private String category;// 商品信息相对稳定适合缓存// 价格可能变化需要及时更新 }2.3.2 内容管理系统 // 文章内容缓存 Entity Cacheable Cache(usage CacheConcurrencyStrategy.READ_ONLY) public class Article {Idprivate Long id;private String title;private String content;private String author;private LocalDateTime publishTime;// 已发布的文章内容不变适合只读缓存 }2.3.3 用户权限系统 // 角色权限缓存 Entity Cacheable Cache(usage CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Role {Idprivate Long id;private String roleName;OneToMany(mappedBy role)private SetPermission permissions;// 角色权限变化不频繁适合缓存 }3. 重难点分析 3.1 技术难点 3.1.1 缓存一致性 难点: 保证缓存与数据库数据的一致性 解决方案: // 缓存一致性策略配置 Entity Cacheable Cache(usage CacheConcurrencyStrategy.READ_WRITE) public class User {Idprivate Long id;private String username;private String email;// 使用READ_WRITE策略保证一致性// 读操作从缓存获取// 写操作同时更新缓存和数据库 }// 缓存更新策略 Service public class UserService {Transactionalpublic User updateUser(User user) {// 1. 更新数据库User updatedUser userRepository.save(user);// 2. 清除相关缓存evictUserCache(user.getId());// 3. 重新加载到缓存loadUserToCache(updatedUser.getId());return updatedUser;}private void evictUserCache(Long userId) {// 清除用户相关缓存cacheManager.getCache(userCache).evict(userId);} }3.1.2 缓存穿透 难点: 查询不存在的数据导致缓存失效 解决方案: Service public class UserService {Cacheable(value userCache, key #id)public User findById(Long id) {User user userRepository.findById(id).orElse(null);if (user null) {// 缓存空值防止缓存穿透return new User(); // 返回空对象}return user;}// 布隆过滤器防止缓存穿透Autowiredprivate BloomFilterLong userBloomFilter;public User findByIdWithBloomFilter(Long id) {// 先检查布隆过滤器if (!userBloomFilter.mightContain(id)) {return null; // 确定不存在}return findById(id);} }3.1.3 缓存雪崩 难点: 大量缓存同时失效导致数据库压力 解决方案: Service public class UserService {Cacheable(value userCache, key #id)public User findById(Long id) {// 添加随机过期时间避免同时失效return userRepository.findById(id).orElse(null);}// 缓存预热PostConstructpublic void warmUpCache() {ListUser users userRepository.findAll();users.forEach(user - {cacheManager.getCache(userCache).put(user.getId(), user);});}// 熔断机制HystrixCommand(fallbackMethod getUserFallback)public User getUserWithCircuitBreaker(Long id) {return findById(id);}public User getUserFallback(Long id) {// 降级处理return new User();} }3.2 性能难点 3.2.1 内存管理 难点: 缓存占用大量内存 解决方案: // EHCache配置 Configuration public class CacheConfig {Beanpublic CacheManager cacheManager() {EhCacheManagerFactoryBean factory new EhCacheManagerFactoryBean();factory.setConfigLocation(new ClassPathResource(ehcache.xml));factory.setShared(true);EhCacheCacheManager cacheManager new EhCacheCacheManager();cacheManager.setCacheManager(factory.getObject());return cacheManager;} }// ehcache.xml配置 ?xml version1.0 encodingUTF-8? ehcachecache nameuserCachemaxEntriesLocalHeap1000maxEntriesLocalDisk10000eternalfalsetimeToIdleSeconds300timeToLiveSeconds600memoryStoreEvictionPolicyLRUdiskPersistentfalsediskExpiryThreadIntervalSeconds120/ /ehcache3.2.2 序列化性能 难点: 对象序列化影响性能 解决方案: // 使用高效的序列化方式 Configuration public class RedisConfig {Beanpublic RedisTemplateString, Object redisTemplate(RedisConnectionFactory factory) {RedisTemplateString, Object template new RedisTemplate();template.setConnectionFactory(factory);// 使用Jackson序列化Jackson2JsonRedisSerializerObject serializer new Jackson2JsonRedisSerializer(Object.class);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);return template;} }// 实体类优化 Entity Cacheable public class User implements Serializable {private static final long serialVersionUID 1L;Idprivate Long id;private String username;private String email;// 避免循环引用JsonIgnoreOneToMany(mappedBy user)private SetOrder orders; }3.3 业务难点 3.3.1 缓存策略选择 难点: 选择合适的缓存策略 解决方案: // 不同场景的缓存策略 Entity Cacheable public class Product {Idprivate Long id;private String name;private BigDecimal price;// 根据业务特点选择策略Cache(usage CacheConcurrencyStrategy.READ_WRITE)private String description; // 可读写Cache(usage CacheConcurrencyStrategy.READ_ONLY)private String category; // 只读Cache(usage CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)private Integer stock; // 非严格读写 }3.3.2 缓存更新策略 难点: 确定何时更新缓存 解决方案: Service public class ProductService {// 主动更新策略Transactionalpublic Product updateProduct(Product product) {Product updated productRepository.save(product);// 立即更新缓存cacheManager.getCache(productCache).put(product.getId(), updated);return updated;}// 延迟更新策略Transactionalpublic Product updateProductLazy(Product product) {Product updated productRepository.save(product);// 延迟更新缓存CompletableFuture.runAsync(() - {cacheManager.getCache(productCache).put(product.getId(), updated);});return updated;}// 版本控制策略EntityCacheablepublic class Product {Idprivate Long id;private String name;Versionprivate Long version; // 乐观锁版本// 版本变化时自动清除缓存} }4. 结合SpringBoot使用 4.1 环境准备 4.1.1 依赖配置 !-- pom.xml -- dependencies!-- Spring Boot Starter --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- Spring Boot Data JPA --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId/dependency!-- Spring Boot Cache --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-cache/artifactId/dependency!-- Hibernate Core --dependencygroupIdorg.hibernate/groupIdartifactIdhibernate-core/artifactId/dependency!-- EHCache --dependencygroupIdorg.hibernate/groupIdartifactIdhibernate-ehcache/artifactId/dependency!-- Redis --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependency /dependencies4.1.2 配置文件 # application.yml spring:datasource:url: jdbc:mysql://localhost:3306/testdbusername: rootpassword: passworddriver-class-name: com.mysql.cj.jdbc.Driverjpa:hibernate:ddl-auto: updateshow-sql: trueproperties:hibernate:cache:use_second_level_cache: trueuse_query_cache: trueregion:factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactoryformat_sql: truecache:type: ehcacheehcache:config: classpath:ehcache.xmlredis:host: localhostport: 6379password: timeout: 2000mslettuce:pool:max-active: 8max-wait: -1msmax-idle: 8min-idle: 04.2 基础配置 4.2.1 缓存配置类 Configuration EnableCaching public class CacheConfig {// EHCache配置Beanpublic CacheManager ehCacheManager() {EhCacheManagerFactoryBean factory new EhCacheManagerFactoryBean();factory.setConfigLocation(new ClassPathResource(ehcache.xml));factory.setShared(true);EhCacheCacheManager cacheManager new EhCacheCacheManager();cacheManager.setCacheManager(factory.getObject());return cacheManager;}// Redis配置Beanpublic RedisTemplateString, Object redisTemplate(RedisConnectionFactory factory) {RedisTemplateString, Object template new RedisTemplate();template.setConnectionFactory(factory);// 序列化配置Jackson2JsonRedisSerializerObject serializer new Jackson2JsonRedisSerializer(Object.class);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);return template;}// 缓存键生成器Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {Overridepublic Object generate(Object target, Method method, Object... params) {StringBuilder sb new StringBuilder();sb.append(target.getClass().getName());sb.append(method.getName());for (Object obj : params) {sb.append(obj.toString());}return sb.toString();}};} }4.2.2 EHCache配置文件 !-- ehcache.xml -- ?xml version1.0 encodingUTF-8? ehcache xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:noNamespaceSchemaLocationhttp://ehcache.org/ehcache.xsd!-- 默认缓存配置 --defaultCachemaxEntriesLocalHeap10000eternalfalsetimeToIdleSeconds120timeToLiveSeconds120maxEntriesLocalDisk10000000diskExpiryThreadIntervalSeconds120memoryStoreEvictionPolicyLRUpersistence strategylocalTempSwap//defaultCache!-- 用户缓存 --cache nameuserCachemaxEntriesLocalHeap1000eternalfalsetimeToIdleSeconds300timeToLiveSeconds600memoryStoreEvictionPolicyLRUdiskPersistentfalse/!-- 商品缓存 --cache nameproductCachemaxEntriesLocalHeap5000eternalfalsetimeToIdleSeconds600timeToLiveSeconds1200memoryStoreEvictionPolicyLRUdiskPersistentfalse/!-- 查询缓存 --cache namequeryCachemaxEntriesLocalHeap10000eternalfalsetimeToIdleSeconds300timeToLiveSeconds600memoryStoreEvictionPolicyLRUdiskPersistentfalse/ /ehcache4.3 实体类配置 4.3.1 基础实体类 Entity Table(name users) Cacheable Cache(usage CacheConcurrencyStrategy.READ_WRITE) public class User {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;Column(unique true, nullable false)private String username;Column(unique true, nullable false)private String email;Column(name created_at)private LocalDateTime createdAt;Column(name updated_at)private LocalDateTime updatedAt;// 关联实体不缓存避免循环引用OneToMany(mappedBy user, fetch FetchType.LAZY)JsonIgnoreprivate SetOrder orders new HashSet();// 构造方法public User() {}public User(String username, String email) {this.username username;this.email email;this.createdAt LocalDateTime.now();this.updatedAt LocalDateTime.now();}// Getter和Setter方法// ... }4.3.2 商品实体类 Entity Table(name products) Cacheable Cache(usage CacheConcurrencyStrategy.READ_WRITE) public class Product {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;Column(nullable false)private String name;Column(columnDefinition TEXT)private String description;Column(precision 10, scale 2)private BigDecimal price;Column(name category_id)private Long categoryId;Column(name stock_quantity)private Integer stockQuantity;Column(name created_at)private LocalDateTime createdAt;Column(name updated_at)private LocalDateTime updatedAt;// 构造方法public Product() {}public Product(String name, String description, BigDecimal price, Long categoryId) {this.name name;this.description description;this.price price;this.categoryId categoryId;this.stockQuantity 0;this.createdAt LocalDateTime.now();this.updatedAt LocalDateTime.now();}// Getter和Setter方法// ... }4.4 服务层实现 4.4.1 用户服务 Service Transactional public class UserService {Autowiredprivate UserRepository userRepository;Autowiredprivate CacheManager cacheManager;// 根据ID查找用户使用缓存Cacheable(value userCache, key #id)public User findById(Long id) {return userRepository.findById(id).orElseThrow(() - new EntityNotFoundException(User not found with id: id));}// 根据用户名查找用户Cacheable(value userCache, key #username)public User findByUsername(String username) {return userRepository.findByUsername(username).orElseThrow(() - new EntityNotFoundException(User not found with username: username));}// 保存用户清除相关缓存CacheEvict(value userCache, allEntries true)public User save(User user) {user.setUpdatedAt(LocalDateTime.now());return userRepository.save(user);}// 更新用户清除相关缓存CacheEvict(value userCache, key #user.id)public User update(User user) {user.setUpdatedAt(LocalDateTime.now());return userRepository.save(user);}// 删除用户清除相关缓存CacheEvict(value userCache, key #id)public void deleteById(Long id) {userRepository.deleteById(id);}// 批量清除缓存CacheEvict(value userCache, allEntries true)public void clearUserCache() {// 清除所有用户缓存}// 手动缓存管理public void evictUserCache(Long userId) {Cache cache cacheManager.getCache(userCache);if (cache ! null) {cache.evict(userId);}}public void putUserToCache(User user) {Cache cache cacheManager.getCache(userCache);if (cache ! null) {cache.put(user.getId(), user);}} }4.4.2 商品服务 Service Transactional public class ProductService {Autowiredprivate ProductRepository productRepository;Autowiredprivate CacheManager cacheManager;// 根据ID查找商品Cacheable(value productCache, key #id)public Product findById(Long id) {return productRepository.findById(id).orElseThrow(() - new EntityNotFoundException(Product not found with id: id));}// 根据分类查找商品Cacheable(value productCache, key category: #categoryId)public ListProduct findByCategoryId(Long categoryId) {return productRepository.findByCategoryId(categoryId);}// 搜索商品Cacheable(value productCache, key search: #keyword)public ListProduct searchProducts(String keyword) {return productRepository.findByNameContainingIgnoreCase(keyword);}// 保存商品CacheEvict(value productCache, allEntries true)public Product save(Product product) {product.setUpdatedAt(LocalDateTime.now());return productRepository.save(product);}// 更新商品CacheEvict(value productCache, key #product.id)public Product update(Product product) {product.setUpdatedAt(LocalDateTime.now());return productRepository.save(product);}// 更新库存CacheEvict(value productCache, key #productId)public Product updateStock(Long productId, Integer quantity) {Product product findById(productId);product.setStockQuantity(quantity);product.setUpdatedAt(LocalDateTime.now());return productRepository.save(product);}// 条件更新缓存CacheEvict(value productCache, condition #product.price 100)public Product updateExpensiveProduct(Product product) {return productRepository.save(product);} }4.5 控制器层 4.5.1 用户控制器 RestController RequestMapping(/api/users) public class UserController {Autowiredprivate UserService userService;// 获取用户信息GetMapping(/{id})public ResponseEntityUser getUser(PathVariable Long id) {try {User user userService.findById(id);return ResponseEntity.ok(user);} catch (EntityNotFoundException e) {return ResponseEntity.notFound().build();}}// 创建用户PostMappingpublic ResponseEntityUser createUser(RequestBody User user) {User savedUser userService.save(user);return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);}// 更新用户PutMapping(/{id})public ResponseEntityUser updateUser(PathVariable Long id, RequestBody User user) {try {user.setId(id);User updatedUser userService.update(user);return ResponseEntity.ok(updatedUser);} catch (EntityNotFoundException e) {return ResponseEntity.notFound().build();}}// 删除用户DeleteMapping(/{id})public ResponseEntityVoid deleteUser(PathVariable Long id) {try {userService.deleteById(id);return ResponseEntity.noContent().build();} catch (EntityNotFoundException e) {return ResponseEntity.notFound().build();}}// 清除用户缓存PostMapping(/cache/clear)public ResponseEntityString clearUserCache() {userService.clearUserCache();return ResponseEntity.ok(User cache cleared successfully);} }4.5.2 商品控制器 RestController RequestMapping(/api/products) public class ProductController {Autowiredprivate ProductService productService;// 获取商品信息GetMapping(/{id})public ResponseEntityProduct getProduct(PathVariable Long id) {try {Product product productService.findById(id);return ResponseEntity.ok(product);} catch (EntityNotFoundException e) {return ResponseEntity.notFound().build();}}// 根据分类获取商品GetMapping(/category/{categoryId})public ResponseEntityListProduct getProductsByCategory(PathVariable Long categoryId) {ListProduct products productService.findByCategoryId(categoryId);return ResponseEntity.ok(products);}// 搜索商品GetMapping(/search)public ResponseEntityListProduct searchProducts(RequestParam String keyword) {ListProduct products productService.searchProducts(keyword);return ResponseEntity.ok(products);}// 创建商品PostMappingpublic ResponseEntityProduct createProduct(RequestBody Product product) {Product savedProduct productService.save(product);return ResponseEntity.status(HttpStatus.CREATED).body(savedProduct);}// 更新商品PutMapping(/{id})public ResponseEntityProduct updateProduct(PathVariable Long id, RequestBody Product product) {try {product.setId(id);Product updatedProduct productService.update(product);return ResponseEntity.ok(updatedProduct);} catch (EntityNotFoundException e) {return ResponseEntity.notFound().build();}}// 更新库存PutMapping(/{id}/stock)public ResponseEntityProduct updateStock(PathVariable Long id, RequestParam Integer quantity) {try {Product product productService.updateStock(id, quantity);return ResponseEntity.ok(product);} catch (EntityNotFoundException e) {return ResponseEntity.notFound().build();}} }4.6 查询缓存 4.6.1 查询缓存配置 Repository public class UserRepository extends JpaRepositoryUser, Long {// 启用查询缓存QueryHints(QueryHint(name org.hibernate.cacheable, value true))Query(SELECT u FROM User u WHERE u.username :username)OptionalUser findByUsername(Param(username) String username);// 复杂查询缓存QueryHints(QueryHint(name org.hibernate.cacheable, value true))Query(SELECT u FROM User u WHERE u.createdAt :startDate AND u.createdAt :endDate)ListUser findUsersByDateRange(Param(startDate) LocalDateTime startDate, Param(endDate) LocalDateTime endDate);// 统计查询缓存QueryHints(QueryHint(name org.hibernate.cacheable, value true))Query(SELECT COUNT(u) FROM User u WHERE u.createdAt :startDate)Long countUsersSince(Param(startDate) LocalDateTime startDate); }4.6.2 查询缓存服务 Service public class UserQueryService {Autowiredprivate UserRepository userRepository;// 缓存查询结果Cacheable(value queryCache, key users_by_date: #startDate _ #endDate)public ListUser findUsersByDateRange(LocalDateTime startDate, LocalDateTime endDate) {return userRepository.findUsersByDateRange(startDate, endDate);}// 缓存统计结果Cacheable(value queryCache, key user_count_since: #startDate)public Long countUsersSince(LocalDateTime startDate) {return userRepository.countUsersSince(startDate);}// 清除查询缓存CacheEvict(value queryCache, allEntries true)public void clearQueryCache() {// 清除所有查询缓存} }5. 最佳实践与案例 5.1 缓存策略最佳实践 5.1.1 缓存粒度控制 // 细粒度缓存 - 单个实体 Cacheable(value userCache, key #id) public User findById(Long id) {return userRepository.findById(id).orElse(null); }// 粗粒度缓存 - 列表数据 Cacheable(value userListCache, key all_users) public ListUser findAllUsers() {return userRepository.findAll(); }// 条件缓存 - 根据条件决定是否缓存 Cacheable(value userCache, key #id, condition #id 0) public User findByIdConditional(Long id) {return userRepository.findById(id).orElse(null); }5.1.2 缓存更新策略 Service public class CacheUpdateService {Autowiredprivate CacheManager cacheManager;// 立即更新策略CachePut(value userCache, key #user.id)public User updateUserImmediate(User user) {return userRepository.save(user);}// 延迟更新策略AsyncCacheEvict(value userCache, key #user.id)public void updateUserLazy(User user) {userRepository.save(user);// 异步更新缓存CompletableFuture.runAsync(() - {putUserToCache(user);});}// 批量更新策略CacheEvict(value userCache, allEntries true)public void batchUpdateUsers(ListUser users) {userRepository.saveAll(users);} }5.2 性能优化案例 5.2.1 缓存预热 Component public class CacheWarmupService {Autowiredprivate UserService userService;Autowiredprivate ProductService productService;EventListener(ApplicationReadyEvent.class)public void warmupCache() {// 预热用户缓存warmupUserCache();// 预热商品缓存warmupProductCache();}private void warmupUserCache() {ListUser users userService.findAll();users.forEach(user - {userService.findById(user.getId()); // 触发缓存});}private void warmupProductCache() {ListProduct products productService.findAll();products.forEach(product - {productService.findById(product.getId()); // 触发缓存});} }5.2.2 缓存监控 Component public class CacheMonitorService {Autowiredprivate CacheManager cacheManager;// 获取缓存统计信息public MapString, Object getCacheStats() {MapString, Object stats new HashMap();cacheManager.getCacheNames().forEach(cacheName - {Cache cache cacheManager.getCache(cacheName);if (cache instanceof EhCache) {EhCache ehCache (EhCache) cache;MapString, Object cacheStats new HashMap();cacheStats.put(hitCount, ehCache.getStatistics().getCacheHits());cacheStats.put(missCount, ehCache.getStatistics().getCacheMisses());cacheStats.put(hitRate, ehCache.getStatistics().getCacheHitPercentage());stats.put(cacheName, cacheStats);}});return stats;}// 清理过期缓存Scheduled(fixedRate 300000) // 每5分钟执行一次public void cleanExpiredCache() {cacheManager.getCacheNames().forEach(cacheName - {Cache cache cacheManager.getCache(cacheName);if (cache instanceof EhCache) {((EhCache) cache).getNativeCache().evictExpiredElements();}});} }5.3 实际应用案例 5.3.1 电商系统缓存方案 // 商品详情页缓存策略 Service public class ProductDetailService {Autowiredprivate ProductService productService;Autowiredprivate ProductReviewService reviewService;// 商品详情页数据聚合Cacheable(value productDetailCache, key #productId)public ProductDetailVO getProductDetail(Long productId) {Product product productService.findById(productId);ListProductReview reviews reviewService.findByProductId(productId);ProductStatistics stats productService.getProductStatistics(productId);return ProductDetailVO.builder().product(product).reviews(reviews).statistics(stats).build();}// 商品列表页缓存Cacheable(value productListCache, key #categoryId _ #page _ #size)public PageProduct getProductList(Long categoryId, int page, int size) {return productService.findByCategoryId(categoryId, PageRequest.of(page, size));} }5.3.2 用户权限缓存方案 // 用户权限缓存 Service public class UserPermissionService {Autowiredprivate UserRepository userRepository;Autowiredprivate RoleRepository roleRepository;// 用户权限缓存Cacheable(value userPermissionCache, key #userId)public UserPermissionVO getUserPermissions(Long userId) {User user userRepository.findById(userId).orElse(null);if (user null) {return null;}SetRole roles user.getRoles();SetPermission permissions new HashSet();roles.forEach(role - {permissions.addAll(role.getPermissions());});return UserPermissionVO.builder().userId(userId).roles(roles).permissions(permissions).build();}// 权限检查public boolean hasPermission(Long userId, String permission) {UserPermissionVO userPermissions getUserPermissions(userId);if (userPermissions null) {return false;}return userPermissions.getPermissions().stream().anyMatch(p - p.getName().equals(permission));} }6. 总结 6.1 二级缓存优势 性能提升: 减少数据库访问提高响应速度可扩展性: 支持多种缓存提供者适应不同场景透明性: 对业务代码透明无需修改现有逻辑灵活性: 支持细粒度缓存控制可配置缓存策略 6.2 使用建议 合理选择缓存策略: 根据数据特点选择合适的并发策略注意缓存一致性: 确保缓存与数据库数据的一致性监控缓存性能: 定期监控缓存命中率和性能指标合理设置过期时间: 根据业务需求设置合适的缓存过期时间避免缓存雪崩: 使用随机过期时间避免同时失效 6.3 注意事项 内存管理: 注意缓存占用内存合理配置缓存大小序列化性能: 选择高效的序列化方式缓存穿透: 防止查询不存在数据导致缓存失效缓存雪崩: 避免大量缓存同时失效数据一致性: 确保缓存与数据库数据的一致性 二级缓存是提升应用性能的重要手段合理使用可以显著提高系统响应速度和用户体验。在实际应用中需要根据具体业务场景选择合适的缓存策略和配置参数。
http://www.pierceye.com/news/495611/

相关文章:

  • 小米4路由器可以做网站嘛服务类网站建设服务公司
  • 电子商务网站建设规划书实例注册微信公众平台
  • 网站设计课程总结线上营销方案
  • 谷城网站建设网站集群建设实施方案
  • 怎么做外贸生意谷歌seo服务
  • 做网站好还是做淘宝好市场调研模板
  • 网站做换肤做一个平台费用是多少
  • 省内注销二建 建设部网站更新慢网站建设合同书封皮
  • 天津城市建设网站营销型网站的好处
  • 网站建设维护文档好看的页面
  • 网站搜索优化官网网站建设在电子商务中的作用的看法
  • 网站推广费用价格html大屏展示模板
  • 编辑网站用什么软件网站开发人员职责
  • 网站搜索引擎提交wordpress发布站点
  • 阳春网站建设天水网站seo
  • 仙桃市建设局网站wordpress链接前面的图标
  • 温州市城乡建设建档案馆网站公司装修费用可以一次性入账吗
  • 房地产开发公司网站宠物网页设计模板
  • 网站备案信息可以改吗中国做二手房最大的网站
  • 设计 企业网站罗湖网站-建设深圳信科
  • 太原自助模板建站手机版电脑qq登录入口
  • 公司网站建设哪家比较好app 网站
  • 建设银行个人网站打不开个人主页模板下载
  • 山西建设公司网站wordpress视频适应手机端
  • 原型样网站做一般的公司门户网站投资额
  • 南宁百度网站公司电话网站配置优化
  • 德州网站建设的公司免费注册公司怎么注册
  • 成都开发网站建设中国建设规划采购网站
  • 企业网站建设应避免数据孤岛深圳东莞网站建设
  • pk10网站怎么做郑州seo费用