com.alipay.sofa.rpc.config.ConsumerConfig Java Examples
The following examples show how to use
com.alipay.sofa.rpc.config.ConsumerConfig.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BoltExceptionTest.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Test public void testAll() { final String directUrl = "bolt://127.0.0.1:12300"; final ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>() .setInterfaceId(HelloService.class.getName()) .setDirectUrl(directUrl) .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT) .setBootstrap("bolt") .setApplication(new ApplicationConfig().setAppName("clientApp")) .setReconnectPeriod(1000); HelloService helloService = consumerConfig.refer(); // 关闭后再调用一个抛异常 try { helloService.sayHello("xx", 22); } catch (Exception e) { // 应该抛出异常 Assert.assertTrue(e instanceof SofaRouteException); Assert.assertTrue(e.getMessage().contains(directUrl)); } }
Example #2
Source File: AllConnectConnectionHolderTest.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Test public void getAvailableClientTransport1() throws Exception { ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>() .setInterfaceId(HelloService.class.getName()) .setDirectUrl("bolt://127.0.0.1:22221") .setConnectionHolder("all") .setRegister(false) .setLazy(true) .setTimeout(3000); HelloService helloService = consumerConfig.refer(); ClientProxyInvoker invoker = (ClientProxyInvoker) ProxyFactory.getInvoker(helloService, consumerConfig.getProxy()); Cluster cluster = invoker.getCluster(); Assert.assertTrue(cluster.getConnectionHolder() instanceof AllConnectConnectionHolder); AllConnectConnectionHolder holder = (AllConnectConnectionHolder) cluster.getConnectionHolder(); Assert.assertTrue(holder.isAvailableEmpty()); Assert.assertNull(holder.getAvailableClientTransport( ProviderHelper.toProviderInfo("bolt://127.0.0.1:22221?serialization=hessian2"))); }
Example #3
Source File: SofaRegistry.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void unSubscribe(ConsumerConfig config) { String serviceName = SofaRegistryHelper.buildListDataId(config, config.getProtocol()); String appName = config.getAppName(); Subscriber subscriber = subscribers.get(serviceName); if (subscriber != null) { SofaRegistrySubscribeCallback callback = (SofaRegistrySubscribeCallback) subscriber.getDataObserver(); callback.remove(serviceName, config); if (callback.getListenerNum() == 0) { // 已经没人订阅这个data Key了 SofaRegistryClient.getRegistryClient(appName, registryConfig).unregister(serviceName, subscriber.getGroup(), RegistryType.SUBSCRIBER); subscribers.remove(serviceName); // 已经没人订阅这个config Key了 SofaRegistryClient.getRegistryClient(appName, registryConfig).unregister(serviceName, subscriber.getGroup(), RegistryType.CONFIGURATOR); configurators.remove(serviceName); } } }
Example #4
Source File: MeshRouter.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public boolean needToLoad(ConsumerBootstrap consumerBootstrap) { ConsumerConfig consumerConfig = consumerBootstrap.getConsumerConfig(); // 不是直连,且从注册中心订阅配置 final boolean isDirect = StringUtils.isNotBlank(consumerConfig.getDirectUrl()); final List<RegistryConfig> registrys = consumerConfig.getRegistry(); boolean isMesh = false; if (registrys != null) { for (RegistryConfig registry : registrys) { if (registry.getProtocol().equalsIgnoreCase(RpcConstants.REGISTRY_PROTOCOL_MESH)) { isMesh = true; break; } } } return !isDirect && isMesh; }
Example #5
Source File: ZookeeperProviderObserver.java From sofa-rpc with Apache License 2.0 | 6 votes |
private void notifyListeners(ConsumerConfig config, String providerPath, List<ChildData> currentData, boolean add) throws UnsupportedEncodingException { List<ProviderInfoListener> providerInfoListeners = providerListenerMap.get(config); if (CommonUtils.isNotEmpty(providerInfoListeners)) { List<ProviderInfo> providerInfos = ZookeeperRegistryHelper.convertUrlsToProviders(providerPath, currentData); List<ProviderInfo> providerInfosForProtocol = RegistryUtils.matchProviderInfos(config, providerInfos); for (ProviderInfoListener listener : providerInfoListeners) { if (add) { listener.addProvider(new ProviderGroup(providerInfosForProtocol)); } else { listener.updateProviders(new ProviderGroup(providerInfosForProtocol)); } } } }
Example #6
Source File: NacosRegistry.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void unSubscribe(ConsumerConfig config) { if (config.isSubscribe()) { String serviceName = NacosRegistryHelper.buildServiceName(config, config.getProtocol()); try { EventListener eventListener = consumerListeners.remove(config); if (null != eventListener) { namingService.unsubscribe(serviceName, defaultCluster, eventListener); } } catch (Exception e) { if (!RpcRunningState.isShuttingDown()) { if (e instanceof SofaRpcRuntimeException) { throw (SofaRpcRuntimeException) e; } else { throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_UNSUB_LISTENER, EXT_NAME), e); } } } providerObserver.removeProviderListener(config); } }
Example #7
Source File: NacosRegistryProviderObserver.java From sofa-rpc with Apache License 2.0 | 6 votes |
/** * Update providers. * * @param config the config * @param instances the instances */ void updateProviders(ConsumerConfig config, List<Instance> instances) { if (LOGGER.isInfoEnabled(config.getAppName())) { LOGGER.infoWithApp(config.getAppName(), "Receive update provider: serviceName={}, size={}, data={}", NacosRegistryHelper.buildServiceName(config, config.getProtocol()), instances.size(), instances); } List<ProviderInfoListener> providerInfoListeners = providerListenerMap.get(config); if (CommonUtils.isNotEmpty(providerInfoListeners)) { List<ProviderInfo> providerInfos = NacosRegistryHelper.convertInstancesToProviders(instances); List<ProviderInfo> matchProviders = RegistryUtils.matchProviderInfos(config, providerInfos); for (ProviderInfoListener providerInfoListener : providerInfoListeners) { providerInfoListener .updateAllProviders(Collections.singletonList(new ProviderGroup().addAll(matchProviders))); } } }
Example #8
Source File: BootstrapsTest.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Test public void from1() throws Exception { ConsumerConfig consumerConfig = new ConsumerConfig().setProtocol("test") .setBootstrap("test"); ConsumerBootstrap bootstrap = Bootstraps.from(consumerConfig); Assert.assertEquals(TestConsumerBootstrap.class, bootstrap.getClass()); Assert.assertEquals(consumerConfig, bootstrap.getConsumerConfig()); // if not set bootstrap consumerConfig = new ConsumerConfig().setProtocol("test"); bootstrap = Bootstraps.from(consumerConfig); Assert.assertEquals(TestConsumerBootstrap.class, bootstrap.getClass()); Assert.assertEquals(consumerConfig, bootstrap.getConsumerConfig()); // if not set bootstrap and not exist consumerConfig = new ConsumerConfig().setProtocol("xx"); bootstrap = Bootstraps.from(consumerConfig); Assert.assertEquals(TestConsumerBootstrap.class, bootstrap.getClass()); Assert.assertEquals(consumerConfig, bootstrap.getConsumerConfig()); }
Example #9
Source File: SofaBootRpcAllTest.java From sofa-rpc-boot-projects with Apache License 2.0 | 6 votes |
@Test public void testLoadBalancerAnnotation() throws NoSuchFieldException, IllegalAccessException { ConsumerConfigContainer ccc = SpringBridge.getConsumerConfigContainer(); Field consumerConfigMapField = ConsumerConfigContainer.class.getDeclaredField("consumerConfigMap"); consumerConfigMapField.setAccessible(true); ConcurrentMap<Binding, ConsumerConfig> consumerConfigMap = (ConcurrentMap<Binding, ConsumerConfig>) consumerConfigMapField .get(ccc); boolean found = false; for (ConsumerConfig consumerConfig : consumerConfigMap.values()) { if ("loadbalancer".equals(consumerConfig.getUniqueId()) && AnnotationService.class.getName().equals(consumerConfig.getInterfaceId())) { found = true; Assert.assertEquals("roundRobin", consumerConfig.getLoadBalancer()); } } Assert.assertTrue("Found roundrobin reference", found); }
Example #10
Source File: ServerB.java From sofa-rpc with Apache License 2.0 | 6 votes |
public static void main(String[] args) { // B服务里的C服务客户端 ConsumerConfig<ServiceC> consumerConfig = new ConsumerConfig<ServiceC>() .setApplication(new ApplicationConfig().setAppName("BBB")) .setInterfaceId(ServiceC.class.getName()) .setDirectUrl("bolt://127.0.0.1:12299?appName=CCC") .setRegister(false) .setInvokeType("callback") // 不设置,调用级别可设置 .setTimeout(2000); ServiceC serviceC = consumerConfig.refer(); ServerConfig serverConfig = new ServerConfig() .setPort(12298) .setDaemon(false); ProviderConfig<ServiceB> providerConfig = new ProviderConfig<ServiceB>() .setInterfaceId(ServiceB.class.getName()) .setApplication(new ApplicationConfig().setAppName("BBB")) .setRef(new ServiceBImpl(serviceC)) .setServer(serverConfig) .setRegister(false); providerConfig.export(); }
Example #11
Source File: ConsulRegistry.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Override public void unSubscribe(ConsumerConfig config) { String appName = config.getAppName(); if (!registryConfig.isSubscribe()) { // 注册中心不订阅 if (LOGGER.isInfoEnabled(appName)) { LOGGER.infoWithApp(config.getAppName(), LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE)); } } if (!config.isSubscribe()) { return; } String uniqueName = buildUniqueName(config, config.getProtocol()); HealthServiceInformer informer = healthServiceInformers.get(uniqueName); if (informer == null) { return; } informer.removeListener(config.getProviderInfoListener()); if (informer.getListenerSize() == 0) { healthServiceInformers.remove(uniqueName); informer.shutdown(); } }
Example #12
Source File: BoltMockTest.java From sofa-rpc with Apache License 2.0 | 6 votes |
@Test public void testLocal() { final ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>() .setInterfaceId(HelloService.class.getName()) .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT) .setBootstrap("bolt") .setApplication(new ApplicationConfig().setAppName("clientApp")) .setReconnectPeriod(1000) .setMockMode("local") .setMockRef(new HelloService() { @Override public String sayHello(String name, int age) { return "mock"; } }); HelloService helloService = consumerConfig.refer(); Assert.assertEquals("mock", helloService.sayHello("xx", 22)); }
Example #13
Source File: SofaProtoUtils.java From sofa-rpc with Apache License 2.0 | 6 votes |
public static boolean checkIfUseGeneric(ConsumerConfig consumerConfig) { Class proxyClass = consumerConfig.getProxyClass(); Class enclosingClass = proxyClass.getEnclosingClass(); if (enclosingClass != null) { try { enclosingClass.getDeclaredMethod("getSofaStub", Channel.class, CallOptions.class, ProviderInfo.class, ConsumerConfig.class, int.class); return false; } catch (NoSuchMethodException e) { //ignore return true; } } return true; }
Example #14
Source File: TripleClientInvoker.java From sofa-rpc with Apache License 2.0 | 6 votes |
public TripleClientInvoker(ConsumerConfig consumerConfig, Channel channel) { this.channel = channel; this.consumerConfig = consumerConfig; useGeneric = checkIfUseGeneric(consumerConfig); cacheCommonData(consumerConfig); if (!useGeneric) { Class enclosingClass = consumerConfig.getProxyClass().getEnclosingClass(); try { sofaStub = enclosingClass.getDeclaredMethod("getSofaStub", Channel.class, CallOptions.class, ProviderInfo.class, ConsumerConfig.class, int.class); } catch (NoSuchMethodException e) { LOGGER.error("getSofaStub not found in enclosingClass" + enclosingClass.getName()); } } }
Example #15
Source File: LocalRegistry.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public void unSubscribe(ConsumerConfig config) { String key = LocalRegistryHelper.buildListDataId(config, config.getProtocol()); // 取消注册订阅关系,监听文件修改变化 List<ConsumerConfig> listeners = notifyListeners.get(key); if (listeners != null) { listeners.remove(config); if (listeners.size() == 0) { notifyListeners.remove(key); } } }
Example #16
Source File: BoltClientProxyInvokerTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Test(expected = SofaRpcRuntimeException.class) public void testParseSerializeTypeException() { ConsumerConfig consumerConfig = new ConsumerConfig().setProtocol("bolt"); ConsumerBootstrap bootstrap = Bootstraps.from(consumerConfig); BoltClientProxyInvoker invoker = new BoltClientProxyInvoker(bootstrap); invoker.parseSerializeType("unknown"); }
Example #17
Source File: SofaRegistrySubscribeCallback.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 增加监听器,一个dataId增加多的ConsumerConfig的listener * * @param dataId 配置Id * @param consumerConfig 服务调用者信息 * @param listener 服务列表监听器 */ void addProviderInfoListener(String dataId, ConsumerConfig consumerConfig, ProviderInfoListener listener) { providerInfoListeners.put(consumerConfig, listener); // 同一个key重复订阅多次,提醒用户需要检查一下是否是代码问题 if (LOGGER.isWarnEnabled(consumerConfig.getAppName()) && providerInfoListeners.size() > 5) { LOGGER.warnWithApp(consumerConfig.getAppName(), "Duplicate to add provider listener of {} " + "more than 5 times, now is {}, please check it", dataId, providerInfoListeners.size()); } }
Example #18
Source File: TestAsyncFilter.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public void onAsyncResponse(ConsumerConfig config, SofaRequest request, SofaResponse response, Throwable throwable) throws SofaRpcException { if (request.isAsync() && response != null) { response.setAppResponse(response.getAppResponse() + "append by async filter"); } }
Example #19
Source File: ClientSyncReceiveEvent.java From sofa-rpc with Apache License 2.0 | 5 votes |
public ClientSyncReceiveEvent(ConsumerConfig consumerConfig, ProviderInfo providerInfo, SofaRequest request, SofaResponse response, Throwable throwable) { this.consumerConfig = consumerConfig; this.providerInfo = providerInfo; this.request = request; this.response = response; this.throwable = throwable; }
Example #20
Source File: AllConnectConnectionHolderTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Test public void getAvailableClientTransport4() throws Exception { ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>() .setInterfaceId(HelloService.class.getName()) .setDirectUrl("bolt://127.0.0.1:22223,bolt://127.0.0.1:22224") .setConnectionHolder("all") .setRegister(false) .setLazy(true) .setTimeout(3000); HelloService helloService = consumerConfig.refer(); ClientProxyInvoker invoker = (ClientProxyInvoker) ProxyFactory.getInvoker(helloService, consumerConfig.getProxy()); Cluster cluster = invoker.getCluster(); Assert.assertTrue(cluster.getConnectionHolder() instanceof AllConnectConnectionHolder); AllConnectConnectionHolder holder = (AllConnectConnectionHolder) cluster.getConnectionHolder(); ProviderGroup providerGroups = new ProviderGroup(); providerGroups.add(ProviderHelper.toProviderInfo("bolt://127.0.0.1:22223")); providerGroups.add(ProviderHelper.toProviderInfo("bolt://127.0.0.1:22224")); holder.updateProviders(providerGroups); Set<ProviderInfo> last = holder.currentProviderList(); Assert.assertEquals(2, last.size()); ProviderGroup providerGroups2 = new ProviderGroup(); holder.updateProviders(providerGroups2); Set<ProviderInfo> current = holder.currentProviderList(); Assert.assertEquals(0, current.size()); consumerConfig.unRefer(); }
Example #21
Source File: SofaRegistrySubscribeCallback.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * 单独通知某个Listener * * @param dataId 订阅关键字 * @param config 服务端订阅者配置 * @param listener 服务列表监听器 */ void handleDataToListener(String dataId, ConsumerConfig config, ProviderInfoListener listener) { if (!canNotify()) { return; } if (lastUserData != null) { ComposeUserData composeUserData = composeUserAndConfigData(lastUserData, lastConfigData); notifyToListener(listener, composeUserData); } }
Example #22
Source File: ConsulRegistry.java From sofa-rpc with Apache License 2.0 | 5 votes |
private List<ProviderInfo> lookupHealthService(ConsumerConfig config) { String uniqueName = buildUniqueName(config, config.getProtocol()); String serviceName = buildServiceName(config); String informerKey = String.join("-", serviceName, uniqueName); HealthServiceInformer informer = healthServiceInformers.get(informerKey); if (informer == null) { informer = new HealthServiceInformer(serviceName, uniqueName, consulClient, properties); informer.init(); healthServiceInformers.put(informerKey, informer); } informer.addListener(config.getProviderInfoListener()); return informer.currentProviders(); }
Example #23
Source File: ZookeeperRegistry.java From sofa-rpc with Apache License 2.0 | 5 votes |
protected void recoverRegistryData() { for (ProviderConfig providerConfig : providerUrls.keySet()) { registerProviderUrls(providerConfig); } for (ConsumerConfig consumerConfig : consumerUrls.keySet()) { subscribeConsumerUrls(consumerConfig); } }
Example #24
Source File: MeshRegistry.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public void batchUnSubscribe(List<ConsumerConfig> configs) { // 不支持批量反注册,那就一个个来吧 for (ConsumerConfig config : configs) { String appName = config.getAppName(); try { unSubscribe(config); } catch (Exception e) { LOGGER.errorWithApp(appName, "Error when batch unSubscribe", e); } } }
Example #25
Source File: MulticastRegistry.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public void batchUnSubscribe(List<ConsumerConfig> configs) { for (ConsumerConfig config : configs) { String appName = config.getAppName(); try { unSubscribe(config); } catch (Exception e) { LOGGER.errorWithApp(appName, "Error when batch unSubscribe", e); } } }
Example #26
Source File: ZookeeperRegistryHelper.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * Convert child data to attribute. * * @param overridePath the override path * @param childData the child data * @param removeType is remove type * @param interfaceConfig register provider/consumer config * @return the attribute * @throws Exception decode exception */ static Map<String, String> convertOverrideToAttribute(String overridePath, ChildData childData, boolean removeType, AbstractInterfaceConfig interfaceConfig) throws Exception { String url = URLDecoder.decode(childData.getPath().substring(overridePath.length() + 1), "UTF-8"); Map<String, String> attribute = new ConcurrentHashMap<String, String>(); for (String keyPairs : url.substring(url.indexOf('?') + 1).split("&")) { String[] overrideAttrs = keyPairs.split("="); // TODO 这个列表待确认,不少字段是不支持的 List<String> configKeys = Arrays.asList(RpcConstants.CONFIG_KEY_TIMEOUT, RpcConstants.CONFIG_KEY_SERIALIZATION, RpcConstants.CONFIG_KEY_LOADBALANCER); if (configKeys.contains(overrideAttrs[0])) { if (removeType) { Class clazz = null; if (interfaceConfig instanceof ProviderConfig) { // TODO 服务端也生效? clazz = ProviderConfig.class; } else if (interfaceConfig instanceof ConsumerConfig) { clazz = ConsumerConfig.class; } if (clazz != null) { Method getMethod = ReflectUtils.getPropertyGetterMethod(clazz, overrideAttrs[0]); Class propertyClazz = getMethod.getReturnType(); //If event type is CHILD_REMOVED, attribute should return to register value attribute.put(overrideAttrs[0], StringUtils.toString(BeanUtils .getProperty(interfaceConfig, overrideAttrs[0], propertyClazz))); } } else { attribute.put(overrideAttrs[0], overrideAttrs[1]); } } } return attribute; }
Example #27
Source File: ZookeeperProviderObserver.java From sofa-rpc with Apache License 2.0 | 5 votes |
/** * Remove Provider * * @param config ConsumerConfig * @param providerPath Provider path of zookeeper * @param data Event data * @param currentData provider data list * @throws UnsupportedEncodingException decode error */ public void removeProvider(ConsumerConfig config, String providerPath, ChildData data, List<ChildData> currentData) throws UnsupportedEncodingException { if (LOGGER.isInfoEnabled(config.getAppName())) { LOGGER.infoWithApp(config.getAppName(), "Receive remove provider: path=[" + data.getPath() + "]" + ", data=[" + StringSerializer.decode(data.getData()) + "]" + ", stat=[" + data.getStat() + "]" + ", list=[" + currentData.size() + "]"); } notifyListeners(config, providerPath, currentData, false); }
Example #28
Source File: MulticastRegistry.java From sofa-rpc with Apache License 2.0 | 5 votes |
@Override public void unSubscribe(ConsumerConfig config) { if (!config.isSubscribe()) { return; } String key = MulticastRegistryHelper.buildListDataId(config, config.getProtocol()); notifyListeners.remove(key); // it is not necessary to multicast UNSUBSCRIBE info }
Example #29
Source File: AbstractInvokeCallback.java From sofa-rpc with Apache License 2.0 | 5 votes |
protected AbstractInvokeCallback(ConsumerConfig consumerConfig, ProviderInfo providerInfo, SofaRequest request, RpcInternalContext context, ClassLoader classLoader) { this.consumerConfig = consumerConfig; this.providerInfo = providerInfo; this.request = request; this.context = context; this.classLoader = classLoader; }
Example #30
Source File: ConsulRegistryTest.java From sofa-rpc with Apache License 2.0 | 5 votes |
private ConsumerConfig<?> consumerConfig(String uniqueId) { ConsumerConfig<?> consumer = new ConsumerConfig(); consumer.setInterfaceId(INTERFACE_ID) .setUniqueId(uniqueId) .setApplication(new ApplicationConfig().setAppName("consul-registry-test")) .setProxy("javassist") .setSubscribe(true) .setSerialization("java") .setInvokeType("sync") .setTimeout(4444); return consumer; }