监听服务的四种实现方式,以监听 Nacos 服务为例
1. 传统方式
public void subscribe() { try { NamingService namingService = NamingFactory.createNamingService("127.0.0.1:8848"); namingService.subscribe("serverName","groupName",new EventListener() { @Override public void onEvent(Event event) { if (event instanceof NamingEvent) { System.out.println("服务名:"+((NamingEvent)event).getServiceName()); System.out.println("实例:"+((NamingEvent)event).getInstances()); } } }); } catch (NacosException e) { logger.error(e.getMessage(), e); } }
2. 简写方式
public void subscribe() { try { NamingService namingService = NamingFactory.createNamingService("127.0.0.1:8848"); namingService.subscribe("serverName","groupName", event -> { if (event instanceof NamingEvent) { System.out.println("服务名:"+((NamingEvent)event).getServiceName()); System.out.println("实例:"+((NamingEvent)event).getInstances()); } }); } catch (NacosException e) { logger.error(e.getMessage(), e); } }
3. 独立方法
public void subscribe() { try { NamingService namingService = NamingFactory.createNamingService("127.0.0.1:8848"); namingService.subscribe("serverName","groupName", serviceListener); } catch (NacosException e) { logger.error(e.getMessage(), e); } } EventListener serviceListener = (event) -> { if (event instanceof NamingEvent) { System.out.println("服务名:"+((NamingEvent)event).getServiceName()); System.out.println("实例:"+((NamingEvent)event).getInstances()); } };
4. 独立文件
public void subscribe() { try { NamingService namingService = NamingFactory.createNamingService("127.0.0.1:8848"); namingService.subscribe("serverName","groupName", new NacosListener()); } catch (NacosException e) { logger.error(e.getMessage(), e); } } //单独Class类 public class NacosListener implements EventListener { @Override public void onEvent(Event event) { if (event instanceof NamingEvent) { System.out.println(((NamingEvent)event).getServiceName()); System.out.println(((NamingEvent)event).getInstances()); } } }