电商项目高级篇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);
    }
相关推荐
Kookoos2 小时前
Redis + ABP vNext 构建分布式高可用缓存架构
redis·分布式·缓存·架构·c#·.net
菜鸟茜4 小时前
从银行排队到零钱支付:用“钱包经济学”重构Java缓存认知
缓存
爱刘温柔的小猪19 小时前
Redis+Caffeine构造多级缓存
redis·spring·缓存
hello1114-19 小时前
Redis学习打卡-Day2-缓存更新策略、主动更新策略、缓存穿透、缓存雪崩、缓存击穿
java·redis·学习·缓存·javaweb
码农飞哥1 天前
互联网大厂Java求职面试实战:Spring Boot到微服务的技术问答解析
java·spring boot·缓存·面试·消息队列·技术栈·microservices
?abc!2 天前
缓存(3):本地缓存作用 及 数据一致性 实现策略
缓存
Toky Zhu2 天前
ubuntu清除缓存
linux·ubuntu·缓存
呦呦鹿鸣Rzh2 天前
redis
数据库·redis·缓存
只因只因爆2 天前
spark的缓存
大数据·缓存·spark
摘星编程2 天前
Redis+Caffeine构建高性能二级缓存
数据库·redis·缓存