电商项目高级篇06-缓存

电商项目高级篇06-缓存

缓存

流程图:

复制代码
data = cache.load(id);//从缓存加载数据
If(data == null){
data = db.load(id);//从数据库加载数据
cache.put(id,data);//保存到 cache 中
}
return data;

在我们的单体项目中可以用Map作为本地缓存,速度还很快。但是分布式项目。由于有多个服务。每次负载均衡到服务时,可能都不命中本地缓存,本地缓存不会在多个服务间生效。所以应该集成分布式缓存:比如redis

1、docker下启动redis

docker下载redis镜像

复制代码
docker pull redis

创建镜像挂载

在redis文件夹下网络下载redis.conf文件

复制代码
wget http://download.redis.io/redis-stable/redis.conf

去编辑redis.conf文件

注释后代表任意ip访问

设置redis密码

appendonly yes:redis持久化

##最后挂载永久启动redis

复制代码
docker run --restart=always --log-opt max-size=100m --log-opt max-file=2 -p 6379:6379 --name myredis -v /mydata/redis/redis.conf:/etc/redis/redis.conf -v /home/redis/data:/data -d redis redis-server /etc/redis/redis.conf --appendonly yes  --requirepass 123456

然后我们用rdm工具连上redis

2、项目整合redis

1、pom.xml引入依赖

复制代码
 <!--整合redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、application.yml配置redis配置信息

3、使用RedisTemplate操作redis

复制代码
	@Autowired
    StringRedisTemplate stringRedisTemplate;

	@Test
    public void testRedis(){
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.set("hello","world_"+ UUID.randomUUID().toString());
        String hello = ops.get("hello");
        System.out.println(hello);
    }

测试用例执行成功,控制台输出redis的值。

检查redis里是否有这个值

集成redis是成功的

3、redis改造三级分类业务

CategoryServiceImpl

复制代码
	 @Autowired
    private StringRedisTemplate redisTemplate;


 	@Override
    public Map<String, List<Catelog2Vo>> getCatalog() {
        // 1、获取缓存中的数据
        String catalog = redisTemplate.opsForValue().get("catalog");
        if (StrUtil.isBlank(catalog)) {
            // 2、从数据库中获取数据
            Map<String, List<Catelog2Vo>> catalogDb = this.getCatalogDb();
            // 3、缓存数据
            redisTemplate.opsForValue().set("catalog", JSON.toJSONString(catalogDb));
            return catalogDb;
        }
       // 将缓存中的数据返回
        return JSON.parseObject(catalog,Map.class);
    }
相关推荐
-Xie-4 小时前
Redis(二)——数据类型二
数据库·redis·缓存
似水流年QC9 小时前
深入 Pinia 工作原理:响应式核心、持久化机制与缓存策略
缓存·pinia·持久化·缓存策略
明月与玄武17 小时前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
JH307318 小时前
《Redis 经典应用场景(一):缓存、分布式锁与限流》
redis·分布式·缓存
苦学编程的谢18 小时前
Redis_4_常见命令(完)+认识数据类型和编码方式
数据库·redis·缓存
大G的笔记本1 天前
高频 Redis 面试题答案解析
数据库·redis·缓存
m0_748248021 天前
Redis的数据淘汰策略解读
数据库·redis·缓存
Freed&1 天前
《Nginx进阶实战:反向代理、负载均衡、缓存优化与Keepalived高可用》
nginx·缓存·负载均衡
Irene19911 天前
前端缓存技术和使用场景
前端·缓存