@Component("InitRedisData")
public class InitRedisData implements ApplicationListener<ContextRefreshedEvent>{
@Autowired
private ReservationConfigService reservationConfigService;
@Autowired
private JedisClient jedisClient;
@Value("${RESERVATION_CONFIG}")
private String RESERVATION_CONFIG; //可以多次使用
public static int isStart = 1;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(isStart==1){
System.out.println("容器启动............"+isStart);
isStart++;
}else if(isStart==2){
System.out.println("容器启动............"+isStart);
isStart++;
}else{
System.err.println("容器启动............"+isStart);
try {
String json = jedisClient.hget(RESERVATION_CONFIG, "1");
//缓存中存在,则把json转为结果对象;否则不执行
if(StringUtils.isBlank(json)){
ReservationConfig configSave = (ReservationConfig) reservationConfigService.getOne("1", ReservationConfig.class);
System.out.println(RESERVATION_CONFIG);
jedisClient.hset(RESERVATION_CONFIG, "1", JsonUtils.objectToJson(configSave));
System.out.println("添加成功");
}else{
System.out.println("缓存存在");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("系统配置查询缓存异常");
}
}
}
}
public class InitRedisData implements ApplicationListener<ContextRefreshedEvent>{
@Autowired
private ReservationConfigService reservationConfigService;
@Autowired
private JedisClient jedisClient;
@Value("${RESERVATION_CONFIG}")
private String RESERVATION_CONFIG; //可以多次使用
public static int isStart = 1;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(isStart==1){
System.out.println("容器启动............"+isStart);
isStart++;
}else if(isStart==2){
System.out.println("容器启动............"+isStart);
isStart++;
}else{
System.err.println("容器启动............"+isStart);
try {
String json = jedisClient.hget(RESERVATION_CONFIG, "1");
//缓存中存在,则把json转为结果对象;否则不执行
if(StringUtils.isBlank(json)){
ReservationConfig configSave = (ReservationConfig) reservationConfigService.getOne("1", ReservationConfig.class);
System.out.println(RESERVATION_CONFIG);
jedisClient.hset(RESERVATION_CONFIG, "1", JsonUtils.objectToJson(configSave));
System.out.println("添加成功");
}else{
System.out.println("缓存存在");
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("系统配置查询缓存异常");
}
}
}
}
注意:网上很多文章说onApplicationEvent值行两次,但是经过测试,其实onApplicationEvent被执行了三次
在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。这是网上这么说,其实我还想研究还有一次是谁执行的希望有知道的留言一块沟通
所以想要初始化一些数据,可以像我一样选择在其中任意一次进行数据的加载。