SpringBoot项目初始化讲解实现缓存预热

场景:将一千万用户白名单load缓存,用户请求的时候判断该用户是否是缓存里面的用户

SpringBoot实现初始化加载配置

Step1:采用实现springboot ApplicationRunner

该方法仅在SpringApplication.run(…)完成之前调用

Step2:采用实现InitializingBean

InitializaingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet()方法。

在spring初始化bean的时候,如果bean实现了InitializingBean接口

在对象的所有属性被初始化之后才会调用afterPropertiesSet()方法。

使用方式

Step1:实现方法继承接口

以上两种方式推荐使用第二种,两种方式分别重写各自方法,都只有一个方法

Step2:重写方法调用load数据

像我下面的方法就是简单的查数据库 然后写入缓存

在调用InitializaingBean接口重写的afterPropertiesSet()方法里直接调用,就能项目初始化load进去了

    @Override
    public void selectUserScore() {
        List<UserScore> userScoreList = userScoreMapper.selectUserScore();
        userScoreList.forEach(userScoreLists -> {
            String key = userScoreLists.getId() + ":" + userScoreLists.getUserName();
            //写入Redis
            redisService.zAdd(RedisKeyManager.SALESCORE,key,userScoreLists.getUserScore());
        });
    }
        @Override
    public void afterPropertiesSet() throws Exception {
        selectUserScore();
    }

猜你喜欢

转载自blog.csdn.net/q736317048/article/details/113858147