zoukankan      html  css  js  c++  java
  • 多级缓存-redis缓存预热

    冷启动:服务刚刚启动时,Redis中并没有缓存,如果所有商品数据都在第一次查询时添加缓存,可能会给数据库带来较大压力。

    缓存预热:在实际开发中,我们可以利用大数据统计用户访问的热点数据,在项目启动时将这些热点数据提前查询并保存到Redis中。

    我们数据量较少,可以在启动时将所有数据都放入缓存中。

    缓存预热示例
    1.安装redis
    2.在item-service服务中引入Redis依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    3.配置redis地址

    spring:
      redis:
        host: localhost
        password: 123456

    4.编写初始化类

    @Component
    @Slf4j
    public class RedisHandler implements InitializingBean {
    
        @Autowired
        private StringRedisTemplate redisTemplate;
    
        @Autowired
        private IItemService itemService;
        @Autowired
        private IItemStockService stockService;
    
        private static final ObjectMapper MAPPER = new ObjectMapper();
    
        @Override
        public void afterPropertiesSet() throws Exception {
            // 初始化缓存
            // 1.查询商品信息
            List<Item> itemList = itemService.list();
            // 2.放入缓存
            for (Item item : itemList) {
                // 2.1.item序列化为JSON
                String json = MAPPER.writeValueAsString(item);
                // 2.2.存入redis
                redisTemplate.opsForValue().set("item:id:" + item.getId(), json);
            }
    
            // 3.查询商品库存信息
            List<ItemStock> stockList = stockService.list();
            // 4.放入缓存
            for (ItemStock stock : stockList) {
                // 2.1.item序列化为JSON
                String json = MAPPER.writeValueAsString(stock);
                // 2.2.存入redis
                redisTemplate.opsForValue().set("item:stock:id:" + stock.getId(), json);
            }
            
            log.info("缓存预热初始化结束");
        }
    
        public void saveItem(Item item) {
            try {
                String json = MAPPER.writeValueAsString(item);
                redisTemplate.opsForValue().set("item:id:" + item.getId(), json);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    
        public void deleteItemById(Long id) {
            redisTemplate.delete("item:id:" + id);
        }
    }
  • 相关阅读:
    Http方法:Get请求与Post请求的区别
    udev和rules使用规则
    c++中的动态内存分配
    c++中重载运算符
    c++中静态成员函数
    c++中值传递,址传递,引用传递
    c++中实现单例模式singleton class
    [Windows篇] 在windows 10上源码编译gtest 并编写CMakeLists.txt
    [Ubuntu篇] 在ubuntu上源码编译gtest,编写gtest-config.cmake并测试
    使用boost data_time模块来获取毫秒级时间并转换为string字符串
  • 原文地址:https://www.cnblogs.com/linjiqin/p/15438803.html
Copyright © 2011-2022 走看看