电商项目高级篇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);
    }
相关推荐
拾贰_C14 小时前
【English | conversation 】call | 抖音AI短句情景:打电话---come over
数据库·redis·缓存
ShineWinsu17 小时前
对于Redis:缓存的解析
java·redis·缓存·缓存穿透·缓存击穿·缓存雪崩·缓存预热
害人终害己17 小时前
redis修改密码的地方在哪里
数据库·redis·缓存
小静AI工程实验室18 小时前
robots.txt 不是门禁:RFC 9309 规则、缓存与 Python 爬虫的 10 个边界
爬虫·python·缓存
for_ever_love__18 小时前
缓存穿透、击穿、雪崩:三个经典问题与完整解决方案
java·数据库·redis·缓存·哈希算法·布隆过滤器·雪崩
hweiyu001 天前
Redis命令:HSTRLEN
redis·缓存
ShineWinsu2 天前
对于Redis:主从复制的解析
linux·数据库·c++·redis·缓存·面试·主从复制
ShineWinsu2 天前
对于Redis:事务的解析
数据库·redis·mysql·缓存·面试·事务·acid
JavaPub-rodert2 天前
公共 Docker 镜像源总失效?用 Harbor Proxy Cache 自建 Docker Hub 镜像缓存
java·缓存·docker
hweiyu002 天前
Redis命令:HRANDFIELD
redis·缓存