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);
        }
    }
  • 相关阅读:
    jQuery之五:CheckBox控制
    WinServer2003 设置之:xp风格
    ASP.net: cookie
    ASP.NET之:URL重写(转载)
    jQuery 之二:Ajax加载Json数据
    jQuery 之一:对象插件
    Asp.net:Form
    jQuery之四:Table过滤
    jQuery之三:Tab控制
    Opera 9.01 Build 8543
  • 原文地址:https://www.cnblogs.com/linjiqin/p/15438803.html
Copyright © 2011-2022 走看看