java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > dubbo服务调用者调用

dubbo服务调用者的三种调用过程

作者:辰辰浩

文章主要介绍了在Dubbo框架中进行服务调用的几种常见方法,包括使用注解、在XML中注册服务实例以及泛化调用

1、使用注解

@Referenc 或 @DubboReference(2.2.7版本以后)

	@Reference
    DubboTestService dubboTestService;
	
/*  @DubboReference
    DubboTestService dubboTestService;*/
	
    @GetMapping(value = "/dubbo/getInfo")
    public Map<String, Object> cachePermissions(String id) {
       return dubboTestService.getInfo(id);
    }
	

2、将服务实例在 applicationContext.xml 文件中注册 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://dubbo.apache.org/schema/dubbo" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://dubbo.apache.org/schema/dubbo
       http://dubbo.apache.org/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.lyj.service"></context:component-scan>

    <!-- 消费方应用名,用于计算依赖关系,不是匹配条件,可自定义 -->
    <dubbo:application name="spring-consumer"  />

    <!-- 使用multicast广播注册中心暴露发现服务地址 -->
    <dubbo:registry address="zookeeper://127.0.0.1:2181" />

    <!-- 监控中心监控设置,直连监控中心服务器地址或者从注册中心发现 -->
    <dubbo:monitor protocol="registry"></dubbo:monitor>
    <!-- <dubbo:monitor address="127.0.0.1:7070"></dubbo:monitor> -->

    <!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
    <dubbo:reference id="dubboTestService" interface="com.dubbo.service.dubboTestService" loadbalance="consistenthash" timeout="30000" />

</beans>

服务调用时可通过继承ApplicationContextAware,获取spring容器内的实例

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @description: ApplicationContextProvider 通过context获取目标原型
 **/
@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {

        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {

        return getApplicationContext().getBean(clazz);
    }

}

调用服务时只需要

Object bean = ApplicationContextProvider.get(dubboTestService)//值取自<dubbo:reference里注册的 id
String method = "getInfo";//需要调用的方法名
Class<?> parameterTypes = Class.forName("java.lang.String");//method的参数类型的列表(参数顺序需按声明method时的参数列表排列),可含有多个,取决于该方法
Method met= bean.getClass().getMethod(method, parameterTypes);
Object resp= met.invoke(bean, id); //resp返回值 id为method方法的参数

3、泛化 

创建服务调用类   借鉴 dubbo-samples

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DubboServiceGeneric {

    public static final Logger logger = LoggerFactory.getLogger(DubboServiceGeneric.class);

    @Value("${dubbo.cloud.subscribed-services}")
    public String applicationName;

    @Value("${dubbo.registry.address}")
    public String dubboRegistryAddress;


    public Object invoke(String interfaceName, String version, String metName, String[] paramsClass, Object[] paramsValues) {
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(applicationName);
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(dubboRegistryAddress);
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(interfaceName);
        referenceConfig.setVersion(version);
        applicationConfig.setRegistry(registryConfig);
        referenceConfig.setApplication(applicationConfig);
        referenceConfig.setGeneric("true");
        referenceConfig.setAsync(true);
        referenceConfig.setTimeout(7000);

        GenericService genericService = referenceConfig.get();
        Object o = genericService.$invoke(metName, paramsClass, paramsValues);
        return o;
    }
}

调用时只需要

@Autowired
DubboServiceGeneric dubboServiceGeneric;

String s = "";//s为method方法的参数
String getInfo = dubboServiceGeneric.invoke("com.dubbo.service.DubboTestService", "1.0.0", "getInfo", s);//1.0.0为版本号 

对应的服务提供者为

import com.dubbo.service.DubboTestService;
import org.apache.dubbo.config.annotation.Service;

@Service(version = "1.0.0")
public class DubboTestServiceImpl implements DubboTestService {


    @Autowired
    GatewayComponentMapper gatewayComponentMapper;

    @Override
    public Map<String, String> getInfo(Object json) {
        List<GatewayComponentDTO> dtos = gatewayComponentMapper.selectList(new QueryWrapper<>());
        HashMap<String, String> map = new HashMap<>();
        map.put("info", JSON.toJSONString(dtos));
        return map;
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文