当前位置: 代码迷 >> 综合 >> CommandLineRunner在微服务启动类之中的运用
  详细解决方案

CommandLineRunner在微服务启动类之中的运用

热度:25   发布时间:2024-01-26 10:45:16.0

CommandLineRunner 在复用启动后执行,最普遍的用处就是打印日志标识服务启动成功;

其二可以在服务启动成功后设置一些开关值;比如MQ消费者在服务启动过程中接收到消息,这时可能导致消息的丢失;

如下代码,当 isOpen = false 时表示服务启动中,此时可以代码里加上使消息重回消息队列等操作,等服务启动成功后再消费;

其他涉及服务启动状态的业务场景可灵活使用CommandLineRunner。

@MapperScan(basePackages = {"com.xx.**.mapper"})
@EnableFeignClients(basePackages={"com.xx"})
@SpringBootApplication(scanBasePackages = "com.xx")
@EnableScheduling
@EnableAsync
public class AllApplication implements CommandLineRunner{protected final Logger log = LoggerFactory.getLogger(getClass());public static void main(String[] args) {SpringApplication.run(AllApplication.class, args);}@Overridepublic void run(String... strings) throws Exception {SwitchUtil.getInstance().setOpen(true);log.info("======SwitchUtil open======");log.info(">>>>>>>>>>>>>>>[AllApplication start success]<<<<<<<<<<<<<");}
}public class SwitchUtil {private boolean isOpen;private static SwitchUtil switchUtil = new  SwitchUtil();private SwitchUtil() {}public static SwitchUtil getInstance() {return switchUtil;}public boolean isOpen() {return isOpen;}public void setOpen(boolean open) {isOpen = open;}
}

 

 

  相关解决方案