Dubbo的泛化调用demo

application.propertise

dubbo.address=zookeeper://127.0.0.1:2181
# application.name 自定义 应用名称
application.name=api-test
apigateway.dubbo.protocol.name=dubbo
apigateway.dubbo.protocol.port=20880

初始化 ApiGateway的Controller,只需要开启一个Controller入口即可,其他服务全部使用ApiGateway进行泛化调用。

@RestController
@RequestMapping("/iot")
public class ApiController {

    @Value("${dubbo.address}")
    private String address;
    
    @Value("${application.name}")
    private String appName;

    @RequestMapping(value = {"/api"})
    public Object api() {
        //注册中心
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress(address);
        //泛化调用
        ApplicationConfig application = new ApplicationConfig();
        application.setName(appName);
        application.setRegistry(registry);

        //弱类型接口名
        ReferenceConfig reference = new ReferenceConfig<>();

        // 接口的路径
        reference.setInterface("com.cui.service.api.UserInfoService");
        // dubbo注册的版本号
        reference.setVersion("1.2.0");
        // 设置接口超时时间
        reference.setTimeout(2000000);
        // 声明为泛化接口
        reference.setGeneric(true);
        reference.setApplication(application);

        // 添加缓存策略
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        GenericService genericService = cache.get(reference);

        // 设置接口所需参数的类型
        String[] parameterTypes = new String[]{"java.lang.String","java.lang.String","java.lang.Integer","java.lang.Integer"};
        // 传递 必传的参数
        String[] args = new String[]{null,"NO001",null,null};
        //调用泛化接口
        Object object = genericService.$invoke("listPartnerInfo", parameterTypes, args);
        System.out.println(JSON.toJSONString(object));
        return JSON.toJSONString(object);
    }
}

 

你可能感兴趣的:(Dubbo)