分类数据一般情况下不会做过多的修改,因此可以将分类数据进行缓存,以提高页面的加载速度。
1 使用缓存
先将首页接口获取一级分类数据缓存
步骤:
1、在service-product微服务中集成Spring Data Redis,如下所示:
在service-product的pom.xml文件中添加如下依赖:
<!-- redis的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在application-dev.yml文件中添加如下Redis的相关配置:
spring:
# Redis的相关配置
data:
redis:
host: 192.168.136.142
port: 6379
password: 1234DAS
2、对CategoryServiceImpl的findOneCategory方法进行改造,如下所示:
package com.atguigu.spzx.product.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis 配置类,用于配置 RedisTemplate 的相关属性,以满足项目对 Redis 操作的需求。
* 该类通过 Spring 的 Java 配置方式,创建并定制 RedisTemplate 实例。
*
* @version: java version 1.8
* @Author: Mr Orange
* @description: 此配置类的主要目的是对 RedisTemplate 进行序列化配置,
* 使得 Redis 能够以合适的格式存储和读取数据。
* @date: 2025-02-11 17:40
*/
@Configuration
public class RedisConfig {
/**
* 创建并配置一个 RedisTemplate 实例,用于与 Redis 进行交互。
* 使用 @Bean 注解将该方法返回的对象注册为 Spring 容器中的 Bean,
* 使用 @Primary 注解表示当存在多个 RedisTemplate Bean 时,优先使用此 Bean。
*
* @param redisConnectionFactory Redis 连接工厂,用于创建 Redis 连接
* @return 配置好的 RedisTemplate 实例
*/
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 创