importcom.netflix.appinfo.ApplicationInfoManager;importcom.netflix.appinfo.InstanceInfo;importcom.netflix.config.DynamicPropertyFactory;importcom.netflix.discovery.DefaultEurekaClientConfig;importcom.netflix.discovery.DiscoveryManager;importlombok.extern.slf4j.Slf4j;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;/** * Created by Kowalski on 2017/5/18 * Updated by Kowalski on 2017/5/18 */@Slf4jpublicclassEurekaInitAndRegisterListenerimplementsServletContextListener { /** * * Notification that the web application initialization * * process is starting. * * All ServletContextListeners are notified of context * * initialization before any filter or servlet in the web * * application is initialized. * * @param sce */ @OverridepublicvoidcontextInitialized(ServletContextEvent sce) {registerWithEureka(); }publicvoidregisterWithEureka() {/**加载本地配置文件 根据配置初始化这台 Eureka Application Service 并且注册到 Eureka Server*/DiscoveryManager.getInstance().initComponent(newMyInstanceConfig(),newDefaultEurekaClientConfig());/**本台 Application Service 已启动,准备好侍服网络请求*/ApplicationInfoManager.getInstance().setInstanceStatus(InstanceInfo.InstanceStatus.UP);log.info("o2o eureka Application Service initing and registering");/**Application Service 的 Eureka Server 初始化以及注册是异步的,需要一段时间 此处等待初始化及注册成功 可去除*/// private static final DynamicPropertyFactory configInstance = DynamicPropertyFactory// .getInstance();// String vipAddress = configInstance.getStringProperty(// "eureka.vipAddress", "o2o").get();// InstanceInfo nextServerInfo = null;// while (nextServerInfo == null) {// try {// nextServerInfo = DiscoveryManager.getInstance()// .getDiscoveryClient()// .getNextServerFromEureka(vipAddress, false);// } catch (Throwable e) {// log.info("Waiting for service to register with eureka..");// try {// Thread.sleep(10000);// } catch (InterruptedException e1) {// e1.printStackTrace();// }// }// }// log.info("Service started and ready to process requests.."); } /** * * Notification that the servlet context is about to be shut down. * * All servlets and filters have been destroy()ed before any * * ServletContextListeners are notified of context * * destruction. * * @param sce */ @OverridepublicvoidcontextDestroyed(ServletContextEvent sce) {DiscoveryManager.getInstance().shutdownComponent(); }}