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<GenericService> reference = new ReferenceConfig<>();// 接口的路径reference.setInterface("com.ailiving.iot.servicehub.api.SteelPartnerInfoService");// 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);}
}