Here are the examples of the java api org.apache.dubbo.config.ProtocolConfig taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
54 Examples
19
Source : RpcServer.java
with Apache License 2.0
from yametech
with Apache License 2.0
from yametech
/**
* 判断是否所有的服务都停止了,该方法暂时不要用
* @return
*/
public boolean stop() {
for (ProtocolConfig config : protocols) {
try {
// config.destory();
config.destroy();
} catch (Exception e) {
// log.warn("停止服务异常", e);
}
}
return true;
}
19
Source : DubboConfigurationProperties.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void setProtocol(ProtocolConfig protocol) {
this.protocol = protocol;
}
18
Source : DubboHealthIndicator.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private Set<String> getStatusCheckerNames(ProtocolConfig protocolConfig) {
String status = protocolConfig.getStatus();
return StringUtils.commaDelimitedListToSet(status);
}
17
Source : ProviderConfig.java
with Apache License 2.0
from sentinel-group
with Apache License 2.0
from sentinel-group
@Bean
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(25758);
return protocolConfig;
}
17
Source : SafDubboUtil.java
with Apache License 2.0
from saf-group
with Apache License 2.0
from saf-group
public static void initProtocolConfig(ProtocolConfig config) {
config.setName("dubbo");
config.setPort(10001);
}
17
Source : ProviderConfiguration.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
/**
* Current protocol configuration, to replace XML config:
* <prev>
* <dubbo:protocol name="dubbo" port="12345"/>
* </prev>
*
* @return {@link ProtocolConfig} Bean
*/
@Bean("dubbo")
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(12345);
return protocolConfig;
}
17
Source : ProviderConfiguration.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Bean
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(dubboPort);
return protocolConfig;
}
16
Source : DubboConfiguration.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
@Bean
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setPort(port);
protocolConfig.setTransporter("netty4");
protocolConfig.setThreadpool("fixed");
protocolConfig.setThreads(800);
return protocolConfig;
}
15
Source : AnnotationBean.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
/**
* @author [email protected]
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@IocBean(depose = "depose")
@Slf4j
public clreplaced AnnotationBean {
@Inject
protected Ioc ioc;
@Inject
protected Map<String, IocObject> iobjs;
@Inject
private String[] annotationPackages;
private ApplicationConfig applicationConfig = null;
private RegistryConfig registryConfig = null;
private ProtocolConfig protocolConfig = null;
private List<ServiceBean> providerList = new ArrayList<>();
private List<ReferenceConfig> consumerList = new ArrayList<>();
private Function<String, ClreplacedLoader> func;
public AnnotationBean() {
}
public void depose() {
try {
long begin = System.currentTimeMillis();
log.info("AnnotationBean depose begin");
if (null != func) {
log.info("remove clreplacedLoader func");
ClreplacedHelper.clreplacedLoaderFunSet.remove(func);
}
providerList.stream().forEach(it -> {
try {
log.info("depose:{}", it);
it.unexport();
} catch (Throwable ex) {
log.error(ex.getMessage(), ex);
}
});
consumerList.stream().forEach(it -> {
try {
it.destroy();
} catch (Throwable ex) {
log.error(ex.getMessage(), ex);
}
});
RpcContext.getContext().clearAttachments();
RpcContext.getServerContext().clearAttachments();
log.info("AnnotationBean depose end:{}", System.currentTimeMillis() - begin);
} finally {
// 解除整体的阻塞
IocInit.ins().destoryFinish();
}
}
public void load() {
Thread.currentThread().setContextClreplacedLoader(this.getClreplaced().getClreplacedLoader());
log.info("AnnotationBean load:{} {} {}", new Gson().toJson(TeslaConfig.ins().getDubboDatasource()), new Gson().toJson(this.annotationPackages), Thread.currentThread().getContextClreplacedLoader());
// 没有配置dubbo数据源
if (null == TeslaConfig.ins().getDubboDatasource()) {
return;
}
String apiPackage = TeslaConfig.ins().getDubboDatasource().getApiPackage();
if (StringUtils.isNotEmpty(apiPackage.trim())) {
func = (desc) -> {
// 这里需要配置
String ap = apiPackage.replaceAll("\\.", "/");
log.info("get clreplacedLoader desc{} value:{} {}", desc, ap, desc.contains(ap));
if (desc.contains(ap)) {
return AnnotationBean.clreplaced.getClreplacedLoader();
}
return null;
};
}
this.applicationConfig = new ApplicationConfig(TeslaConfig.ins().getDubboDatasource().getAppName());
this.applicationConfig.setQosEnable(false);
this.registryConfig = new RegistryConfig(TeslaConfig.ins().getDubboDatasource().getRegAddress());
this.protocolConfig = new ProtocolConfig();
protocolConfig.setPort(-1);
protocolConfig.setTransporter("netty4");
protocolConfig.setThreadpool("fixed");
int threads = TeslaConfig.ins().getDubboDatasource().getThreads() > 0 ? TeslaConfig.ins().getDubboDatasource().getThreads() : 100;
protocolConfig.setThreads(threads);
Set<Field> consumers = new HashSet<>();
Set<Clreplaced> services = new HashSet<>();
for (String pkg : annotationPackages) {
for (Clreplaced klreplaced : Scans.me().scanPackage(pkg)) {
if (klreplaced.isInterface()) {
continue;
}
Service service = (Service) klreplaced.getAnnotation(Service.clreplaced);
if (service != null) {
log.info("--->dubbo add service:{}", klreplaced);
services.add(klreplaced);
}
for (Field field : klreplaced.getDeclaredFields()) {
if (field.getType().isInterface() && field.getAnnotation(Reference.clreplaced) != null) {
consumers.add(field);
}
}
}
}
// consumer
for (Field field : consumers) {
Reference ref = field.getAnnotation(Reference.clreplaced);
ReferenceConfig<?> rc = new ReferenceConfig<>(ref);
rc.setApplication(applicationConfig);
rc.setRegistry(registryConfig);
rc.setInterface(field.getType());
rc.setGroup(ref.group());
rc.setRetries(ref.retries());
rc.setTimeout(ref.timeout());
String name = R.UU32();
IocObject iobj = Iocs.wrap(rc);
iobj.setType(ReferenceBean.clreplaced);
DubboAgent.checkIocObject(name, iobj);
iobjs.put(name, iobj);
// 构造工厂
iobj = new IocObject();
iobj.setType(field.getType());
iobj.setFactory("$" + name + "#get");
iobjs.put(R.UU32(), iobj);
}
// provider
for (Clreplaced klreplaced : services) {
Service service = (Service) klreplaced.getAnnotation(Service.clreplaced);
ServiceBean sc = new ServiceBean<>(service);
sc.setApplication(applicationConfig);
sc.setRegistry(registryConfig);
sc.setProtocol(protocolConfig);
sc.setGroup(service.group());
sc.setVersion(service.version());
sc.setRetries(service.retries());
sc.setTag(service.tag());
// 使用jdk代理
// sc.setProxy("jdk");
// 从ioc容器中获取实现类
sc.setRef(ioc.getByType(klreplaced));
// 导出
sc.export();
providerList.add(sc);
String name = R.UU32();
IocObject iobj = Iocs.wrap(sc);
iobj.setType(ServiceBean.clreplaced);
DubboAgent.checkIocObject(name, iobj);
iobjs.put(name, iobj);
}
if (null != func) {
ClreplacedHelper.clreplacedLoaderFunSet.add(func);
}
log.info("clreplacedLoaderFunSet size:{}", ClreplacedHelper.clreplacedLoaderFunSet.size());
DubboProtocol protocol = DubboProtocol.getDubboProtocol();
Map<String, Exporter<?>> exporterMap = protocol.getExporterMap();
// 需要清除掉,不然下载加载有问题(cache中还保留原来clreplacedlader加载出来的类)
ReflectUtils.clear();
log.info("plugin exporterMap:{} : {}", exporterMap, protocol);
}
}
15
Source : SafDubboAutoConfiguration.java
with Apache License 2.0
from saf-group
with Apache License 2.0
from saf-group
@Bean(name = "defaultProtocolConfig")
@ConditionalOnMissingBean
@ConfigurationProperties(prefix = "dubbo.default.protocol")
public ProtocolConfig ProtocolConfigBean() {
ProtocolConfig config = new ProtocolConfig();
SafDubboUtil.initProtocolConfig(config);
return config;
}
15
Source : DubboDocAnnotationScanner.java
with Apache License 2.0
from KeRan213539
with Apache License 2.0
from KeRan213539
/**
* @author klw(213539 @ qq.com)
* @ClreplacedName: DubboDocAnnotationScanner
* Scan and process dubbo doc annotations
* @date 2020/2/2 18:26
*/
@Slf4j
@Import({ DubboDocProviderImpl.clreplaced })
public clreplaced DubboDocAnnotationScanner implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private ApplicationContext applicationContext;
@Autowired
private ApplicationConfig application;
@Autowired
private RegistryConfig registry;
@Autowired
private ProtocolConfig protocol;
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
// Register dubbo doc provider
IDubboDocProvider dubboDocProvider = applicationContext.getBean(IDubboDocProvider.clreplaced);
exportDubboService(IDubboDocProvider.clreplaced, dubboDocProvider, false);
log.info("================= Dubbo Doc--Start scanning and processing dubbo doc annotations ================");
Map<String, Object> apiModules = applicationContext.getBeansWithAnnotation(DubboApiModule.clreplaced);
apiModules.forEach((key, apiModuleTemp) -> {
Clreplaced<?> apiModuleClreplaced;
if (AopUtils.isAopProxy(apiModuleTemp)) {
apiModuleClreplaced = AopUtils.getTargetClreplaced(apiModuleTemp);
} else {
apiModuleClreplaced = apiModuleTemp.getClreplaced();
}
DubboApiModule moduleAnn = apiModuleClreplaced.getAnnotation(DubboApiModule.clreplaced);
if (!apiModuleClreplaced.isAnnotationPresent(Service.clreplaced)) {
log.warn("【Warning】{} @DubboApiModule annotation is used, but it is not a dubbo provider (without {} annotation)", apiModuleClreplaced.getName(), Service.clreplaced.getName());
return;
}
Service dubboService = apiModuleClreplaced.getAnnotation(Service.clreplaced);
boolean async = dubboService.async();
Map<String, Object> moduleCacheItem = new HashMap<>(4);
DubboDocCache.addApiModule(moduleAnn.apiInterface().getCanonicalName(), moduleCacheItem);
// module name
moduleCacheItem.put("moduleChName", moduleAnn.value());
// interface name containing package path
moduleCacheItem.put("moduleClreplacedName", moduleAnn.apiInterface().getCanonicalName());
// module version
moduleCacheItem.put("moduleVersion", moduleAnn.version());
Method[] apiModuleMethods = apiModuleClreplaced.getMethods();
// API basic information list in module cache
List<Map<String, Object>> moduleApiList = new ArrayList<>(apiModuleMethods.length);
moduleCacheItem.put("moduleApiList", moduleApiList);
for (Method method : apiModuleMethods) {
if (method.isAnnotationPresent(DubboApi.clreplaced)) {
DubboApi dubboApi = method.getAnnotation(DubboApi.clreplaced);
// API basic information in API list in module
Map<String, Object> apiLisreplacedem = new HashMap<>(4);
moduleApiList.add(apiLisreplacedem);
// API method name
apiLisreplacedem.put("apiName", method.getName());
// API name
apiLisreplacedem.put("apiChName", dubboApi.value());
// API description
apiLisreplacedem.put("description", dubboApi.description());
// API version
apiLisreplacedem.put("apiVersion", dubboApi.version());
// Description of API return data
apiLisreplacedem.put("apiRespDec", dubboApi.responseClreplacedDescription());
// Interface parameters and response information
Map<String, Object> apiParamsAndResp = new HashMap<>(2);
DubboDocCache.addApiParamsAndResp(moduleAnn.apiInterface().getCanonicalName() + "." + method.getName(), apiParamsAndResp);
Clreplaced<?>[] argsClreplaced = method.getParameterTypes();
Annotation[][] argsAnns = method.getParameterAnnotations();
Parameter[] parameters = method.getParameters();
List<Map<String, Object>> paramList = new ArrayList<>(argsClreplaced.length);
apiParamsAndResp.put("async", async);
apiParamsAndResp.put("apiName", method.getName());
apiParamsAndResp.put("apiChName", dubboApi.value());
apiParamsAndResp.put("apiVersion", dubboApi.version());
apiParamsAndResp.put("apiRespDec", dubboApi.responseClreplacedDescription());
apiParamsAndResp.put("apiModelClreplaced", moduleCacheItem.get("moduleClreplacedName"));
apiParamsAndResp.put("params", paramList);
apiParamsAndResp.put("response", ClreplacedTypeUtils.calss2Json(method.getGenericReturnType(), method.getReturnType()));
for (int i = 0; i < argsClreplaced.length; i++) {
Clreplaced<?> argClreplaced = argsClreplaced[i];
Annotation[] argAnns = argsAnns[i];
Map<String, Object> prarmLisreplacedem = new HashMap<>(2);
paramList.add(prarmLisreplacedem);
prarmLisreplacedem.put("prarmType", argClreplaced.getCanonicalName());
prarmLisreplacedem.put("prarmIndex", i);
RequestParam requestParam = null;
// Handling @RequestParam annotations on parameters
for (Annotation ann : argAnns) {
if (ann instanceof RequestParam) {
requestParam = (RequestParam) ann;
}
}
ParamBean paramBean = this.processHtmlType(argClreplaced, requestParam, null);
if (paramBean == null) {
// Not a basic type, handling properties in method parameters
List<ParamBean> apiParamsList = processField(argClreplaced);
if (apiParamsList != null && !apiParamsList.isEmpty()) {
prarmLisreplacedem.put("prarmInfo", apiParamsList);
}
} else {
// Is the basic type
Parameter methodParameter = parameters[i];
prarmLisreplacedem.put("name", methodParameter.getName());
prarmLisreplacedem.put("htmlType", paramBean.getHtmlType().name());
prarmLisreplacedem.put("allowableValues", paramBean.getAllowableValues());
if (requestParam != null) {
// Handling requestparam annotations on parameters
prarmLisreplacedem.put("nameCh", requestParam.value());
prarmLisreplacedem.put("description", requestParam.description());
prarmLisreplacedem.put("example", requestParam.example());
prarmLisreplacedem.put("defaultValue", requestParam.defaultValue());
prarmLisreplacedem.put("required", requestParam.required());
} else {
prarmLisreplacedem.put("required", false);
}
}
}
}
}
});
log.info("================= Dubbo Doc--Dubbo doc annotations scanning and processing completed ================");
}
/**
* @author klw([email protected])
* For the attributes in the method parameters, only one layer is processed.
* The deeper layer is directly converted to JSON, and the deeper layer is up to 5 layers
*/
private List<ParamBean> processField(Clreplaced<?> argClreplaced) {
List<ParamBean> apiParamsList = new ArrayList(16);
// get all fields
List<Field> allFields = ClreplacedTypeUtils.getAllFields(null, argClreplaced);
for (Field field : allFields) {
ParamBean paramBean = new ParamBean();
paramBean.setName(field.getName());
paramBean.setJavaType(field.getType().getCanonicalName());
RequestParam requestParam = null;
if (field.isAnnotationPresent(RequestParam.clreplaced)) {
// Handling @RequestParam annotations on properties
requestParam = field.getAnnotation(RequestParam.clreplaced);
paramBean.setNameCh(requestParam.value());
paramBean.setRequired(requestParam.required());
paramBean.setDescription(requestParam.description());
paramBean.setExample(requestParam.example());
paramBean.setDefaultValue(requestParam.defaultValue());
} else {
paramBean.setRequired(false);
}
if (this.processHtmlType(field.getType(), requestParam, paramBean) == null) {
// Not a basic type, handle as JSON
Object objResult = ClreplacedTypeUtils.initClreplacedTypeWithDefaultValue(field.getGenericType(), field.getType(), 0);
if (!ClreplacedTypeUtils.isBaseType(objResult)) {
paramBean.setHtmlType(HtmlTypeEnum.TEXT_AREA);
paramBean.setSubParamsJson(JSON.toJSONString(objResult, ClreplacedTypeUtils.FAST_JSON_FEATURES));
}
}
apiParamsList.add(paramBean);
}
return apiParamsList;
}
/**
* @author klw([email protected])
* Determine what HTML form elements to use
* @Date 2020/2/28 18:59
* @param: clreplacedType
* @param: annotation
* @param: prarm
* @return top.klw8.alita.dubbodoc.core.beans.ParamBean
*/
private ParamBean processHtmlType(Clreplaced<?> clreplacedType, RequestParam annotation, ParamBean prarm) {
if (prarm == null) {
prarm = new ParamBean();
}
if (annotation != null) {
prarm.setAllowableValues(annotation.allowableValues());
}
// Is there any allowed values
boolean hasAllowableValues = (prarm.getAllowableValues() != null && prarm.getAllowableValues().length > 0);
// Processed or not
boolean processed = false;
if (Integer.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.NUMBER_INTEGER);
processed = true;
} else if (Byte.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.TEXT_BYTE);
processed = true;
} else if (Long.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.NUMBER_INTEGER);
processed = true;
} else if (Double.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.NUMBER_DECIMAL);
processed = true;
} else if (Float.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.NUMBER_DECIMAL);
processed = true;
} else if (String.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.TEXT);
processed = true;
} else if (Character.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.TEXT_CHAR);
processed = true;
} else if (Short.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.NUMBER_INTEGER);
processed = true;
}
if (processed) {
// Processed, time to return
if (hasAllowableValues) {
// Allowed values has value, change to select
prarm.setHtmlType(HtmlTypeEnum.SELECT);
}
return prarm;
}
// haven't dealt with it. Go on
if (Boolean.clreplaced.isreplacedignableFrom(clreplacedType)) {
prarm.setHtmlType(HtmlTypeEnum.SELECT);
// Boolean can only be true / false. No matter what the previous allowed value is, it is forced to replace
prarm.setAllowableValues(new String[] { "true", "false" });
processed = true;
} else if (Enum.clreplaced.isreplacedignableFrom(clreplacedType)) {
// process enum
prarm.setHtmlType(HtmlTypeEnum.SELECT);
if (!hasAllowableValues) {
// If there is no optional value, it is taken from the enumeration.
// TODO If there is an optional value, it is necessary to check whether the optional value matches the enumeration. It is add it later
Object[] enumConstants = clreplacedType.getEnumConstants();
String[] enumAllowableValues = new String[enumConstants.length];
try {
Method getNameMethod = clreplacedType.getMethod("name");
for (int i = 0; i < enumConstants.length; i++) {
Object obj = enumConstants[i];
enumAllowableValues[i] = (String) getNameMethod.invoke(obj);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
log.error("", e);
}
prarm.setAllowableValues(enumAllowableValues);
}
processed = true;
}
if (processed) {
return prarm;
}
return null;
}
/**
* @author klw([email protected])
* export dubbo service for dubbo doc
*/
private <I, T> void exportDubboService(Clreplaced<I> serviceClreplaced, T serviceImplInstance, boolean async) {
ServiceConfig<T> service = new ServiceConfig<>();
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
service.setInterface(serviceClreplaced);
service.setRef(serviceImplInstance);
service.setAsync(async);
// service.setVersion("1.0.0");
service.export();
}
}
15
Source : DubboHealthIndicator.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private Map<String, String> resolveStatusCheckerNamesMapFromProtocolConfigs() {
Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>();
for (Map.Entry<String, ProtocolConfig> entry : protocolConfigs.entrySet()) {
String beanName = entry.getKey();
ProtocolConfig protocolConfig = entry.getValue();
Set<String> statusCheckerNames = getStatusCheckerNames(protocolConfig);
for (String statusCheckerName : statusCheckerNames) {
String source = buildSource(beanName, protocolConfig);
statusCheckerNamesMap.put(statusCheckerName, source);
}
}
return statusCheckerNamesMap;
}
15
Source : AbstractServiceBuilderTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
void addProtocol() {
ProtocolConfig protocol = new ProtocolConfig();
ServiceBuilder builder = new ServiceBuilder();
replacedertions.replacedertNull(builder.build().getProtocols());
builder.addProtocol(protocol);
replacedertions.replacedertNotNull(builder.build().getProtocols());
replacedertions.replacedertEquals(1, builder.build().getProtocols().size());
replacedertions.replacedertEquals(protocol, builder.build().getProtocol());
}
15
Source : AbstractServiceBuilderTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
void build() {
ProtocolConfig protocol = new ProtocolConfig();
ServiceBuilder builder = new ServiceBuilder();
builder.version("version").group("group").deprecated(true).delay(1000).export(false).weight(1).doreplacedent("doreplacedent").dynamic(true).token("token").accesslog("accesslog").addProtocol(protocol).protocolIds("protocolIds").tag("tag").executes(100).register(false).warmup(200).serialization("serialization").id("id").prefix("prefix");
ServiceConfig config = builder.build();
ServiceConfig config2 = builder.build();
replacedertions.replacedertEquals("id", config.getId());
replacedertions.replacedertEquals("prefix", config.getPrefix());
replacedertions.replacedertEquals("version", config.getVersion());
replacedertions.replacedertEquals("group", config.getGroup());
replacedertions.replacedertEquals("doreplacedent", config.getDoreplacedent());
replacedertions.replacedertEquals("token", config.getToken());
replacedertions.replacedertEquals("accesslog", config.getAccesslog());
replacedertions.replacedertEquals("protocolIds", config.getProtocolIds());
replacedertions.replacedertEquals("tag", config.getTag());
replacedertions.replacedertEquals("serialization", config.getSerialization());
replacedertions.replacedertTrue(config.isDeprecated());
replacedertions.replacedertFalse(config.getExport());
replacedertions.replacedertTrue(config.isDynamic());
replacedertions.replacedertFalse(config.isRegister());
replacedertions.replacedertEquals(1000, config.getDelay());
replacedertions.replacedertEquals(1, config.getWeight());
replacedertions.replacedertEquals(100, config.getExecutes());
replacedertions.replacedertEquals(200, config.getWarmup());
replacedertions.replacedertNotSame(config, config2);
}
14
Source : RpcServer.java
with Apache License 2.0
from yametech
with Apache License 2.0
from yametech
public RpcServer addProtocol(String transporter, int port, Integer maxThreadNum) {
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName(DEFAULT_PROTOCOL_NAME);
protocol.setPort(port);
if (maxThreadNum != null) {
// 默认为fixed,core线程个数即为最大个数,不会按需创建线程,不会伸缩
protocol.setThreadpool("cached");
protocol.setThreads(maxThreadNum);
}
if (transporter != null && !transporter.trim().equals("")) {
protocol.setTransporter(transporter);
}
protocols.add(protocol);
return server;
}
14
Source : DubboConfiguration.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
@Bean
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setPort(port);
protocolConfig.setTransporter("netty4");
protocolConfig.setThreadpool("fixed");
protocolConfig.setThreads(dubboPoolSize);
return protocolConfig;
}
14
Source : HealthyTask.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
/**
* @author gaoyibo
* <p>
* modify [email protected]
* <p>
* 健康监测
* <p>
* http 直接调用
* dubbo 的去nacos上验证
*/
@Slf4j
@Component
public clreplaced HealthyTask extends AbstractTask {
@Autowired
private HttpTask httpTask;
@Autowired
private DubboTask dubboTask;
@Autowired
private NacosNaming nacosNaming;
private static final String TAG = "HealthChecker";
private static final String NUKE_TAG = "NukeTag";
private static final String NOTIFY = "notify";
@Autowired
private ApplicationConfig applicationConfig;
@Autowired
private ProtocolConfig protocolConfig;
@Autowired
private RegistryConfig registryConfig;
@Autowired
private FeiShuService feiShuService;
@Override
public TaskResult execute(TaskParam taskParam, TaskContext taskContext) {
log.info("health check:{}", new Gson().toJson(taskParam));
int taskId = taskParam.getTaskId();
HealthParam hp = new Gson().fromJson(taskParam.get(TaskParam.PARAM), HealthParam.clreplaced);
List<HealthCheckUrl> urls = hp.getUrls().stream().map(it -> {
HealthCheckUrl url = new HealthCheckUrl();
if (isHttp(it)) {
url.setType("http");
url.setUrl(it);
url.setIp(it.split("://|:")[1]);
} else if (isDubbo(it)) {
String[] ss = it.split("://|/");
MethodInfo mi = new MethodInfo();
mi.setIp(ss[1]);
mi.setServiceName(ss[2]);
mi.setGroup(ss[3]);
mi.setMethodName(ss[4]);
url.setMethodInfo(mi);
url.setType("dubbo");
url.setIp(ss[1]);
}
return url;
}).collect(Collectors.toList());
PipelineInfo pipelineInfo = hp.getPipelineInfo();
HealthResult result = new HealthResult();
result.setPipelineInfo(pipelineInfo);
List<ServiceInfo> resList = urls.stream().map(it -> {
if (it.getType().equals(HealthCheckUrl.HTTP)) {
TaskParam tp = new TaskParam();
HttpTaskParam p = new HttpTaskParam();
p.setMethodType("get");
p.setUrl(it.getUrl());
tp.put(TaskParam.PARAM, new Gson().toJson(p));
TaskResult res = httpTask.execute(tp, new TaskContext());
ServiceInfo si = new ServiceInfo();
si.setType("http");
si.setStatus(res.getCode() == TaskResult.Success().getCode() ? 0 : 1);
si.setIp(it.getIp());
return si;
} else if (it.getType().equals(HealthCheckUrl.DUBBO)) {
MethodInfo mi = it.getMethodInfo();
Pair<Integer, Long> pair = getDubboServiceStatus(mi.getServiceName(), mi.getGroup(), mi.getIp(), taskId, taskContext);
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setServiceName(mi.getServiceName());
serviceInfo.setGroup(mi.getGroup());
serviceInfo.setType("dubbo");
serviceInfo.setIp(it.getIp());
serviceInfo.setStatus(pair.getKey());
serviceInfo.setQps(pair.getValue());
return serviceInfo;
}
return null;
}).filter(it -> null != it).collect(Collectors.toList());
result.setServiceInfoList(resList);
taskContext.notifyMsg(TAG, new Gson().toJson(result));
// 清除不再适用的docker容器
if (resList.size() > 0 && resList.get(0).getType().equals("dubbo")) {
Set<String> ipSet = resList.stream().map(it -> it.getIp()).collect(Collectors.toSet());
String serviceName = resList.get(0).getServiceName();
serviceName = "providers:" + serviceName;
if (StringUtils.isNotEmpty(resList.get(0).getGroup())) {
serviceName = serviceName + ":" + resList.get(0).getGroup();
}
// nukeService(ipSet, serviceName, pipelineInfo, taskContext);
}
return TaskResult.Success();
}
private boolean isDubbo(String it) {
return it.startsWith("dubbo");
}
private boolean isHttp(String it) {
return it.startsWith("http");
}
private void nukeService(Set<String> ipSet, String serviceName, PipelineInfo pipelineInfo, TaskContext taskContext) {
try {
HealthResult result = new HealthResult();
result.setPipelineInfo(pipelineInfo);
List<Instance> instance = nacosNaming.getAllInstances(serviceName);
List<ServiceInfo> list = instance.stream().filter(it -> {
if (it.isEnabled() && it.isHealthy() && !ipSet.contains(it.getIp())) {
return true;
}
return false;
}).map(it -> {
ServiceInfo info = new ServiceInfo();
info.setIp(it.getIp());
return info;
}).collect(Collectors.toList());
result.setServiceInfoList(list);
taskContext.notifyMsg(NUKE_TAG, new Gson().toJson(result));
} catch (Throwable e) {
log.error("error:{}", e.getMessage());
}
}
/**
* 0 正常 1 有问题
*
* @param serviceName
* @param group
* @param ip
* @param taskContext
* @return
*/
private Pair<Integer, Long> getDubboServiceStatus(String serviceName, String group, String ip, int taskId, TaskContext taskContext) {
long now = System.currentTimeMillis();
serviceName = "providers:" + serviceName;
if (StringUtils.isNotEmpty(group)) {
serviceName = serviceName + ":" + group;
}
try {
List<Instance> instance = nacosNaming.getAllInstances(serviceName);
Optional<Instance> optional = instance.stream().filter(it -> it.getIp().equals(ip) && it.isEnabled() && it.isHealthy()).findFirst();
if (optional.isPresent()) {
try {
String interfaceName = optional.get().getMetadata().get("interface");
Map data = getDubboServiceStatusByGeneric(optional.get().getIp(), optional.get().getPort(), interfaceName, optional.get().getMetadata().get("group"), "health");
log.info("data:{}", data);
// 标准的接口实现必须返回qps
if (null != data && data.containsKey("qps")) {
return Pair.of(0, (long) data.get("qps"));
}
} catch (Throwable ex) {
log.error("error:{}", ex.getMessage());
sendMsg(taskContext, now, taskId, serviceName, ip, ex.getMessage());
}
} else {
sendMsg(taskContext, now, taskId, serviceName, ip, "");
}
// 如果没有这个ip没有服务,那么是有问题的
return optional.isPresent() ? Pair.of(0, 0L) : Pair.of(1, 0L);
} catch (NacosException e) {
log.warn("getDubboServiceStatus error:{}", e.getMessage());
}
return Pair.of(0, 0L);
}
private void sendMsg(TaskContext taskContext, long now, int taskId, String serviceName, String ip, String error) {
if (checkNotifyTime(taskContext, now)) {
taskContext.put(NOTIFY, String.valueOf(now + TimeUnit.MINUTES.toMillis(1)));
feiShuService.sendMsg("", "health check|" + taskId + "|" + serviceName + "|" + ip + "|error|" + error);
}
}
private boolean checkNotifyTime(TaskContext context, long now) {
String time = context.get(NOTIFY);
if (StringUtils.isEmpty(time)) {
return true;
}
long t = Long.valueOf(time);
if (now - t >= 0) {
return true;
}
return false;
}
/**
* 获取服务的健康情况
* 方法是固定的health 参数固定为空
*
* @param ip
* @param port
* @param interfaceName
* @param group
* @param methodName
* @return
*/
public Map getDubboServiceStatusByGeneric(String ip, int port, String interfaceName, String group, String methodName) {
ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
reference.setApplication(applicationConfig);
reference.setRegistry(registryConfig);
reference.setInterface(interfaceName);
reference.setGeneric(true);
reference.setGroup(group);
reference.setTimeout(1000);
RpcContext.getContext().setAttachment(Constants.TIMEOUT_KEY, "1000");
RpcContext.getContext().setAttachment(Constants.PROVIDER_IP, ip);
RpcContext.getContext().setAttachment(Constants.PROVIDER_PORT, String.valueOf(port));
RpcContext.getContext().setAttachment(Constants.MUST_PROVIDER_IP_PORT, "true");
ReferenceConfigCache cache = ReferenceConfigCache.getCache();
GenericService genericService = cache.get(reference);
String[] parameterTypes = new String[] {};
Object res = genericService.$invoke(methodName, parameterTypes, new Object[] {});
log.info("res:{}", res);
Map m = (Map) res;
Map data = (Map) m.get("data");
return data;
}
}
14
Source : DubboConfiguration.java
with Apache License 2.0
from XiaoMi
with Apache License 2.0
from XiaoMi
@Bean
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setPort(port);
protocolConfig.setTransporter("netty4");
protocolConfig.setThreadpool("fixed");
protocolConfig.setThreads(200);
return protocolConfig;
}
14
Source : BasicServicesCfg.java
with Apache License 2.0
from KeRan213539
with Apache License 2.0
from KeRan213539
/**
* @author klw(213539 @ qq.com)
* @ClreplacedName: BasicServicesCfg
* @Description: basic-services配制
* @date 2019/9/17 14:08
*/
@Configuration
@MapperScan("top.klw8.alita.service.authority.mapper")
@Import({ UserCacheHelper.clreplaced, AlitaUserServiceImpl.clreplaced, SystemAuthoritysCatlogServiceImpl.clreplaced, SystemAuthoritysServiceImpl.clreplaced, SystemRoleServiceImpl.clreplaced, DevHelperProviderImpl.clreplaced, AuthorityAdminProviderImpl.clreplaced, AlitaUserProvider.clreplaced })
public clreplaced BasicServicesCfg {
@Autowired
private ApplicationConfig application;
@Autowired
private RegistryConfig registry;
@Autowired
private ProtocolConfig protocol;
@Autowired
private Environment env;
@Bean
public Object regDubboProviders(@Autowired IDevHelperProvider devHelperProvider, @Autowired IAuthorityAdminProvider authorityAdminProvider, @Autowired IAlitaUserProvider alitaUserProvider) throws InstantiationException, IllegalAccessException {
String[] activeprofiles = env.getActiveProfiles();
for (String activeprofile : activeprofiles) {
if (activeprofile.equals("dev")) {
exportDubboService(IDevHelperProvider.clreplaced, devHelperProvider);
}
}
exportDubboService(IAlitaUserProvider.clreplaced, alitaUserProvider);
exportDubboService(IAuthorityAdminProvider.clreplaced, authorityAdminProvider);
return new Object();
}
// @Bean
// public IAlitaUserService alitaUserService(){
// return new AlitaUserServiceImpl();
// }
//
// @Bean
// public ISystemAuthoritysCatlogService systemAuthoritysCatlogService() throws InstantiationException, IllegalAccessException {
// String[] activeprofiles = env.getActiveProfiles();
// for (String activeprofile : activeprofiles) {
// if (activeprofile.equals("dev")) {
// exportDubboService(IDevHelperProvider.clreplaced, DevHelperProviderImpl.clreplaced);
// }
// }
// exportDubboService(IAuthorityAdminProvider.clreplaced, AuthorityAdminProviderImpl.clreplaced);
// exportDubboService(IAlitaUserProvider.clreplaced, AlitaUserProvider.clreplaced);
//
// return new SystemAuthoritysCatlogServiceImpl();
// }
//
// @Bean
// public ISystemAuthoritysService systemAuthoritysService(){
// return new SystemAuthoritysServiceImpl();
// }
//
// @Bean
// public ISystemRoleService systemRoleService(){
// return new SystemRoleServiceImpl();
// }
private <I, T> void exportDubboService(Clreplaced<I> serviceClreplaced, T serviceImplInstance) throws IllegalAccessException, InstantiationException {
// 此实例很重,封装了与注册中心的连接,请自行缓存,否则可能造成内存和连接泄漏
ServiceConfig<T> service = new ServiceConfig<>();
service.setApplication(application);
// 多个注册中心可以用setRegistries()
service.setRegistry(registry);
// 多个协议可以用setProtocols()
service.setProtocol(protocol);
service.setInterface(serviceClreplaced);
service.setRef(serviceImplInstance);
service.setAsync(true);
// service.setVersion("1.0.0");
// 暴露及注册服务
service.export();
}
}
14
Source : DubboNamespaceHandlerTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testDefaultProtocol() {
ClreplacedPathXmlApplicationContext ctx = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/override-protocol.xml");
ctx.start();
ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.clreplaced);
replacedertThat(protocolConfig.getName(), is("dubbo"));
}
14
Source : UrlTestBase.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@SuppressWarnings("unused")
public clreplaced UrlTestBase {
// ======================================================
// data column definition
// ======================================================
protected static final int KEY = 0;
protected static final int URL_KEY = 1;
protected static final int TESTVALUE1 = 4;
private static final Logger log = LoggerFactory.getLogger(UrlTestBase.clreplaced);
private static final int TYPE = 2;
private static final int DEFAULT = 3;
private static final int TESTVALUE2 = 5;
private static final int TESTVALUE3 = 6;
private static final int TESTVALUE4 = 7;
private static final int TESTVALUE5 = 8;
private static final int TESTVALUE6 = 9;
private static final int TESTVALUE7 = 10;
protected ApplicationConfig appConfForProvider;
protected ApplicationConfig appConfForService;
protected RegistryConfig regConfForProvider;
protected RegistryConfig regConfForService;
protected ProviderConfig provConf;
protected ProtocolConfig protoConfForProvider;
protected ProtocolConfig protoConfForService;
protected MethodConfig methodConfForService;
protected ServiceConfig<DemoService> servConf;
protected Object[][] servConfTable = { { "proxy", "proxy", "string", "javreplacedist", "jdk", "javreplacedist", "", "", "", "" }, { "actives", "actives", "int", 0, 90, "", "", "", "", "" }, { "executes", "executes", "int", 0, 90, "", "", "", "", "" }, { "deprecated", "deprecated", "boolean", false, true, "", "", "", "", "" }, { "dynamic", "dynamic", "boolean", true, false, "", "", "", "", "" }, { "accesslog", "accesslog", "string", "", "haominTest", "", "", "", "", "" }, { "doreplacedent", "doreplacedent", "string", "", "http://b2b-doc.alibaba-inc.com/display/RC/dubbo_devguide.htm?testquery=你好你好", "", "", "", "", "" }, { "weight", "weight", "int", 0, 90, "", "", "", "", "" } // {"filter", "service.filter", "string", "", "", "", "", "", "", ""},
// {"listener", "listener", "string", "", "", "", "", "", "", ""},
};
protected Object[][] regConfForServiceTable = { // {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""},
// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""},
// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""},
// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""},
// {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""},
{ "dynamic", "dynamic", "boolean", true, false, "", "", "", "", "" } };
protected Object[][] provConfTable = { { "cluster", "default.cluster", "string", "string", "failover", "failfast", "failsafe", "", "", "" }, { "async", "default.async", "boolean", false, true, "", "", "", "", "" }, { "loadbalance", "default.loadbalance", "string", "random", "leastactive", "", "", "", "", "" }, { "connections", "default.connections", "int", 0, 60, "", "", "", "", "" }, { "retries", "default.retries", "int", 2, 60, "", "", "", "", "" }, { "timeout", "default.timeout", "int", 5000, 60, "", "", "", "", "" } // change by fengting listener 没有缺省值
// {"listener", "exporter.listener", "string", "", "", "", "", "", "", ""},
// {"filter", "service.filter", "string", "", "", "", "", "", "", ""},
};
protected Object[][] methodConfForServiceTable = { { "actives", "sayName.actives", "int", 0, 90, "", "", "", "", "" }, { "executes", "sayName.executes", "int", 0, 90, "", "", "", "", "" }, { "deprecated", "sayName.deprecated", "boolean", false, true, "", "", "", "", "" }, { "async", "sayName.async", "boolean", false, true, "", "", "", "", "" }, { "timeout", "sayName.timeout", "int", 0, 90, "", "", "", "", "" } };
protected DemoService demoService = new DemoServiceImpl();
private Object[][] appConfForProviderTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] appConfForServiceTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] regConfForProviderTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] protoConfForProviderTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] protoConfForServiceTable = { { "", "", "", "", "", "", "", "", "", "" } };
// ======================================================
// data table manipulation utils
// ======================================================
protected String genParamString(Object urlKey, Object value) {
return (String) urlKey + "=" + value.toString();
}
protected <T> void fillConfigs(T conf, Object[][] table, int column) {
for (Object[] row : table) {
fillConfig(conf, row, column);
}
}
protected <T> void fillConfig(T conf, Object[] row, int column) {
RpcConfigGetSetProxy proxy = new RpcConfigGetSetProxy(conf);
proxy.setValue((String) row[KEY], row[column]);
}
@SuppressWarnings("deprecation")
protected void initServConf() {
appConfForProvider = new ApplicationConfig();
appConfForService = new ApplicationConfig();
regConfForProvider = new RegistryConfig();
regConfForService = new RegistryConfig();
provConf = new ProviderConfig();
protoConfForProvider = new ProtocolConfig("mockprotocol");
protoConfForService = new ProtocolConfig("mockprotocol");
methodConfForService = new MethodConfig();
servConf = new ServiceConfig<DemoService>();
provConf.setApplication(appConfForProvider);
servConf.setApplication(appConfForService);
provConf.setRegistry(regConfForProvider);
servConf.setRegistry(regConfForService);
provConf.setProtocols(Arrays.asList(new ProtocolConfig[] { protoConfForProvider }));
servConf.setProtocols(Arrays.asList(new ProtocolConfig[] { protoConfForService }));
servConf.setMethods(Arrays.asList(new MethodConfig[] { methodConfForService }));
servConf.setProvider(provConf);
servConf.setRef(demoService);
servConf.setInterfaceClreplaced(DemoService.clreplaced);
methodConfForService.setName("sayName");
regConfForService.setAddress("127.0.0.1:9090");
regConfForService.setProtocol("mockregistry");
appConfForService.setName("ConfigTests");
}
protected String getProviderParamString() {
return servConf.getExportedUrls().get(0).toString();
}
/**
* @param paramStringFromDb
* @param dataTable
* @param configName
* @param column
*/
protected void replacedertUrlStringWithLocalTable(String paramStringFromDb, Object[][] dataTable, String configName, int column) {
final String FAILLOG_HEADER = "The following config items are not found in URLONE: ";
log.warn("Verifying service url for " + configName + "... ");
log.warn("Consumer url string: " + paramStringFromDb);
String failLog = FAILLOG_HEADER;
for (Object[] row : dataTable) {
String targetString = genParamString(row[URL_KEY], row[column]);
log.warn("Checking " + (String) row[KEY] + "for" + targetString);
if (paramStringFromDb.contains(targetString)) {
log.warn((String) row[KEY] + " --> " + targetString + " OK!");
} else {
failLog += targetString + ", ";
}
}
if (!failLog.equals(FAILLOG_HEADER)) {
fail(failLog);
}
}
}
14
Source : UrlTestBase.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@SuppressWarnings("unused")
public clreplaced UrlTestBase {
// ======================================================
// data column definition
// ======================================================
protected static final int KEY = 0;
protected static final int URL_KEY = 1;
protected static final int TESTVALUE1 = 4;
private static final Logger log = LoggerFactory.getLogger(UrlTestBase.clreplaced);
private static final int TYPE = 2;
private static final int DEFAULT = 3;
private static final int TESTVALUE2 = 5;
private static final int TESTVALUE3 = 6;
private static final int TESTVALUE4 = 7;
private static final int TESTVALUE5 = 8;
private static final int TESTVALUE6 = 9;
private static final int TESTVALUE7 = 10;
protected ApplicationConfig application = new ApplicationConfig();
protected RegistryConfig regConfForProvider;
protected RegistryConfig regConfForService;
protected ProviderConfig provConf;
protected ProtocolConfig protoConfForProvider;
protected ProtocolConfig protoConfForService;
protected MethodConfig methodConfForService;
protected ServiceConfig<DemoService> servConf;
protected Object[][] servConfTable = { { "proxy", "proxy", "string", "javreplacedist", "jdk", "javreplacedist", "", "", "", "" }, { "actives", "actives", "int", 0, 90, "", "", "", "", "" }, { "executes", "executes", "int", 0, 90, "", "", "", "", "" }, { "deprecated", "deprecated", "boolean", false, true, "", "", "", "", "" }, { "dynamic", "dynamic", "boolean", true, false, "", "", "", "", "" }, { "accesslog", "accesslog", "string", "", "haominTest", "", "", "", "", "" }, { "doreplacedent", "doreplacedent", "string", "", "http://dubbo.apache.org/zh-cn/docs/user/quick-start.html?testquery=你好你好", "", "", "", "", "" }, { "weight", "weight", "int", 0, 90, "", "", "", "", "" } // {"filter", "service.filter", "string", "", "", "", "", "", "", ""},
// {"listener", "listener", "string", "", "", "", "", "", "", ""},
};
protected Object[][] regConfForServiceTable = { // {"timeout", "registry.timeout", "int", 5000, 9000, "", "", "", "", ""},
// {"file", "registry.file", "string", "", "regConfForServiceTable.log", "", "", "", "", ""},
// {"wait", "registry.wait", "int", 0, 9000, "", "", "", "", ""},
// {"transport", "registry.transporter", "string", "netty", "mina", "", "", "", "", ""},
// {"subscribe", "subscribe", "boolean", true, false, "", "", "", "", ""},
{ "dynamic", "dynamic", "boolean", true, false, "", "", "", "", "" } };
protected Object[][] provConfTable = { { "cluster", "cluster", "string", "string", "failover", "failfast", "failsafe", "", "", "" }, { "async", "async", "boolean", false, true, "", "", "", "", "" }, { "loadbalance", "loadbalance", "string", "random", "leastactive", "", "", "", "", "" }, { "connections", "connections", "int", 0, 60, "", "", "", "", "" }, { "retries", "retries", "int", 2, 60, "", "", "", "", "" }, { "timeout", "timeout", "int", 5000, 60, "", "", "", "", "" } // change by fengting listener 没有缺省值
// {"listener", "exporter.listener", "string", "", "", "", "", "", "", ""},
// {"filter", "service.filter", "string", "", "", "", "", "", "", ""},
};
protected Object[][] methodConfForServiceTable = { { "actives", "sayName.actives", "int", 0, 90, "", "", "", "", "" }, { "executes", "sayName.executes", "int", 0, 90, "", "", "", "", "" }, { "deprecated", "sayName.deprecated", "boolean", false, true, "", "", "", "", "" }, { "async", "sayName.async", "boolean", false, true, "", "", "", "", "" }, { "timeout", "sayName.timeout", "int", 0, 90, "", "", "", "", "" } };
protected DemoService demoService = new DemoServiceImpl();
private Object[][] appConfForProviderTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] appConfForServiceTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] regConfForProviderTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] protoConfForProviderTable = { { "", "", "", "", "", "", "", "", "", "" } };
private Object[][] protoConfForServiceTable = { { "", "", "", "", "", "", "", "", "", "" } };
// ======================================================
// data table manipulation utils
// ======================================================
protected String genParamString(Object urlKey, Object value) {
return (String) urlKey + "=" + value.toString();
}
protected <T> void fillConfigs(T conf, Object[][] table, int column) {
for (Object[] row : table) {
fillConfig(conf, row, column);
}
}
protected <T> void fillConfig(T conf, Object[] row, int column) {
RpcConfigGetSetProxy proxy = new RpcConfigGetSetProxy(conf);
proxy.setValue((String) row[KEY], row[column]);
}
@SuppressWarnings("deprecation")
protected void initServConf() {
regConfForProvider = new RegistryConfig();
regConfForService = new RegistryConfig();
provConf = new ProviderConfig();
protoConfForProvider = new ProtocolConfig("mockprotocol");
protoConfForService = new ProtocolConfig("mockprotocol");
methodConfForService = new MethodConfig();
servConf = new ServiceConfig<DemoService>();
// provConf.setApplication(appConfForProvider);
servConf.setApplication(application);
provConf.setRegistry(regConfForProvider);
servConf.setRegistry(regConfForService);
provConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForProvider)));
servConf.setProtocols(new ArrayList<>(Arrays.asList(protoConfForService)));
servConf.setMethods(Arrays.asList(new MethodConfig[] { methodConfForService }));
servConf.setProvider(provConf);
servConf.setRef(demoService);
servConf.setInterfaceClreplaced(DemoService.clreplaced);
methodConfForService.setName("sayName");
regConfForService.setAddress("127.0.0.1:9090");
regConfForService.setProtocol("mockregistry");
application.setName("ConfigTests");
}
protected String getProviderParamString() {
return servConf.getExportedUrls().get(0).toString();
}
/**
* @param paramStringFromDb
* @param dataTable
* @param configName
* @param column
*/
protected void replacedertUrlStringWithLocalTable(String paramStringFromDb, Object[][] dataTable, String configName, int column) {
final String FAILLOG_HEADER = "The following config items are not found in URLONE: ";
log.warn("Verifying service url for " + configName + "... ");
log.warn("Consumer url string: " + paramStringFromDb);
String failLog = FAILLOG_HEADER;
for (Object[] row : dataTable) {
String targetString = genParamString(row[URL_KEY], row[column]);
log.warn("Checking " + (String) row[KEY] + "for" + targetString);
if (paramStringFromDb.contains(targetString)) {
log.warn((String) row[KEY] + " --> " + targetString + " OK!");
} else {
failLog += targetString + ", ";
}
}
if (!failLog.equals(FAILLOG_HEADER)) {
fail(failLog);
}
}
}
14
Source : AbstractServiceBuilderTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
void addProtocols() {
ProtocolConfig protocol = new ProtocolConfig();
ServiceBuilder builder = new ServiceBuilder();
replacedertions.replacedertNull(builder.build().getProtocols());
builder.addProtocols(Collections.singletonList(protocol));
replacedertions.replacedertNotNull(builder.build().getProtocols());
replacedertions.replacedertEquals(1, builder.build().getProtocols().size());
}
14
Source : Application.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void main(String[] args) throws Exception {
ServiceConfig<UserService> service = new ServiceConfig<>();
service.setInterface(UserService.clreplaced);
service.setRef(new UserServiceImpl());
ProtocolConfig protocolConfig = new ProtocolConfig("rest");
protocolConfig.setPort(8090);
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap.application(new ApplicationConfig("dubbo-provider-for-sc")).registry(new RegistryConfig(String.format("consul://%s:8500?registry-type=service", consulAddress))).protocol(protocolConfig).service(service).start();
System.out.println("dubbo service started");
new CountDownLatch(1).await();
}
14
Source : DubboProtocolConfigSupplier.java
with Apache License 2.0
from alibaba
with Apache License 2.0
from alibaba
@Override
public ProtocolConfig get() {
ProtocolConfig protocolConfig = null;
Collection<ProtocolConfig> protocols = this.protocols.getIfAvailable();
if (!isEmpty(protocols)) {
for (ProtocolConfig protocol : protocols) {
String protocolName = protocol.getName();
if (DEFAULT_PROTOCOL.equals(protocolName)) {
protocolConfig = protocol;
break;
}
}
if (protocolConfig == null) {
// If The ProtocolConfig bean named "dubbo" is
// absent, take first one of them
Iterator<ProtocolConfig> iterator = protocols.iterator();
protocolConfig = iterator.hasNext() ? iterator.next() : null;
}
}
if (protocolConfig == null) {
protocolConfig = new ProtocolConfig();
protocolConfig.setName(DEFAULT_PROTOCOL);
}
return protocolConfig;
}
13
Source : DubboNamespaceHandlerTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testCustomParameter() {
ClreplacedPathXmlApplicationContext ctx = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/customize-parameter.xml");
ctx.start();
ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.clreplaced);
replacedertThat(protocolConfig.getParameters().size(), is(1));
replacedertThat(protocolConfig.getParameters().get("protocol-paramA"), is("protocol-paramA"));
ServiceBean serviceBean = ctx.getBean(ServiceBean.clreplaced);
replacedertThat(serviceBean.getParameters().size(), is(1));
replacedertThat(serviceBean.getParameters().get("service-paramA"), is("service-paramA"));
}
13
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSystemPropertyOverrideProtocol() throws Exception {
System.setProperty("dubbo.protocol.port", "20812");
ClreplacedPathXmlApplicationContext providerContext = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/override-protocol.xml");
providerContext.start();
try {
ProtocolConfig dubbo = (ProtocolConfig) providerContext.getBean("dubbo");
replacedertEquals(20812, dubbo.getPort().intValue());
} finally {
System.setProperty("dubbo.protocol.port", "");
providerContext.stop();
providerContext.close();
}
}
13
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSystemPropertyOverrideMultiProtocol() throws Exception {
System.setProperty("dubbo.protocol.dubbo.port", "20814");
System.setProperty("dubbo.protocol.rmi.port", "10914");
ClreplacedPathXmlApplicationContext providerContext = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/override-multi-protocol.xml");
providerContext.start();
try {
ProtocolConfig dubbo = (ProtocolConfig) providerContext.getBean("dubbo");
replacedertEquals(20814, dubbo.getPort().intValue());
ProtocolConfig rmi = (ProtocolConfig) providerContext.getBean("rmi");
replacedertEquals(10914, rmi.getPort().intValue());
} finally {
System.setProperty("dubbo.protocol.dubbo.port", "");
System.setProperty("dubbo.protocol.rmi.port", "");
providerContext.stop();
providerContext.close();
}
}
13
Source : DubboConfigurationProperties.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Dubbo {@link ConfigurationProperties Config Properties} only used to generate JSON metadata(non-public clreplaced)
*
* @since 2.7.1
*/
@ConfigurationProperties(DUBBO_PREFIX)
clreplaced DubboConfigurationProperties {
@NestedConfigurationProperty
private Config config = new Config();
@NestedConfigurationProperty
private Scan scan = new Scan();
// Single Config Bindings
@NestedConfigurationProperty
private ApplicationConfig application = new ApplicationConfig();
@NestedConfigurationProperty
private ModuleConfig module = new ModuleConfig();
@NestedConfigurationProperty
private RegistryConfig registry = new RegistryConfig();
@NestedConfigurationProperty
private ProtocolConfig protocol = new ProtocolConfig();
@NestedConfigurationProperty
private MonitorConfig monitor = new MonitorConfig();
@NestedConfigurationProperty
private ProviderConfig provider = new ProviderConfig();
@NestedConfigurationProperty
private ConsumerConfig consumer = new ConsumerConfig();
@NestedConfigurationProperty
private ConfigCenterBean configCenter = new ConfigCenterBean();
@NestedConfigurationProperty
private MetadataReportConfig metadataReport = new MetadataReportConfig();
// Multiple Config Bindings
private Map<String, ModuleConfig> modules = new LinkedHashMap<>();
private Map<String, RegistryConfig> registries = new LinkedHashMap<>();
private Map<String, ProtocolConfig> protocols = new LinkedHashMap<>();
private Map<String, MonitorConfig> monitors = new LinkedHashMap<>();
private Map<String, ProviderConfig> providers = new LinkedHashMap<>();
private Map<String, ConsumerConfig> consumers = new LinkedHashMap<>();
private Map<String, ConfigCenterBean> configCenters = new LinkedHashMap<>();
private Map<String, MetadataReportConfig> metadataReports = new LinkedHashMap<>();
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
public Scan getScan() {
return scan;
}
public void setScan(Scan scan) {
this.scan = scan;
}
public ApplicationConfig getApplication() {
return application;
}
public void setApplication(ApplicationConfig application) {
this.application = application;
}
public ModuleConfig getModule() {
return module;
}
public void setModule(ModuleConfig module) {
this.module = module;
}
public RegistryConfig getRegistry() {
return registry;
}
public void setRegistry(RegistryConfig registry) {
this.registry = registry;
}
public ProtocolConfig getProtocol() {
return protocol;
}
public void setProtocol(ProtocolConfig protocol) {
this.protocol = protocol;
}
public MonitorConfig getMonitor() {
return monitor;
}
public void setMonitor(MonitorConfig monitor) {
this.monitor = monitor;
}
public ProviderConfig getProvider() {
return provider;
}
public void setProvider(ProviderConfig provider) {
this.provider = provider;
}
public ConsumerConfig getConsumer() {
return consumer;
}
public void setConsumer(ConsumerConfig consumer) {
this.consumer = consumer;
}
public ConfigCenterBean getConfigCenter() {
return configCenter;
}
public void setConfigCenter(ConfigCenterBean configCenter) {
this.configCenter = configCenter;
}
public MetadataReportConfig getMetadataReport() {
return metadataReport;
}
public void setMetadataReport(MetadataReportConfig metadataReport) {
this.metadataReport = metadataReport;
}
public Map<String, ModuleConfig> getModules() {
return modules;
}
public void setModules(Map<String, ModuleConfig> modules) {
this.modules = modules;
}
public Map<String, RegistryConfig> getRegistries() {
return registries;
}
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
}
public Map<String, MonitorConfig> getMonitors() {
return monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
public Map<String, ConfigCenterBean> getConfigCenters() {
return configCenters;
}
public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) {
this.configCenters = configCenters;
}
public Map<String, MetadataReportConfig> getMetadataReports() {
return metadataReports;
}
public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) {
this.metadataReports = metadataReports;
}
static clreplaced Config {
/**
* Indicates multiple properties binding from externalized configuration or not.
*/
private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE;
/**
* The property name of override Dubbo config
*/
private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE;
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
static clreplaced Scan {
/**
* The basePackages to scan , the multiple-value is delimited by comma
*
* @see EnableDubbo#scanBasePackages()
*/
private Set<String> basePackages = new LinkedHashSet<>();
public Set<String> getBasePackages() {
return basePackages;
}
public void setBasePackages(Set<String> basePackages) {
this.basePackages = basePackages;
}
}
}
12
Source : DubboNamespaceHandlerTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testMultiProtocol() {
ClreplacedPathXmlApplicationContext ctx = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/multi-protocol.xml");
ctx.start();
Map<String, ProtocolConfig> protocolConfigMap = ctx.getBeansOfType(ProtocolConfig.clreplaced);
replacedertThat(protocolConfigMap.size(), is(2));
ProtocolConfig rmiProtocolConfig = protocolConfigMap.get("rmi");
replacedertThat(rmiProtocolConfig.getPort(), is(10991));
ProtocolConfig dubboProtocolConfig = protocolConfigMap.get("dubbo");
replacedertThat(dubboProtocolConfig.getPort(), is(20881));
}
12
Source : DefaultDubboConfigBinderTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Disabled
public // @Test
void testBinder() {
ApplicationConfig applicationConfig = new ApplicationConfig();
dubboConfigBinder.bind("dubbo.application", applicationConfig);
replacedertions.replacedertEquals("hello", applicationConfig.getName());
replacedertions.replacedertEquals("world", applicationConfig.getOwner());
RegistryConfig registryConfig = new RegistryConfig();
dubboConfigBinder.bind("dubbo.registry", registryConfig);
replacedertions.replacedertEquals("10.20.153.17", registryConfig.getAddress());
ProtocolConfig protocolConfig = new ProtocolConfig();
dubboConfigBinder.bind("dubbo.protocol", protocolConfig);
replacedertions.replacedertEquals(Integer.valueOf(20881), protocolConfig.getPort());
}
10
Source : DubboNamespaceHandlerTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testProviderXml() {
ClreplacedPathXmlApplicationContext ctx = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/demo-provider.xml");
ctx.start();
ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.clreplaced);
replacedertThat(protocolConfig, not(nullValue()));
replacedertThat(protocolConfig.getName(), is("dubbo"));
replacedertThat(protocolConfig.getPort(), is(20813));
ApplicationConfig applicationConfig = ctx.getBean(ApplicationConfig.clreplaced);
replacedertThat(applicationConfig, not(nullValue()));
replacedertThat(applicationConfig.getName(), is("demo-provider"));
DemoService service = ctx.getBean(DemoService.clreplaced);
replacedertThat(service, not(nullValue()));
}
10
Source : SslBasicProvider.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void main(String[] args) throws Exception {
new EmbeddedZooKeeper(Integer.parseInt(zookeeperPort), false).start();
// wait for embedded zookeeper start completely.
Thread.sleep(1000);
SslConfig sslConfig = new SslConfig();
if (args.length > 0) {
if (args.length < 2 || args.length > 3) {
System.out.println("USAGE: BasicProvider certChainFilePath privateKeyFilePath " + "[trustCertCollectionFilePath]\n Specify 'trustCertCollectionFilePath' only if you want " + "need Mutual TLS.");
System.exit(0);
}
sslConfig.setServerKeyCertChainPath(args[0]);
sslConfig.setServerPrivateKeyPath(args[1]);
if (args.length == 3) {
sslConfig.setServerTrustCertCollectionPath(args[2]);
}
}
ProtocolConfig protocolConfig = new ProtocolConfig("dubbo");
protocolConfig.setSslEnabled(true);
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap.application(new ApplicationConfig("ssl-provider")).registry(new RegistryConfig(zookeeperAddress)).protocol(protocolConfig).ssl(sslConfig);
ServiceConfig<DemoService> service = new ServiceConfig<>();
service.setInterface(DemoService.clreplaced);
service.setRef(new DemoServiceImpl());
bootstrap.service(service);
bootstrap.start();
System.out.println("dubbo service started");
new CountDownLatch(1).await();
}
10
Source : SslBasicProvider.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void main(String[] args) throws Exception {
new EmbeddedZooKeeper(2181, false).start();
// wait for embedded zookeeper start completely.
Thread.sleep(1000);
SslConfig sslConfig = new SslConfig();
if (args.length > 0) {
if (args.length < 2 || args.length > 3) {
System.out.println("USAGE: BasicProvider certChainFilePath privateKeyFilePath " + "[trustCertCollectionFilePath]\n Specify 'trustCertCollectionFilePath' only if you want " + "need Mutual TLS.");
System.exit(0);
}
sslConfig.setServerKeyCertChainPath(args[0]);
sslConfig.setServerPrivateKeyPath(args[1]);
if (args.length == 3) {
sslConfig.setServerTrustCertCollectionPath(args[2]);
}
}
ProtocolConfig protocolConfig = new ProtocolConfig("grpc");
protocolConfig.setSslEnabled(true);
DubboBootstrap bootstrap = DubboBootstrap.getInstance();
bootstrap.application(new ApplicationConfig("ssl-provider")).registry(new RegistryConfig("zookeeper://127.0.0.1:2181")).protocol(protocolConfig).ssl(sslConfig);
ServiceConfig<IGreeter> service = new ServiceConfig<>();
service.setInterface(IGreeter.clreplaced);
service.setRef(new GrpcGreeterImpl());
bootstrap.service(service);
bootstrap.start();
System.out.println("dubbo service started");
new CountDownLatch(1).await();
}
9
Source : RelaxedDubboConfigBinderTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
public void testBinder() {
ApplicationConfig applicationConfig = new ApplicationConfig();
Map<String, Object> properties = getSubProperties(environment.getPropertySources(), "dubbo.application");
dubboConfigBinder.bind(properties, true, true, applicationConfig);
replacedert.replacedertEquals("hello", applicationConfig.getName());
replacedert.replacedertEquals("world", applicationConfig.getOwner());
RegistryConfig registryConfig = new RegistryConfig();
properties = getSubProperties(environment.getPropertySources(), "dubbo.registry");
dubboConfigBinder.bind(properties, true, true, registryConfig);
replacedert.replacedertEquals("10.20.153.17", registryConfig.getAddress());
ProtocolConfig protocolConfig = new ProtocolConfig();
properties = getSubProperties(environment.getPropertySources(), "dubbo.protocol");
dubboConfigBinder.bind(properties, true, true, protocolConfig);
replacedert.replacedertEquals(Integer.valueOf(20881), protocolConfig.getPort());
}
8
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testXmlOverrideProperties() throws Exception {
ClreplacedPathXmlApplicationContext providerContext = new ClreplacedPathXmlApplicationContext(ConfigTest.clreplaced.getPackage().getName().replace('.', '/') + "/xml-override-properties.xml");
providerContext.start();
try {
ApplicationConfig application = (ApplicationConfig) providerContext.getBean("application");
replacedertEquals("demo-provider", application.getName());
replacedertEquals("world", application.getOwner());
RegistryConfig registry = (RegistryConfig) providerContext.getBean("registry");
replacedertEquals("N/A", registry.getAddress());
ProtocolConfig dubbo = (ProtocolConfig) providerContext.getBean("dubbo");
replacedertEquals(20813, dubbo.getPort().intValue());
} finally {
providerContext.stop();
providerContext.close();
}
}
8
Source : DubboAutoConfigurationOnSingleConfigTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* {@link DubboAutoConfiguration} Test On single Dubbo Configuration
*
* @since 2.7.0
*/
@RunWith(SpringRunner.clreplaced)
@TestPropertySource(properties = { "dubbo.application.name = dubbo-demo-application", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.address = zookeeper://192.168.99.100:32770", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.monitor.address=zookeeper://127.0.0.1:32770", "dubbo.provider.host=127.0.0.1", "dubbo.consumer.client=netty" })
@SpringBootTest(clreplacedes = { DubboAutoConfigurationOnSingleConfigTest.clreplaced })
@EnableAutoConfiguration
public clreplaced DubboAutoConfigurationOnSingleConfigTest {
@Autowired
private ApplicationConfig applicationConfig;
@Autowired
private ModuleConfig moduleConfig;
@Autowired
private RegistryConfig registryConfig;
@Autowired
private MonitorConfig monitorConfig;
@Autowired
private ProviderConfig providerConfig;
@Autowired
private ConsumerConfig consumerConfig;
@Autowired
private ProtocolConfig protocolConfig;
@Autowired(required = false)
private DubboAutoConfiguration.MultipleDubboConfigConfiguration multipleDubboConfigConfiguration;
@Autowired
private DubboAutoConfiguration.SingleDubboConfigConfiguration singleDubboConfigConfiguration;
@Autowired
private Environment environment;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testApplicationConfig() {
replacedert.replacedertEquals("dubbo-demo-application", applicationConfig.getName());
}
@Test
public void testModuleConfig() {
replacedert.replacedertEquals("dubbo-demo-module", moduleConfig.getName());
}
@Test
public void testRegistryConfig() {
replacedert.replacedertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
}
@Test
public void testMonitorConfig() {
replacedert.replacedertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress());
}
@Test
public void testProtocolConfig() {
replacedert.replacedertEquals("dubbo", protocolConfig.getName());
replacedert.replacedertEquals(Integer.valueOf(20880), protocolConfig.getPort());
}
@Test
public void testProviderConfig() {
replacedert.replacedertEquals("127.0.0.1", providerConfig.getHost());
}
@Test
public void testConsumerConfig() {
replacedert.replacedertEquals("netty", consumerConfig.getClient());
}
@Test
public void testMultipleDubboConfigConfiguration() {
replacedert.replacedertNotNull(multipleDubboConfigConfiguration);
}
@Test
public void testSingleDubboConfigConfiguration() {
replacedert.replacedertNotNull(singleDubboConfigConfiguration);
}
@Test
public void testServiceAnnotationBeanPostProcessor() {
replacedert.replacedertNotNull(multipleDubboConfigConfiguration);
}
}
7
Source : ProviderGenerator.java
with Apache License 2.0
from xuerong
with Apache License 2.0
from xuerong
static Object generateProvider(Clreplaced<?> serviceClreplaced, Object object, List<? extends RegistryConfig> registries) throws NotFoundException, CannotCompileException, IllegalAccessException, InstantiationException {
if (CollectionUtils.isEmpty(registries)) {
throw new MMException("registries is empty!");
}
// 生成代理接口
Clreplaced<?> proxyInterface = DubboHelper.generateProxyInterface(serviceClreplaced);
// 生成代理类
Clreplaced<?> proxyClreplaced = generateProxy(object, proxyInterface);
// 生成代理对象
Object proxyObject = proxyClreplaced.newInstance();
// 生成对应的dubbo服务提供者
ServiceConfig serviceConfig = new ServiceConfig();
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(20880);
ProviderConfig provider = new ProviderConfig();
provider.setExport(true);
provider.setProtocol(protocolConfig);
serviceConfig.setProvider(provider);
ApplicationConfig app = new ApplicationConfig(Util.humpToCenterLine(serviceClreplaced.getSimpleName()));
serviceConfig.setApplication(app);
serviceConfig.setRegistries(registries);
serviceConfig.setGeneric(Boolean.TRUE.toString());
serviceConfig.setInterface(proxyInterface);
serviceConfig.setRef(proxyObject);
serviceConfig.export();
return proxyObject;
}
7
Source : DubboConfigConfigurationTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSingle() throws IOException {
context.register(DubboConfigConfiguration.Single.clreplaced);
context.refresh();
// application
ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.clreplaced);
replacedertions.replacedertEquals("dubbo-demo-application", applicationConfig.getName());
// module
ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.clreplaced);
replacedertions.replacedertEquals("dubbo-demo-module", moduleConfig.getName());
// registry
RegistryConfig registryConfig = context.getBean(RegistryConfig.clreplaced);
replacedertions.replacedertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
// protocol
ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.clreplaced);
replacedertions.replacedertEquals("dubbo", protocolConfig.getName());
replacedertions.replacedertEquals(Integer.valueOf(20880), protocolConfig.getPort());
}
7
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSystemPropertyOverrideReferenceConfig() throws Exception {
System.setProperty("dubbo.reference.retries", "5");
try {
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.clreplaced);
service.setRef(new DemoServiceImpl());
service.setRegistry(new RegistryConfig(RegistryConfig.NO_AVAILABLE));
ProtocolConfig protocolConfig = new ProtocolConfig("injvm");
service.setProtocol(protocolConfig);
service.export();
ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>();
reference.setInterface(DemoService.clreplaced);
reference.setInjvm(true);
reference.setRetries(2);
reference.get();
replacedertEquals(Integer.valueOf(5), reference.getRetries());
} finally {
System.setProperty("dubbo.reference.retries", "");
}
}
7
Source : EtcdDubboServiceProviderBootstrap.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static void multipleRegistries() {
ProtocolConfig restProtocol = new ProtocolConfig();
restProtocol.setName("rest");
restProtocol.setId("rest");
restProtocol.setPort(-1);
RegistryConfig interfaceRegistry = new RegistryConfig();
interfaceRegistry.setId("interfaceRegistry");
interfaceRegistry.setAddress("etcd3://127.0.0.1:2379");
RegistryConfig serviceRegistry = new RegistryConfig();
serviceRegistry.setId("serviceRegistry");
serviceRegistry.setAddress("etcd3://127.0.0.1:2379?registry-type=service");
ServiceConfig<EchoService> echoService = new ServiceConfig<>();
echoService.setInterface(EchoService.clreplaced.getName());
echoService.setRef(new EchoServiceImpl());
// echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry));
ServiceConfig<UserService> userService = new ServiceConfig<>();
userService.setInterface(UserService.clreplaced.getName());
userService.setRef(new UserServiceImpl());
userService.setProtocol(restProtocol);
// userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry));
ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo");
// applicationConfig.setMetadataType("remote");
DubboBootstrap.getInstance().application(applicationConfig).registries(Arrays.asList(interfaceRegistry, serviceRegistry)).protocol(builder -> builder.port(-1).name("dubbo")).service(echoService).service(userService).start().await();
}
7
Source : DubboServiceProviderBootstrap.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private static void multipleRegistries() {
ProtocolConfig restProtocol = new ProtocolConfig();
restProtocol.setName("rest");
restProtocol.setId("rest");
restProtocol.setPort(-1);
RegistryConfig interfaceRegistry = new RegistryConfig();
interfaceRegistry.setId("interfaceRegistry");
interfaceRegistry.setAddress("zookeeper://127.0.0.1:2181");
RegistryConfig serviceRegistry = new RegistryConfig();
serviceRegistry.setId("serviceRegistry");
serviceRegistry.setAddress("zookeeper://127.0.0.1:2181?registry-type=service");
ServiceConfig<EchoService> echoService = new ServiceConfig<>();
echoService.setInterface(EchoService.clreplaced.getName());
echoService.setRef(new EchoServiceImpl());
// echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry));
ServiceConfig<UserService> userService = new ServiceConfig<>();
userService.setInterface(UserService.clreplaced.getName());
userService.setRef(new UserServiceImpl());
userService.setProtocol(restProtocol);
// userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry));
ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo");
applicationConfig.setMetadataType("remote");
DubboBootstrap.getInstance().application(applicationConfig).registries(Arrays.asList(interfaceRegistry, serviceRegistry)).protocol(builder -> builder.port(-1).name("dubbo")).metadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")).service(echoService).service(userService).start().await();
}
4
Source : DubboBenchmark.java
with Apache License 2.0
from catty-project
with Apache License 2.0
from catty-project
private static void startProvider() {
RegistryConfig registry = new RegistryConfig();
ProtocolConfig protocol = new ProtocolConfig();
registry.setAddress("N/A");
protocol.setName("dubbo");
protocol.setPort(25500);
protocol.setThreads(400);
protocol.setHost("0.0.0.0");
ServiceConfig<PojoService> service = new ServiceConfig<>();
Map<String, String> attributes = new HashMap<>();
attributes.put("heartbeat", "0");
service.setParameters(attributes);
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
service.setInterface(PojoService.clreplaced);
service.setRef(new PojoServiceImpl());
service.export();
}
4
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testDubboProtocolPortOverride() throws Exception {
String dubboPort = System.getProperty("dubbo.protocol.dubbo.port");
int port = 55555;
System.setProperty("dubbo.protocol.dubbo.port", String.valueOf(port));
ServiceConfig<DemoService> service = null;
try {
ApplicationConfig application = new ApplicationConfig();
application.setName("dubbo-protocol-port-override");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.clreplaced);
service.setRef(new DemoServiceImpl());
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
service.export();
replacedertions.replacedertEquals(port, service.getExportedUrls().get(0).getPort());
} finally {
if (StringUtils.isNotEmpty(dubboPort)) {
System.setProperty("dubbo.protocol.dubbo.port", dubboPort);
}
if (service != null) {
service.unexport();
}
}
}
3
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testProtocolRandomPort() throws Exception {
ServiceConfig<DemoService> demoService = null;
ServiceConfig<HelloService> helloService = null;
ApplicationConfig application = new ApplicationConfig();
application.setName("test-protocol-random-port");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("dubbo");
protocol.setPort(-1);
demoService = new ServiceConfig<DemoService>();
demoService.setInterface(DemoService.clreplaced);
demoService.setRef(new DemoServiceImpl());
demoService.setApplication(application);
demoService.setRegistry(registry);
demoService.setProtocol(protocol);
helloService = new ServiceConfig<HelloService>();
helloService.setInterface(HelloService.clreplaced);
helloService.setRef(new HelloServiceImpl());
helloService.setApplication(application);
helloService.setRegistry(registry);
helloService.setProtocol(protocol);
try {
demoService.export();
helloService.export();
replacedertions.replacedertEquals(demoService.getExportedUrls().get(0).getPort(), helloService.getExportedUrls().get(0).getPort());
} finally {
unexportService(demoService);
unexportService(helloService);
}
}
2
Source : ApacheDubboPluginTest.java
with Apache License 2.0
from yametech
with Apache License 2.0
from yametech
private static void initDubboConfig() {
ApplicationConfig providerAppConfig = new ApplicationConfig();
providerAppConfig.setName("dubbo-demo");
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(getPort());
protocolConfig.setThreads(10);
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
serviceConfig = new ServiceConfig<>();
serviceConfig.setApplication(providerAppConfig);
serviceConfig.setProtocol(protocolConfig);
serviceConfig.setInterface(DubboTestApi.clreplaced);
serviceConfig.setRef(new DubboTestApiImpl());
serviceConfig.setRegistry(registryConfig);
serviceConfig.export();
referenceConfig = new ReferenceConfig<>();
referenceConfig.setApplication(providerAppConfig);
referenceConfig.setInterface(DubboTestApi.clreplaced);
referenceConfig.setUrl("dubbo://localhost:" + getPort());
referenceConfig.setTimeout(3000);
genericReferenceConfig = new ReferenceConfig<>();
genericReferenceConfig.setApplication(providerAppConfig);
genericReferenceConfig.setInterface(DubboTestApi.clreplaced);
genericReferenceConfig.setUrl("dubbo://localhost:" + getPort());
genericReferenceConfig.setGeneric(true);
}
1
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSystemPropertyOverrideProperties() throws Exception {
String portString = System.getProperty("dubbo.protocol.port");
System.clearProperty("dubbo.protocol.port");
try {
int port = 1234;
System.setProperty("dubbo.protocol.port", String.valueOf(port));
ApplicationConfig application = new ApplicationConfig();
application.setName("aaa");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("N/A");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("rmi");
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.clreplaced);
service.setRef(new DemoServiceImpl());
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
service.export();
try {
URL url = service.toUrls().get(0);
// from api
replacedertEquals("aaa", url.getParameter("application"));
// from dubbo.properties
replacedertEquals("world", url.getParameter("owner"));
// from system property
replacedertEquals(1234, url.getPort());
} finally {
service.unexport();
}
} finally {
if (portString != null) {
System.setProperty("dubbo.protocol.port", portString);
}
}
}
0
Source : EnableDubboConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSingle() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(TestConfig.clreplaced);
context.refresh();
// application
ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.clreplaced);
replacedertions.replacedertEquals("dubbo-demo-application", applicationConfig.getName());
// module
ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.clreplaced);
replacedertions.replacedertEquals("dubbo-demo-module", moduleConfig.getName());
// registry
RegistryConfig registryConfig = context.getBean(RegistryConfig.clreplaced);
replacedertions.replacedertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress());
// protocol
ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.clreplaced);
replacedertions.replacedertEquals("dubbo", protocolConfig.getName());
replacedertions.replacedertEquals(Integer.valueOf(20880), protocolConfig.getPort());
// monitor
MonitorConfig monitorConfig = context.getBean(MonitorConfig.clreplaced);
replacedertions.replacedertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress());
// provider
ProviderConfig providerConfig = context.getBean(ProviderConfig.clreplaced);
replacedertions.replacedertEquals("127.0.0.1", providerConfig.getHost());
// consumer
ConsumerConfig consumerConfig = context.getBean(ConsumerConfig.clreplaced);
replacedertions.replacedertEquals("netty", consumerConfig.getClient());
}
0
Source : CacheTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void testCache(String type) throws Exception {
ApplicationConfig applicationConfig = new ApplicationConfig("cache-test");
RegistryConfig registryConfig = new RegistryConfig("N/A");
ProtocolConfig protocolConfig = new ProtocolConfig("injvm");
ServiceConfig<CacheService> service = new ServiceConfig<CacheService>();
service.setApplication(applicationConfig);
service.setRegistry(registryConfig);
service.setProtocol(protocolConfig);
service.setInterface(CacheService.clreplaced.getName());
service.setRef(new CacheServiceImpl());
service.export();
try {
ReferenceConfig<CacheService> reference = new ReferenceConfig<CacheService>();
reference.setApplication(applicationConfig);
reference.setInterface(CacheService.clreplaced);
reference.setUrl("injvm://127.0.0.1?scope=remote&cache=true");
MethodConfig method = new MethodConfig();
method.setName("findCache");
method.setCache(type);
reference.setMethods(Arrays.asList(method));
CacheService cacheService = reference.get();
try {
// verify cache, same result is returned for multiple invocations (in fact, the return value increases
// on every invocation on the server side)
String fix = null;
for (int i = 0; i < 3; i++) {
String result = cacheService.findCache("0");
replacedertTrue(fix == null || fix.equals(result));
fix = result;
Thread.sleep(100);
}
if ("lru".equals(type)) {
// default cache.size is 1000 for LRU, should have cache expired if invoke more than 1001 times
for (int n = 0; n < 1001; n++) {
String pre = null;
for (int i = 0; i < 10; i++) {
String result = cacheService.findCache(String.valueOf(n));
replacedertTrue(pre == null || pre.equals(result));
pre = result;
}
}
// verify if the first cache item is expired in LRU cache
String result = cacheService.findCache("0");
replacedertFalse(fix == null || fix.equals(result));
}
} finally {
reference.destroy();
}
} finally {
service.unexport();
}
}
0
Source : ConfigTest.java
with Apache License 2.0
from boomblog
with Apache License 2.0
from boomblog
@Test
public void testSystemPropertyOverrideApi() throws Exception {
System.setProperty("dubbo.application.name", "sysover");
System.setProperty("dubbo.application.owner", "sysowner");
System.setProperty("dubbo.registry.address", "N/A");
System.setProperty("dubbo.protocol.name", "dubbo");
System.setProperty("dubbo.protocol.port", "20834");
try {
ApplicationConfig application = new ApplicationConfig();
application.setName("aaa");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("127.0.0.1");
ProtocolConfig protocol = new ProtocolConfig();
protocol.setName("rmi");
protocol.setPort(1099);
ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
service.setInterface(DemoService.clreplaced);
service.setRef(new DemoServiceImpl());
service.setApplication(application);
service.setRegistry(registry);
service.setProtocol(protocol);
service.export();
try {
URL url = service.toUrls().get(0);
replacedertEquals("sysover", url.getParameter("application"));
replacedertEquals("sysowner", url.getParameter("owner"));
replacedertEquals("dubbo", url.getProtocol());
replacedertEquals(20834, url.getPort());
} finally {
service.unexport();
}
} finally {
System.setProperty("dubbo.application.name", "");
System.setProperty("dubbo.application.owner", "");
System.setProperty("dubbo.registry.address", "");
System.setProperty("dubbo.protocol.name", "");
System.setProperty("dubbo.protocol.port", "");
}
}
See More Examples