SpringBoot项目启动时初始化缓存资源

在实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池、提前加载mysql数据库到缓存等。Springboot中CommandLineRunner接口的 Component 会在所有 Spring Beans都初始化之后SpringApplication.run()之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。

package com.xf.zhang.init;

import com.xf.zhang.mapper.UserMapper;
import com.xf.zhang.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class MyStartupRunner implements CommandLineRunner {

    private Logger logger= LoggerFactory.getLogger(MyStartListener.class);

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Override
    public void run(String... strings) throws Exception {

        List list= userMapper.selectAll();
        list.forEach(action->{
            redisTemplate.opsForZSet().add("userList",action,action.getId());
            logger.info(action.toString());
        });

    }
}

 

你可能感兴趣的:(SpringBoot)