org.apache.dubbo.rpc.service.GenericService Java Examples

The following examples show how to use org.apache.dubbo.rpc.service.GenericService. 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: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private ReferenceBean<GenericService> build(String interfaceName, String version,
		String group, Map<String, Object> dubboTranslatedAttributes) {

	Integer key = Objects.hash(interfaceName, version, group,
			dubboTranslatedAttributes);

	return cache.computeIfAbsent(group + key, k -> {
		ReferenceBean<GenericService> referenceBean = new ReferenceBean<>();
		referenceBean.setGeneric(true);
		referenceBean.setInterface(interfaceName);
		referenceBean.setVersion(version);
		referenceBean.setGroup(group);
		referenceBean.setCheck(false);
		bindReferenceBean(referenceBean, dubboTranslatedAttributes);
		return referenceBean;
	});
}
 
Example #2
Source File: GenericServiceTest.java    From jmeter-plugins-for-apache-dubbo with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    ApplicationConfig application = new ApplicationConfig();
    application.setName("api-generic-consumer");
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setUrl("dubbo://192.168.56.1:20880/org.apache.dubbo.samples.basic.api.DemoService");
    reference.setVersion("1.0.0");
    reference.setTimeout(2000);
    reference.setGeneric(true);
    reference.setApplication(application);
    reference.setInterface("com.jiuyescm.account.api.IUserService");
    GenericService genericService = reference.get();
    Object obj = genericService.$invoke("getUserById", new String[]{Long.class.getName()}, new Long[]{1L});
    String json = JsonUtils.toJson(obj);
    System.out.println(json);
}
 
Example #3
Source File: GenericServiceTest.java    From jmeter-plugins-for-apache-dubbo with Apache License 2.0 6 votes vote down vote up
@Test
public void testAttachment() {
    ApplicationConfig application = new ApplicationConfig();
    application.setName("api-generic-consumer");
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setUrl("dubbo://192.168.56.1:20880/org.apache.dubbo.samples.basic.api.DemoService");
    reference.setVersion("1.0.0");
    reference.setTimeout(2000);
    reference.setGeneric(true);
    reference.setApplication(application);
    reference.setInterface("com.jiuyescm.account.api.IUserService");
    GenericService genericService = reference.get();
    RpcContext.getContext().setAttachment("test.ningyu","this is attachmentValue");
    Object obj = genericService.$invoke("sayHello", new String[]{String.class.getName()}, new String[]{"ningyu"});
    String json = JsonUtils.toJson(obj);
    System.out.println(json);
}
 
Example #4
Source File: GenericImplProvider.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    new EmbeddedZooKeeper(2181, false).start();

    ApplicationConfig applicationConfig = new ApplicationConfig();
    applicationConfig.setName("generic-impl-provider");
    RegistryConfig registryConfig = new RegistryConfig();
    registryConfig.setAddress(zookeeperAddress);

    GenericService helloService = new GenericImplOfHelloService();
    ServiceConfig<GenericService> service = new ServiceConfig<>();
    service.setApplication(applicationConfig);
    service.setRegistry(registryConfig);
    service.setInterface("org.apache.dubbo.samples.generic.call.api.HelloService");
    service.setRef(helloService);
    service.setGeneric("true");
    service.export();

    System.out.println("dubbo service started");
    new CountDownLatch(1).await();
}
 
Example #5
Source File: GenericCallConsumer.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName("generic-call-consumer");
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress("zookeeper://127.0.0.1:2181");
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface("org.apache.dubbo.samples.generic.call.api.HelloService");
        applicationConfig.setRegistry(registryConfig);
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setGeneric(true);
        referenceConfig.setAsync(true);
        referenceConfig.setTimeout(7000);

        genericService = referenceConfig.get();
        invokeSayHello();
        invokeSayHelloAsync();
        invokeAsyncSayHelloAsync();
        invokeAsyncSayHello();
//        invokeSayHelloAsyncComplex();
        asyncInvokeSayHelloAsyncComplex();
//        invokeSayHelloAsyncGenericComplex();
        asyncInvokeSayHelloAsyncGenericComplex();
    }
 
Example #6
Source File: DirectServiceIT.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeneric() throws Exception {
    ApplicationConfig application = new ApplicationConfig();
    application.setName("direct-consumer");
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setUrl("dubbo://" + providerAddress + ":20880/" + DirectService.class.getName());
    reference.setVersion("1.0.0-daily");
    reference.setGroup("test");
    reference.setGeneric(true);
    reference.setApplication(application);
    reference.setInterface(DirectService.class.getName());
    GenericService genericService = reference.get();
    Object obj = genericService.$invoke("sayHello", new String[]{String.class.getName()}, new Object[]{ "generic" });
    String str = (String) obj;
    TestCase.assertTrue(str.startsWith("Hello generic"));
}
 
Example #7
Source File: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void bindReferenceBean(ReferenceBean<GenericService> referenceBean,
		Map<String, Object> dubboTranslatedAttributes) {
	DataBinder dataBinder = new DataBinder(referenceBean);
	// Register CustomEditors for special fields
	dataBinder.registerCustomEditor(String.class, "filter",
			new StringTrimmerEditor(true));
	dataBinder.registerCustomEditor(String.class, "listener",
			new StringTrimmerEditor(true));
	dataBinder.registerCustomEditor(Map.class, "parameters",
			new PropertyEditorSupport() {

				@Override
				public void setAsText(String text)
						throws java.lang.IllegalArgumentException {
					// Trim all whitespace
					String content = StringUtils.trimAllWhitespace(text);
					if (!StringUtils.hasText(content)) { // No content , ignore
															// directly
						return;
					}
					// replace "=" to ","
					content = StringUtils.replace(content, "=", ",");
					// replace ":" to ","
					content = StringUtils.replace(content, ":", ",");
					// String[] to Map
					Map<String, String> parameters = CollectionUtils
							.toStringMap(commaDelimitedListToStringArray(content));
					setValue(parameters);
				}
			});

	// ignore "registries" field and then use RegistryConfig beans
	dataBinder.setDisallowedFields("registries");

	dataBinder.bind(new MutablePropertyValues(dubboTranslatedAttributes));

	registryConfigs.ifAvailable(referenceBean::setRegistries);
}
 
Example #8
Source File: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private ReferenceBean<GenericService> build(ServiceRestMetadata serviceRestMetadata,
		Map<String, Object> dubboTranslatedAttributes) {
	String urlValue = serviceRestMetadata.getUrl();
	URL url = URL.valueOf(urlValue);
	String interfaceName = url.getServiceInterface();
	String version = url.getParameter(VERSION_KEY);
	String group = url.getParameter(GROUP_KEY);

	return build(interfaceName, version, group, dubboTranslatedAttributes);
}
 
Example #9
Source File: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public GenericService create(String serviceName, Class<?> serviceClass,
		String version) {
	String interfaceName = serviceClass.getName();
	ReferenceBean<GenericService> referenceBean = build(interfaceName, version,
			serviceName, emptyMap());
	return referenceBean.get();
}
 
Example #10
Source File: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public GenericService create(DubboRestServiceMetadata dubboServiceMetadata,
		Map<String, Object> dubboTranslatedAttributes) {

	ReferenceBean<GenericService> referenceBean = build(
			dubboServiceMetadata.getServiceRestMetadata(), dubboTranslatedAttributes);

	return referenceBean == null ? null : referenceBean.get();
}
 
Example #11
Source File: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public synchronized void destroy(String serviceName) {
	Set<String> removeGroups = new HashSet<>(cache.keySet());
	for (String key : removeGroups) {
		if (key.contains(serviceName)) {
			ReferenceBean<GenericService> referenceBean = cache.remove(key);
			referenceBean.destroy();
		}
	}
}
 
Example #12
Source File: FeignMethodMetadata.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
FeignMethodMetadata(GenericService dubboGenericService,
		RestMethodMetadata dubboRestMethodMetadata,
		RestMethodMetadata feignMethodMetadata) {
	this.dubboGenericService = dubboGenericService;
	this.dubboRestMethodMetadata = dubboRestMethodMetadata;
	this.feignMethodMetadata = feignMethodMetadata;
}
 
Example #13
Source File: TargeterInvocationHandler.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private Map<Method, FeignMethodMetadata> getFeignMethodMetadataMap(String serviceName,
		Map<DubboTransportedMethodMetadata, RestMethodMetadata> feignRestMethodMetadataMap) {
	Map<Method, FeignMethodMetadata> feignMethodMetadataMap = new HashMap<>();

	for (Map.Entry<DubboTransportedMethodMetadata, RestMethodMetadata> entry : feignRestMethodMetadataMap
			.entrySet()) {
		RestMethodMetadata feignRestMethodMetadata = entry.getValue();
		RequestMetadata feignRequestMetadata = feignRestMethodMetadata.getRequest();
		DubboRestServiceMetadata metadata = repository.get(serviceName,
				feignRequestMetadata);
		if (metadata != null) {
			DubboTransportedMethodMetadata dubboTransportedMethodMetadata = entry
					.getKey();
			Map<String, Object> dubboTranslatedAttributes = dubboTransportedMethodMetadata
					.getAttributes();
			Method method = dubboTransportedMethodMetadata.getMethod();
			GenericService dubboGenericService = dubboGenericServiceFactory
					.create(metadata, dubboTranslatedAttributes);
			RestMethodMetadata dubboRestMethodMetadata = metadata
					.getRestMethodMetadata();
			MethodMetadata methodMetadata = dubboTransportedMethodMetadata
					.getMethodMetadata();
			FeignMethodMetadata feignMethodMetadata = new FeignMethodMetadata(
					dubboGenericService, dubboRestMethodMetadata,
					feignRestMethodMetadata);
			feignMethodMetadataMap.put(method, feignMethodMetadata);
		}
	}

	return feignMethodMetadataMap;
}
 
Example #14
Source File: DubboInvocationHandler.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method feignMethod, Object[] args)
		throws Throwable {

	FeignMethodMetadata feignMethodMetadata = feignMethodMetadataMap.get(feignMethod);

	if (feignMethodMetadata == null) {
		return defaultInvocationHandler.invoke(proxy, feignMethod, args);
	}

	GenericService dubboGenericService = feignMethodMetadata.getDubboGenericService();
	RestMethodMetadata dubboRestMethodMetadata = feignMethodMetadata
			.getDubboRestMethodMetadata();
	RestMethodMetadata feignRestMethodMetadata = feignMethodMetadata
			.getFeignMethodMetadata();

	DubboGenericServiceExecutionContext context = contextFactory
			.create(dubboRestMethodMetadata, feignRestMethodMetadata, args);

	String methodName = context.getMethodName();
	String[] parameterTypes = context.getParameterTypes();
	Object[] parameters = context.getParameters();

	Object result = dubboGenericService.$invoke(methodName, parameterTypes,
			parameters);

	Class<?> returnType = getReturnType(dubboRestMethodMetadata);

	return realize(result, returnType);
}
 
Example #15
Source File: DubboGenericServiceFactory.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void destroyReferenceBeans() {
	Collection<ReferenceBean<GenericService>> referenceBeans = cache.values();
	if (logger.isInfoEnabled()) {
		logger.info("The Dubbo GenericService ReferenceBeans are destroying...");
	}
	for (ReferenceBean referenceBean : referenceBeans) {
		referenceBean.destroy(); // destroy ReferenceBean
		if (logger.isInfoEnabled()) {
			logger.info("Destroyed the ReferenceBean  : {} ", referenceBean);
		}
	}
}
 
Example #16
Source File: HelloServiceIT.java    From dubbo-samples with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    ApplicationConfig applicationConfig = new ApplicationConfig();
    applicationConfig.setName("generic-call-consumer");
    RegistryConfig registryConfig = new RegistryConfig();
    registryConfig.setAddress("zookeeper://" + zookeeperHost + ":2181");
    ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
    referenceConfig.setInterface("org.apache.dubbo.samples.generic.call.api.HelloService");
    applicationConfig.setRegistry(registryConfig);
    referenceConfig.setApplication(applicationConfig);
    referenceConfig.setGeneric(true);
    referenceConfig.setAsync(true);
    referenceConfig.setTimeout(7000);
    genericService = referenceConfig.get();
}
 
Example #17
Source File: GenericServiceTest.java    From jmeter-plugins-for-apache-dubbo with Apache License 2.0 5 votes vote down vote up
@Test
public void testZk() {
    for(int i=0;i<5;i++) {
        ApplicationConfig application = new ApplicationConfig();
        application.setName("api-generic-consumer");
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setVersion("1.0.0");
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol(Constants.REGISTRY_ZOOKEEPER);
        registry.setAddress("192.168.0.44:2181,192.168.0.44:2182,192.168.0.44:2183");
        registry.setTimeout(10000);
        reference.setRegistry(registry);
        ConfigCenterConfig cc = new ConfigCenterConfig();
        cc.setAddress("192.168.0.58:2181,192.168.0.59:2181,192.168.0.60:2181");
        cc.setProtocol(Constants.REGISTRY_ZOOKEEPER);
        cc.setTimeout(Long.valueOf("10000"));
        cc.setGroup("");
        cc.setNamespace("");
        reference.setConfigCenter(cc);
        reference.setTimeout(2000);
        reference.setGeneric(true);
        reference.setApplication(application);
        reference.setInterface("com.jiuyescm.account.api.IUserService");
        GenericService genericService = reference.get();
        Object obj = genericService.$invoke("getUserById", new String[]{Long.class.getName()}, new Long[]{1L});
        String json = JsonUtils.toJson(obj);
        System.out.println(json);
    }
}
 
Example #18
Source File: ApplicationConfigCache.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Build reference config.
 *
 * @param metaData the meta data
 * @return the reference config
 */
public ReferenceConfig<GenericService> build(final MetaData metaData) {
    ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
    reference.setGeneric(true);
    reference.setApplication(applicationConfig);
    reference.setRegistry(registryConfig);
    reference.setInterface(metaData.getServiceName());
    reference.setProtocol("dubbo");
    String rpcExt = metaData.getRpcExt();
    DubboParamExtInfo dubboParamExtInfo = GsonUtils.getInstance().fromJson(rpcExt, DubboParamExtInfo.class);
    if (Objects.nonNull(dubboParamExtInfo)) {
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getVersion())) {
            reference.setVersion(dubboParamExtInfo.getVersion());
        }
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getGroup())) {
            reference.setGroup(dubboParamExtInfo.getGroup());
        }
        if (StringUtils.isNoneBlank(dubboParamExtInfo.getLoadbalance())) {
            final String loadBalance = dubboParamExtInfo.getLoadbalance();
            reference.setLoadbalance(buildLoadBalanceName(loadBalance));
        }
        Optional.ofNullable(dubboParamExtInfo.getTimeout()).ifPresent(reference::setTimeout);
        Optional.ofNullable(dubboParamExtInfo.getRetries()).ifPresent(reference::setRetries);
    }
    Object obj = reference.get();
    if (obj != null) {
        log.info("init apache dubbo reference success there meteData is :{}", metaData.toString());
        cache.put(metaData.getServiceName(), reference);
    }
    return reference;
}
 
Example #19
Source File: ApplicationConfigCache.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Init ref reference config.
 *
 * @param metaData the meta data
 * @return the reference config
 */
public ReferenceConfig<GenericService> initRef(final MetaData metaData) {
    try {
        ReferenceConfig<GenericService> referenceConfig = cache.get(metaData.getServiceName());
        if (StringUtils.isNoneBlank(referenceConfig.getInterface())) {
            return referenceConfig;
        }
    } catch (ExecutionException e) {
        log.error("init dubbo ref ex:{}", e.getMessage());
    }
    return build(metaData);
    
}
 
Example #20
Source File: ApacheDubboProxyService.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Generic invoker object.
 *
 * @param body     the body
 * @param metaData the meta data
 * @param exchange the exchange
 * @return the object
 * @throws SoulException the soul exception
 */
public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws SoulException {
    ReferenceConfig<GenericService> reference = ApplicationConfigCache.getInstance().get(metaData.getServiceName());
    if (Objects.isNull(reference) || StringUtils.isEmpty(reference.getInterface())) {
        ApplicationConfigCache.getInstance().invalidate(metaData.getServiceName());
        reference = ApplicationConfigCache.getInstance().initRef(metaData);
    }
    GenericService genericService = reference.get();
    Pair<String[], Object[]> pair;
    try {
        if (null == body || "".equals(body) || "{}".equals(body) || "null".equals(body)) {
            pair = new ImmutablePair<>(new String[]{}, new Object[]{});
        } else {
            pair = dubboParamResolveService.buildParameter(body, metaData.getParameterTypes());
        }
        CompletableFuture<Object> future = genericService.$invokeAsync(metaData.getMethodName(), pair.getLeft(), pair.getRight());
        return Mono.fromFuture(future.thenApply(ret -> {
            if (Objects.nonNull(ret)) {
                exchange.getAttributes().put(Constants.DUBBO_RPC_RESULT, ret);
            } else {
                exchange.getAttributes().put(Constants.DUBBO_RPC_RESULT, Constants.DUBBO_RPC_RESULT_EMPTY);
            }
            exchange.getAttributes().put(Constants.CLIENT_RESPONSE_RESULT_TYPE, ResultEnum.SUCCESS.getName());
            return ret;
        }));
    } catch (GenericException e) {
        log.error("dubbo invoker have exception", e);
        throw new SoulException(e.getMessage());
    }
}
 
Example #21
Source File: DubboProxyService.java    From bird-java with MIT License 5 votes vote down vote up
/**
 * dubbo rpc invoke.
 *
 * @param paramMap    request paramMap.
 * @param dubboHandle dubboHandle.
 * @return rpc result.
 * @throws GatewayException exception for rpc.
 */
public Object genericInvoker(ServerWebExchange exchange, final DubboHandle dubboHandle) throws GatewayException {
    ReferenceConfig<GenericService> reference = buildReferenceConfig(dubboHandle);

    ReferenceConfigCache referenceConfigCache = ReferenceConfigCache.getCache();

    GenericService genericService = null;
    try {
        genericService = referenceConfigCache.get(reference);
    } catch (Exception ex) {
        REFERENCE_CONFIG_MAP.remove(dubboHandle);
        reference.destroy();
        referenceConfigCache.destroy(reference);

        log.error(dubboHandle.getInterfaceName() + "服务连接失败");
        throw new GatewayException(ex);
    }

    final Map<String, Object> paramMap = resolveParam(exchange);
    final Pair<String[], Object[]> pair = buildParameter(paramMap, dubboHandle);

    try {
        return genericService.$invoke(dubboHandle.getMethodName(), pair.getLeft(), pair.getRight());
    } catch (GenericException e) {
        log.error(e.getExceptionMessage());
        if (StringUtils.equals(e.getExceptionClass(), UserFriendlyException.class.getName())) {
            throw new UserFriendlyException(e.getExceptionMessage());
        } else {
            throw new GatewayException(e.getMessage());
        }
    }
}
 
Example #22
Source File: DubboProxyService.java    From bird-java with MIT License 5 votes vote down vote up
private ReferenceConfig<GenericService> buildReferenceConfig(final DubboHandle dubboHandle) {
    ReferenceConfig<GenericService> reference = REFERENCE_CONFIG_MAP.get(dubboHandle);
    if (Objects.isNull(reference)) {
        reference = new ReferenceConfig<>();
        reference.setInterface(dubboHandle.getInterfaceName());
        reference.setGeneric(true);

        reference.setRegistry(cacheRegistry(dubboHandle));
        reference.setConsumer(getConsumer(dubboHandle));

        if (StringUtils.isNoneBlank(dubboHandle.getVersion())) {
            reference.setVersion(dubboHandle.getVersion());
        }
        if (StringUtils.isNoneBlank(dubboHandle.getProtocol())) {
            reference.setProtocol(dubboHandle.getProtocol());
        }
        if (StringUtils.isNoneBlank(dubboHandle.getGroup())) {
            reference.setGroup(dubboHandle.getGroup());
        }
        if (StringUtils.isNoneBlank(dubboHandle.getLoadBalance())) {
            reference.setLoadbalance(dubboHandle.getLoadBalance());
        }

        Optional.ofNullable(dubboHandle.getTimeout()).ifPresent(reference::setTimeout);
        Optional.ofNullable(dubboHandle.getRetries()).ifPresent(reference::setRetries);

        REFERENCE_CONFIG_MAP.put(dubboHandle, reference);
    }

    return reference;
}
 
Example #23
Source File: DubboTransporterInterceptor.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
		ClientHttpRequestExecution execution) throws IOException {

	URI originalUri = request.getURI();

	String serviceName = originalUri.getHost();

	RequestMetadata clientMetadata = buildRequestMetadata(request);

	DubboRestServiceMetadata metadata = repository.get(serviceName, clientMetadata);

	if (metadata == null) {
		// if DubboServiceMetadata is not found, executes next
		return execution.execute(request, body);
	}

	RestMethodMetadata dubboRestMethodMetadata = metadata.getRestMethodMetadata();

	GenericService genericService = serviceFactory.create(metadata,
			dubboTranslatedAttributes);

	MutableHttpServerRequest httpServerRequest = new MutableHttpServerRequest(request,
			body);

	customizeRequest(httpServerRequest, dubboRestMethodMetadata, clientMetadata);

	DubboGenericServiceExecutionContext context = contextFactory
			.create(dubboRestMethodMetadata, httpServerRequest);

	Object result = null;
	GenericException exception = null;

	try {
		result = genericService.$invoke(context.getMethodName(),
				context.getParameterTypes(), context.getParameters());
	}
	catch (GenericException e) {
		exception = e;
	}

	return clientHttpResponseFactory.build(result, exception, clientMetadata,
			dubboRestMethodMetadata);
}
 
Example #24
Source File: DubboGatewayServlet.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {

	String serviceName = resolveServiceName(request);

	String restPath = substringAfter(request.getRequestURI(), serviceName);

	// 初始化 serviceName 的 REST 请求元数据
	repository.initializeMetadata(serviceName);
	// 将 HttpServletRequest 转化为 RequestMetadata
	RequestMetadata clientMetadata = buildRequestMetadata(request, restPath);

	DubboRestServiceMetadata dubboRestServiceMetadata = repository.get(serviceName,
			clientMetadata);

	if (dubboRestServiceMetadata == null) {
		// if DubboServiceMetadata is not found, executes next
		throw new ServletException("DubboServiceMetadata can't be found!");
	}

	RestMethodMetadata dubboRestMethodMetadata = dubboRestServiceMetadata
			.getRestMethodMetadata();

	GenericService genericService = serviceFactory.create(dubboRestServiceMetadata,
			dubboTranslatedAttributes);

	// TODO: Get the Request Body from HttpServletRequest
	byte[] body = getRequestBody(request);

	MutableHttpServerRequest httpServerRequest = new MutableHttpServerRequest(
			new HttpRequestAdapter(request), body);

	DubboGenericServiceExecutionContext context = contextFactory
			.create(dubboRestMethodMetadata, httpServerRequest);

	Object result = null;
	GenericException exception = null;

	try {
		result = genericService.$invoke(context.getMethodName(),
				context.getParameterTypes(), context.getParameters());
	}
	catch (GenericException e) {
		exception = e;
	}
	response.getWriter().println(result);
}
 
Example #25
Source File: FeignMethodMetadata.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
GenericService getDubboGenericService() {
	return dubboGenericService;
}
 
Example #26
Source File: DubboRepeater.java    From jvm-sandbox-repeater with Apache License 2.0 4 votes vote down vote up
@Override
protected Object executeRepeat(RepeatContext context) throws Exception {
    Invocation invocation = context.getRecordModel().getEntranceInvocation();
    if (!(invocation instanceof DubboInvocation)) {
        throw new RepeatException("type miss match, required DubboInvocation but found " + invocation.getClass().getSimpleName());
    }
    DubboInvocation dubboInvocation = (DubboInvocation) invocation;
    ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
    ApplicationConfig applicationConfig = new ApplicationConfig();
    applicationConfig.setName("jvm-sandbox-repeater");
    // require address to initialize registry config
    RegistryConfig registryConfig = new RegistryConfig();
    String address = context.getMeta().getExtension().get("dubbo.address");
    // using special address
    if (StringUtils.isNotEmpty(address)) {
        registryConfig.setAddress(address);
    } else {
        registryConfig.setAddress(dubboInvocation.getAddress());
    }
    String group = context.getMeta().getExtension().get("dubbo.group");
    // using special group
    if (StringUtils.isNotEmpty(group)) {
        registryConfig.setGroup(group);
    } else {
        registryConfig.setGroup(dubboInvocation.getGroup());
    }
    reference.setApplication(ConfigManager.getInstance().getApplication().orElse(applicationConfig));
    reference.setRegistry(registryConfig);

    // set protocol / interface / version / timeout
    reference.setProtocol(dubboInvocation.getProtocol());
    reference.setInterface(dubboInvocation.getInterfaceName());
    if (StringUtils.isNotEmpty(dubboInvocation.getVersion())) {
        reference.setVersion(dubboInvocation.getVersion());
    }
    // timeout
    reference.setTimeout(context.getMeta().getTimeout());
    // use generic invoke
    reference.setGeneric(true);
    // fix issue #45
    ClassLoader swap = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(GenericService.class.getClassLoader());
        GenericService genericService = reference.get();
        return genericService.$invoke(dubboInvocation.getMethodName(), dubboInvocation.getParameterTypes(), invocation.getRequest());
    } finally {
        Thread.currentThread().setContextClassLoader(swap);
    }
}
 
Example #27
Source File: ApplicationConfigCache.java    From soul with Apache License 2.0 4 votes vote down vote up
@Override
public ReferenceConfig<GenericService> load(final String key) {
    return new ReferenceConfig<>();
}
 
Example #28
Source File: DubboGeneric.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    System.setProperty("spring.profiles.active", "generic");

    ConfigurableApplicationContext run = SpringApplication.run(DubboGeneric.class, args);
    DubboGeneric application = run.getBean(DubboGeneric.class);
    GenericService consumer = application.getGenericService();

    Map<String, Object> param = new HashMap<>();
    //header
    Map<String, Object> header = new HashMap<>();
    Map<String, Object> headerAttrs = new HashMap<>();
    headerAttrs.put("type", "generic");
    headerAttrs.put("bodyType", "EchoData");
    header.put("attrs", headerAttrs);
    //body
    Map<String, Object> body = new HashMap<>();
    body.put("code", 1);
    body.put("message", "this is body");
    //param
    param.put("header", header);
    param.put("body", body);


    Object res1 = consumer.$invoke("echoRequest", null, new Object[]{param});

    System.out.println("res:"+res1);

    /*AtomicLong counter = new AtomicLong(0);
    while (true) {
        try {
            Object res = consumer.$invoke(
                    "sayHello",
                    new String[]{String.class.getName()},
                    new Object[]{"dubbo-" + counter.incrementAndGet()});
            System.out.println(res);
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            break;
        } catch (Throwable e) {
            e.printStackTrace();
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException ex) {
            }
        }
    }*/
}
 
Example #29
Source File: DubboGeneric.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
public GenericService getGenericService() {
    return genericService;
}