大号在练葵花宝典 发表于 2024-11-27 12:57:56

电商项目高级篇06-缓存

缓存
流程图:
https://i-blog.csdnimg.cn/direct/686a528d6a3a4d958ad8779e284ec68e.png
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

创建镜像挂载
https://i-blog.csdnimg.cn/direct/d983324b4d7644cfa424d838bdc48b21.png
在redis文件夹下网络下载redis.conf文件
wget http://download.redis.io/redis-stable/redis.conf

去编辑redis.conf文件
https://i-blog.csdnimg.cn/direct/bbfa1e76c79647eaa5e8bc3afd0761eb.png
注释后代表恣意ip访问
https://i-blog.csdnimg.cn/direct/f8bee5d6854a4ddc80bc2d9d4d707d72.png
设置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
https://i-blog.csdnimg.cn/direct/6ab3342dc1aa49d18d0da5522892cbb5.png
2、项目整合redis

1、pom.xml引入依靠
<!--整合redis-->
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
2、application.yml设置redis设置信息
https://i-blog.csdnimg.cn/direct/74caaecea1c741ffa61f7666592150fc.png
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);
    }
https://i-blog.csdnimg.cn/direct/0d484d3362cb479f91154e4102908b95.png
测试用例执行乐成,控制台输出redis的值。
查抄redis里是否有这个值
https://i-blog.csdnimg.cn/direct/ee1d85b73f654ac5a0d7650c75b4fad1.png
集成redis是乐成的

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 电商项目高级篇06-缓存