分布式服务调用ServiceCaller(2)
2016-08-22 本文已影响193人
OneFish
实现详解
-
服务注册
-
实现了ApplicationContextAware接口和InitializingBean接口,获取到spring容器和在启动时注册服务到zk上
-
通过Spring容器的applicationContext.getBeansWithAnnotation()方法,获取到所有的Controller类
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { zeusServices.putAll(applicationContext.getBeansWithAnnotation(Controller.class)); zeusServices.putAll(applicationContext.getBeansWithAnnotation(RestController.class)); logger.info("zeus service initialing , find all zeus service {}", zeusServices); }
-
通过反射获取类和方法的@RequestMapping,通过InetAddress获取服务的ip地址,以及配置的端口号(端口号为各应用配置,不要漏掉),至此已获取该服务的所需信息
@Override public void afterPropertiesSet() throws Exception { String localIp = InetAddress.getLocalHost().getHostAddress(); String localHostName = InetAddress.getLocalHost().getHostName(); String localPort = port; for (Object service : zeusServices.values()) { RequestMapping requestMapping =AnnotationUtils.findAnnotation(service.getClass(), RequestMapping.class); String classPath = getPath(requestMapping); Method[] methods = ReflectionUtils.getAllDeclaredMethods(service.getClass()); for (Method method: methods) { RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class); if (null != methodRequestMapping) { ZeuService zeuService = AnnotationUtils.findAnnotation(method,ZeuService.class); String serviceName = getServiceName(zeuService,method.getName()); String serviceGroup = getServiceGroup(zeuService,group); String methodPath = getPath(methodRequestMapping); register.registerService(localHostName,localIp,localPort,classPath,methodPath,serviceName,serviceGroup); } } } }
-
zookeeper的操作使用了curator包简化了对zk的操作,构建ServiceDiscovery对象来实现对zookeeper的操作
private final ServiceDiscovery<ServiceInstanceDetail> serviceDiscovery; public ZeusRegister(CuratorFramework client, String basePath) throws Exception { CuratorServiceInstanceSerializer serializer = new CuratorServiceInstanceSerializer(ServiceInstanceDetail.class); this.serviceDiscovery = ServiceDiscoveryBuilder.builder(ServiceInstanceDetail.class).client(client).serializer(serializer).basePath(basePath).build(); this.serviceDiscovery.start(); logger.info("zookeeper ServiceRegister start success"); }
<bean id="curatorFramework" class="com.tts.component.webservice.CuratorFrameworkFactoryBean" destroy-method="destroy"> <property name="connectString" value="${zkServer:instance:port}"/> </bean> <bean id="serviceRegister" class="com.tts.component.webservice.ZeusRegister"> <constructor-arg name="basePath" value="/tts/services"/> <constructor-arg name="client" ref="curatorFramework"/> </bean>
- 构建服务的对象ServiceInstance,并使用serviceDiscovery.registerService(serviceInstance)将服务注册到zk上
ServiceInstance serviceInstance = ServiceInstance.builder().name(detail.getServiceName()).address(ip).port(Integer.valueOf(port)).payload(detail).build(); serviceDiscovery.registerService(serviceInstance);
-
自此,服务的注册完成了,引入tts-core.jar,并启动应用可以看到zk上:
image
-