repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/XxxService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils.service;
public interface XxxService {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils.service;
public class FooServiceImpl implements FooService {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/utils/service/FooService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils.service;
public interface FooService {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Box.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.api;
public interface Box {
String getName();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.api;
import java.io.Serializable;
import java.util.List;
public interface DemoService {
String sayName(String name);
Box getBox();
void throwDemoException() throws DemoException;
List<User> getUsers(List<User> users);
int echo(int i);
default InnerClass callInnerClass() {
return new InnerClass();
}
class InnerClass implements Serializable {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/User.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.api;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public User() {}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return name == null ? -1 : name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof User)) {
return false;
}
User other = (User) obj;
if (this == other) {
return true;
}
if (name != null && other.name != null) {
return name.equals(other.name);
}
return false;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/DemoException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.api;
public class DemoException extends Exception {
private static final long serialVersionUID = -8213943026163641747L;
public DemoException() {
super();
}
public DemoException(String message, Throwable cause) {
super(message, cause);
}
public DemoException(String message) {
super(message);
}
public DemoException(Throwable cause) {
super(cause);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/api/Greeting.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.api;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface Greeting {
String hello();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/common/Person.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/common/Person.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.common;
import java.io.Serializable;
/**
* Person.java
*/
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvokerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.invoker;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.api.Greeting;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.sameInstance;
class DelegateProviderMetaDataInvokerTest {
private ServiceConfig service;
private Invoker<Greeting> invoker;
@BeforeEach
public void setUp() throws Exception {
service = Mockito.mock(ServiceConfig.class);
invoker = Mockito.mock(Invoker.class);
}
@Test
void testDelegate() {
DelegateProviderMetaDataInvoker<Greeting> delegate =
new DelegateProviderMetaDataInvoker<Greeting>(invoker, service);
delegate.getInterface();
Mockito.verify(invoker).getInterface();
delegate.getUrl();
Mockito.verify(invoker).getUrl();
delegate.isAvailable();
Mockito.verify(invoker).isAvailable();
Invocation invocation = Mockito.mock(Invocation.class);
delegate.invoke(invocation);
Mockito.verify(invoker).invoke(invocation);
delegate.destroy();
Mockito.verify(invoker).destroy();
assertThat(delegate.getMetadata(), sameInstance(service));
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java | dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/provider/impl/DemoServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.provider.impl;
import org.apache.dubbo.config.api.Box;
import org.apache.dubbo.config.api.DemoException;
import org.apache.dubbo.config.api.DemoService;
import org.apache.dubbo.config.api.User;
import java.util.List;
public class DemoServiceImpl implements DemoService {
public String sayName(String name) {
return "say:" + name;
}
public Box getBox() {
return null;
}
public void throwDemoException() throws DemoException {
throw new DemoException("DemoServiceImpl");
}
public List<User> getUsers(List<User> users) {
return users;
}
public int echo(int i) {
return i;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java | dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo;
import java.io.Serializable;
public class MultiClassLoaderServiceResult implements Serializable {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java | dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo;
import java.io.Serializable;
public class MultiClassLoaderServiceRequest implements Serializable {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderService.java | dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo;
public interface MultiClassLoaderService {
Object call(MultiClassLoaderServiceRequest innerRequest);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java | dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package demo;
import java.util.concurrent.atomic.AtomicReference;
public class MultiClassLoaderServiceImpl implements MultiClassLoaderService {
private AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference;
private AtomicReference<MultiClassLoaderServiceResult> innerResultReference;
public MultiClassLoaderServiceImpl(
AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference,
AtomicReference<MultiClassLoaderServiceResult> innerResultReference) {
this.innerRequestReference = innerRequestReference;
this.innerResultReference = innerResultReference;
}
@Override
public MultiClassLoaderServiceResult call(MultiClassLoaderServiceRequest innerRequest) {
innerRequestReference.set(innerRequest);
return innerResultReference.get();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigScopeModelInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.config.deploy.DefaultApplicationDeployer;
import org.apache.dubbo.config.deploy.DefaultModuleDeployer;
import org.apache.dubbo.config.deploy.FrameworkModelCleaner;
import org.apache.dubbo.config.utils.DefaultConfigValidator;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelInitializer;
public class ConfigScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
frameworkModel.addDestroyListener(new FrameworkModelCleaner());
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {
ScopeBeanFactory beanFactory = applicationModel.getBeanFactory();
beanFactory.registerBean(DefaultConfigValidator.class);
// applicationDeployer
ApplicationDeployer applicationDeployer = beanFactory.registerBean(DefaultApplicationDeployer.class);
applicationModel.setDeployer(applicationDeployer);
}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {
ScopeBeanFactory beanFactory = moduleModel.getBeanFactory();
// moduleDeployer
ModuleDeployer moduleDeployer = beanFactory.registerBean(DefaultModuleDeployer.class);
moduleModel.setDeployer(moduleDeployer);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceListener.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.SPI;
/**
* Listener for service config
*/
@SPI
public interface ServiceListener {
/**
* Callback when ServiceConfig is exported
* @param sc
*/
void exported(ServiceConfig sc);
/**
* Callback when ServiceConfig is unexported
* @param sc
*/
void unexported(ServiceConfig sc);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigPostProcessor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* 2019/12/30
* it will be instead of CommonConfigPostProcessor
*/
@SPI(scope = ExtensionScope.MODULE)
public interface ConfigPostProcessor {
default void postProcessReferConfig(ReferenceConfig referenceConfig) {}
default void postProcessServiceConfig(ServiceConfig serviceConfig) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/DubboShutdownHook.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.rpc.GracefulShutdown;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_SHUTDOWN_HOOK;
/**
* The shutdown hook thread to do the cleanup stuff.
* This is a singleton in order to ensure there is only one shutdown hook registered.
* Because {@link ApplicationShutdownHooks} use {@link java.util.IdentityHashMap}
* to store the shutdown hooks.
*/
public class DubboShutdownHook extends Thread {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboShutdownHook.class);
private final ApplicationModel applicationModel;
/**
* Has it already been registered or not?
*/
private final AtomicBoolean registered = new AtomicBoolean(false);
/**
* Has it already been destroyed or not?
*/
private final AtomicBoolean destroyed = new AtomicBoolean(false);
/**
* Whether ignore listen on shutdown hook?
*/
private final boolean ignoreListenShutdownHook;
public DubboShutdownHook(ApplicationModel applicationModel) {
super("DubboShutdownHook");
this.applicationModel = applicationModel;
Assert.notNull(this.applicationModel, "ApplicationModel is null");
ignoreListenShutdownHook = Boolean.parseBoolean(
ConfigurationUtils.getProperty(applicationModel, CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK));
if (ignoreListenShutdownHook) {
logger.info(
CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK + " configured, will ignore add shutdown hook to jvm.");
}
}
@Override
public void run() {
if (!ignoreListenShutdownHook && destroyed.compareAndSet(false, true)) {
if (logger.isInfoEnabled()) {
logger.info("Run shutdown hook now.");
}
doDestroy();
}
}
private void doDestroy() {
int timeout = ConfigurationUtils.getServerShutdownTimeout(applicationModel);
ConfigurationUtils.setExpectedShutdownTime(System.currentTimeMillis() + timeout);
// send readonly for shutdown hook
List<GracefulShutdown> gracefulShutdowns =
GracefulShutdown.getGracefulShutdowns(applicationModel.getFrameworkModel());
for (GracefulShutdown gracefulShutdown : gracefulShutdowns) {
gracefulShutdown.readonly();
}
boolean hasModuleBindSpring = false;
// check if any modules are bound to Spring
for (ModuleModel module : applicationModel.getModuleModels()) {
if (module.isLifeCycleManagedExternally()) {
hasModuleBindSpring = true;
break;
}
}
if (hasModuleBindSpring) {
if (timeout > 0) {
long start = System.currentTimeMillis();
/*
To avoid shutdown conflicts between Dubbo and Spring,
wait for the modules bound to Spring to be handled by Spring until timeout.
*/
logger.info(
"Waiting for modules(" + applicationModel.getDesc() + ") managed by Spring to be shutdown.");
while (!applicationModel.isDestroyed()
&& hasModuleBindSpring
&& (System.currentTimeMillis() - start) < timeout) {
try {
TimeUnit.MILLISECONDS.sleep(10);
hasModuleBindSpring = false;
if (!applicationModel.isDestroyed()) {
for (ModuleModel module : applicationModel.getModuleModels()) {
if (module.isLifeCycleManagedExternally()) {
hasModuleBindSpring = true;
break;
}
}
}
} catch (InterruptedException e) {
logger.warn(LoggerCodeConstants.INTERNAL_INTERRUPTED, "", "", e.getMessage(), e);
Thread.currentThread().interrupt();
}
}
if (!applicationModel.isDestroyed()) {
long usage = System.currentTimeMillis() - start;
logger.info("Dubbo wait for application(" + applicationModel.getDesc()
+ ") managed by Spring to be shutdown failed, " + "time usage: " + usage + "ms");
}
}
}
if (!applicationModel.isDestroyed()) {
logger.info("Dubbo shutdown hooks execute now. " + applicationModel.getDesc());
applicationModel.destroy();
}
}
/**
* Register the ShutdownHook
*/
public void register() {
if (!ignoreListenShutdownHook && registered.compareAndSet(false, true)) {
try {
Runtime.getRuntime().addShutdownHook(this);
} catch (IllegalStateException e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "register shutdown hook failed: " + e.getMessage(), e);
} catch (Exception e) {
logger.warn(CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "register shutdown hook failed: " + e.getMessage(), e);
}
}
}
/**
* Unregister the ShutdownHook
*/
public void unregister() {
if (!ignoreListenShutdownHook && registered.compareAndSet(true, false)) {
if (this.isAlive()) {
// DubboShutdownHook thread is running
return;
}
try {
Runtime.getRuntime().removeShutdownHook(this);
} catch (IllegalStateException e) {
logger.warn(
CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e);
} catch (Exception e) {
logger.warn(
CONFIG_FAILED_SHUTDOWN_HOOK, "", "", "unregister shutdown hook failed: " + e.getMessage(), e);
}
}
}
public boolean getRegistered() {
return registered.get();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ConfigInitializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* Dynamically add some parameters / check config
*/
@SPI(scope = ExtensionScope.MODULE)
public interface ConfigInitializer {
default void initReferConfig(ReferenceConfig referenceConfig) {}
default void initServiceConfig(ServiceConfig serviceConfig) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.support.ClusterUtils;
import org.apache.dubbo.rpc.cluster.support.registry.ZoneAwareCluster;
import org.apache.dubbo.rpc.model.AsyncMethodInfo;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.DubboStub;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.protocol.injvm.InjvmProtocol;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.stub.StubSuppliers;
import org.apache.dubbo.rpc.support.ProtocolUtils;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_DOMAIN;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_CLUSTER_DOMAIN;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_MESH_PORT;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_IP_TO_REGISTRY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.MESH_ENABLE;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.POD_NAMESPACE;
import static org.apache.dubbo.common.constants.CommonConstants.PROXY_CLASS_REF;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SVC;
import static org.apache.dubbo.common.constants.CommonConstants.TRIPLE;
import static org.apache.dubbo.common.constants.CommonConstants.UNLOAD_CLUSTER_RELATED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CLUSTER_NO_VALID_PROVIDER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_DESTROY_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_LOAD_ENV_VARIABLE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_METHOD_FOUND;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PROPERTY_CONFLICT;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDED_BY;
import static org.apache.dubbo.common.constants.RegistryConstants.SUBSCRIBED_SERVICE_NAMES_KEY;
import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost;
import static org.apache.dubbo.common.utils.StringUtils.splitToSet;
import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
/**
* Please avoid using this class for any new application,
* use {@link ReferenceConfigBase} instead.
*/
public class ReferenceConfig<T> extends ReferenceConfigBase<T> {
public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ReferenceConfig.class);
/**
* The {@link Protocol} implementation with adaptive functionality,it will be different in different scenarios.
* A particular {@link Protocol} implementation is determined by the protocol attribute in the {@link URL}.
* For example:
*
* <li>when the url is registry://224.5.6.7:1234/org.apache.dubbo.registry.RegistryService?application=dubbo-sample,
* then the protocol is <b>RegistryProtocol</b></li>
*
* <li>when the url is dubbo://224.5.6.7:1234/org.apache.dubbo.config.api.DemoService?application=dubbo-sample, then
* the protocol is <b>DubboProtocol</b></li>
* <p>
* Actually,when the {@link ExtensionLoader} init the {@link Protocol} instants,it will automatically wrap three
* layers, and eventually will get a <b>ProtocolSerializationWrapper</b> or <b>ProtocolFilterWrapper</b> or <b>ProtocolListenerWrapper</b>
*/
private Protocol protocolSPI;
/**
* A {@link ProxyFactory} implementation that will generate a reference service's proxy,the JavassistProxyFactory is
* its default implementation
*/
private ProxyFactory proxyFactory;
private ConsumerModel consumerModel;
/**
* The interface proxy reference
*/
private transient volatile T ref;
/**
* The invoker of the reference service
*/
private transient volatile Invoker<?> invoker;
/**
* The flag whether the ReferenceConfig has been initialized
*/
private transient volatile boolean initialized;
/**
* whether this ReferenceConfig has been destroyed
*/
private transient volatile boolean destroyed;
/**
* The service names that the Dubbo interface subscribed.
*
* @since 2.7.8
*/
private String services;
protected final transient ReentrantLock lock = new ReentrantLock();
public ReferenceConfig() {
super();
}
public ReferenceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
public ReferenceConfig(Reference reference) {
super(reference);
}
public ReferenceConfig(ModuleModel moduleModel, Reference reference) {
super(moduleModel, reference);
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
protocolSPI = this.getExtensionLoader(Protocol.class).getAdaptiveExtension();
proxyFactory = this.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
}
/**
* Get a string presenting the service names that the Dubbo interface subscribed.
* If it is a multiple-values, the content will be a comma-delimited String.
*
* @return non-null
* @see RegistryConstants#SUBSCRIBED_SERVICE_NAMES_KEY
* @since 2.7.8
*/
@Deprecated
@Parameter(key = SUBSCRIBED_SERVICE_NAMES_KEY)
public String getServices() {
return services;
}
/**
* It's an alias method for {@link #getServices()}, but the more convenient.
*
* @return the String {@link List} presenting the Dubbo interface subscribed
* @since 2.7.8
*/
@Deprecated
@Parameter(excluded = true)
public Set<String> getSubscribedServices() {
return splitToSet(getServices(), COMMA_SEPARATOR_CHAR);
}
/**
* Set the service names that the Dubbo interface subscribed.
*
* @param services If it is a multiple-values, the content will be a comma-delimited String.
* @since 2.7.8
*/
public void setServices(String services) {
this.services = services;
}
@Override
@Transient
public T get(boolean check) {
if (destroyed) {
throw new IllegalStateException("The invoker of ReferenceConfig(" + url + ") has already destroyed!");
}
if (ref == null) {
if (getScopeModel().isLifeCycleManagedExternally()) {
// prepare model for reference
getScopeModel().getDeployer().prepare();
} else {
// ensure start module, compatible with old api usage
getScopeModel().getDeployer().start();
}
init(check);
}
return ref;
}
@Override
public void checkOrDestroy(long timeout) {
if (!initialized || ref == null) {
return;
}
try {
checkInvokerAvailable(timeout);
} catch (Throwable t) {
logAndCleanup(t);
throw t;
}
}
private void logAndCleanup(Throwable t) {
try {
if (invoker != null) {
invoker.destroy();
}
} catch (Throwable destroy) {
logger.warn(
CONFIG_FAILED_DESTROY_INVOKER,
"",
"",
"Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").",
t);
}
if (consumerModel != null) {
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
repository.unregisterConsumer(consumerModel);
}
initialized = false;
invoker = null;
ref = null;
consumerModel = null;
serviceMetadata.setTarget(null);
serviceMetadata.getAttributeMap().remove(PROXY_CLASS_REF);
// Thrown by checkInvokerAvailable().
if (t.getClass() == IllegalStateException.class
&& t.getMessage().contains("No provider available for the service")) {
// 2-2 - No provider available.
logger.error(CLUSTER_NO_VALID_PROVIDER, "server crashed", "", "No provider available.", t);
}
}
@Override
public void destroy() {
lock.lock();
try {
super.destroy();
if (destroyed) {
return;
}
destroyed = true;
try {
if (invoker != null) {
invoker.destroy();
}
} catch (Throwable t) {
logger.warn(
CONFIG_FAILED_DESTROY_INVOKER,
"",
"",
"Unexpected error occurred when destroy invoker of ReferenceConfig(" + url + ").",
t);
}
invoker = null;
ref = null;
if (consumerModel != null) {
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
repository.unregisterConsumer(consumerModel);
}
} finally {
lock.unlock();
}
}
protected void init() {
init(true);
}
protected void init(boolean check) {
lock.lock();
try {
if (initialized && ref != null) {
return;
}
try {
if (!this.isRefreshed()) {
this.refresh();
}
// auto detect proxy type
String proxyType = getProxy();
if (StringUtils.isBlank(proxyType) && DubboStub.class.isAssignableFrom(interfaceClass)) {
setProxy(CommonConstants.NATIVE_STUB);
}
// init serviceMetadata
initServiceMetadata(consumer);
serviceMetadata.setServiceType(getServiceInterfaceClass());
// TODO, uncomment this line once service key is unified
serviceMetadata.generateServiceKey();
Map<String, String> referenceParameters = appendConfig();
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
ServiceDescriptor serviceDescriptor;
if (CommonConstants.NATIVE_STUB.equals(getProxy())) {
serviceDescriptor = StubSuppliers.getServiceDescriptor(interfaceName);
repository.registerService(serviceDescriptor);
setInterface(serviceDescriptor.getInterfaceName());
} else {
serviceDescriptor = repository.registerService(interfaceClass);
}
consumerModel = new ConsumerModel(
serviceMetadata.getServiceKey(),
proxy,
serviceDescriptor,
getScopeModel(),
serviceMetadata,
createAsyncMethodInfo(),
interfaceClassLoader);
// Compatible with dependencies on ServiceModel#getReferenceConfig() , and will be removed in a future
// version.
consumerModel.setConfig(this);
repository.registerConsumer(consumerModel);
serviceMetadata.getAttachments().putAll(referenceParameters);
ref = createProxy(referenceParameters);
serviceMetadata.setTarget(ref);
serviceMetadata.addAttribute(PROXY_CLASS_REF, ref);
consumerModel.setDestroyRunner(getDestroyRunner());
consumerModel.setProxyObject(ref);
consumerModel.initMethodModels();
if (check) {
checkInvokerAvailable(0);
}
} catch (Throwable t) {
logAndCleanup(t);
throw t;
}
initialized = true;
} finally {
lock.unlock();
}
}
/**
* convert and aggregate async method info
*
* @return Map<String, AsyncMethodInfo>
*/
private Map<String, AsyncMethodInfo> createAsyncMethodInfo() {
Map<String, AsyncMethodInfo> attributes = null;
if (CollectionUtils.isNotEmpty(getMethods())) {
attributes = new HashMap<>(16);
for (MethodConfig methodConfig : getMethods()) {
AsyncMethodInfo asyncMethodInfo = methodConfig.convertMethodConfig2AsyncInfo();
if (asyncMethodInfo != null) {
attributes.put(methodConfig.getName(), asyncMethodInfo);
}
}
}
return attributes;
}
/**
* Append all configuration required for service reference.
*
* @return reference parameters
*/
private Map<String, String> appendConfig() {
Map<String, String> map = new HashMap<>(16);
map.put(INTERFACE_KEY, interfaceName);
map.put(SIDE_KEY, CONSUMER_SIDE);
ReferenceConfigBase.appendRuntimeParameters(map);
if (!ProtocolUtils.isGeneric(generic)) {
String revision = Version.getVersion(interfaceClass, version);
if (StringUtils.isNotEmpty(revision)) {
map.put(REVISION_KEY, revision);
}
String[] methods = methods(interfaceClass);
if (methods.length == 0) {
logger.warn(
CONFIG_NO_METHOD_FOUND,
"",
"",
"No method found in service interface: " + interfaceClass.getName());
map.put(METHODS_KEY, ANY_VALUE);
} else {
map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR));
}
}
AbstractConfig.appendParameters(map, getApplication());
AbstractConfig.appendParameters(map, getModule());
AbstractConfig.appendParameters(map, consumer);
AbstractConfig.appendParameters(map, this);
String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
if (StringUtils.isEmpty(hostToRegistry)) {
hostToRegistry = NetUtils.getLocalHost();
} else if (isInvalidLocalHost(hostToRegistry)) {
throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY
+ ", value:" + hostToRegistry);
}
map.put(REGISTER_IP_KEY, hostToRegistry);
if (CollectionUtils.isNotEmpty(getMethods())) {
for (MethodConfig methodConfig : getMethods()) {
AbstractConfig.appendParameters(map, methodConfig, methodConfig.getName());
String retryKey = methodConfig.getName() + ".retry";
if (map.containsKey(retryKey)) {
String retryValue = map.remove(retryKey);
if ("false".equals(retryValue)) {
map.put(methodConfig.getName() + ".retries", "0");
}
}
}
}
return map;
}
@SuppressWarnings({"unchecked"})
private T createProxy(Map<String, String> referenceParameters) {
urls.clear();
meshModeHandleUrl(referenceParameters);
if (StringUtils.isNotEmpty(url)) {
// user specified URL, could be peer-to-peer address, or register center's address.
parseUrl(referenceParameters);
} else {
// if protocols not in jvm checkRegistry
aggregateUrlFromRegistry(referenceParameters);
}
createInvoker();
if (logger.isInfoEnabled()) {
logger.info("Referred dubbo service: [" + referenceParameters.get(INTERFACE_KEY) + "]."
+ (ProtocolUtils.isGeneric(referenceParameters.get(GENERIC_KEY))
? " it's GenericService reference"
: " it's not GenericService reference"));
}
URL consumerUrl = new ServiceConfigURL(
CONSUMER_PROTOCOL,
referenceParameters.get(REGISTER_IP_KEY),
0,
referenceParameters.get(INTERFACE_KEY),
referenceParameters);
consumerUrl = consumerUrl.setScopeModel(getScopeModel());
consumerUrl = consumerUrl.setServiceModel(consumerModel);
MetadataUtils.publishServiceDefinition(consumerUrl, consumerModel.getServiceModel(), getApplicationModel());
// create service proxy
return (T) proxyFactory.getProxy(invoker, ProtocolUtils.isGeneric(generic));
}
/**
* if enable mesh mode, handle url.
*
* @param referenceParameters referenceParameters
*/
private void meshModeHandleUrl(Map<String, String> referenceParameters) {
if (!checkMeshConfig(referenceParameters)) {
return;
}
if (StringUtils.isNotEmpty(url)) {
// user specified URL, could be peer-to-peer address, or register center's address.
if (logger.isInfoEnabled()) {
logger.info("The url already exists, mesh no longer processes url: " + url);
}
return;
}
// get provider namespace if (@DubboReference, <reference provider-namespace="xx"/>) present
String podNamespace = referenceParameters.get(RegistryConstants.PROVIDER_NAMESPACE);
// get pod namespace from env if annotation not present the provider namespace
if (StringUtils.isEmpty(podNamespace)) {
if (StringUtils.isEmpty(System.getenv(POD_NAMESPACE))) {
if (logger.isWarnEnabled()) {
logger.warn(
CONFIG_FAILED_LOAD_ENV_VARIABLE,
"",
"",
"Can not get env variable: POD_NAMESPACE, it may not be running in the K8S environment , "
+ "finally use 'default' replace.");
}
podNamespace = "default";
} else {
podNamespace = System.getenv(POD_NAMESPACE);
}
}
// In mesh mode, providedBy equals K8S Service name.
String providedBy = referenceParameters.get(PROVIDED_BY);
// cluster_domain default is 'cluster.local',generally unchanged.
String clusterDomain =
Optional.ofNullable(System.getenv(CLUSTER_DOMAIN)).orElse(DEFAULT_CLUSTER_DOMAIN);
// By VirtualService and DestinationRule, envoy will generate a new route rule,such as
// 'demo.default.svc.cluster.local:80',the default port is 80.
Integer meshPort = Optional.ofNullable(getProviderPort()).orElse(DEFAULT_MESH_PORT);
// DubboReference default is -1, process it.
meshPort = meshPort > -1 ? meshPort : DEFAULT_MESH_PORT;
// get mesh url.
url = TRIPLE + "://" + providedBy + "." + podNamespace + SVC + clusterDomain + ":" + meshPort;
}
/**
* check if mesh config is correct
*
* @param referenceParameters referenceParameters
* @return mesh config is correct
*/
private boolean checkMeshConfig(Map<String, String> referenceParameters) {
if (!"true".equals(referenceParameters.getOrDefault(MESH_ENABLE, "false"))) {
// In mesh mode, unloadClusterRelated can only be false.
referenceParameters.put(UNLOAD_CLUSTER_RELATED, "false");
return false;
}
getScopeModel()
.getConfigManager()
.getProtocol(TRIPLE)
.orElseThrow(() -> new IllegalStateException("In mesh mode, a triple protocol must be specified"));
String providedBy = referenceParameters.get(PROVIDED_BY);
if (StringUtils.isEmpty(providedBy)) {
throw new IllegalStateException("In mesh mode, the providedBy of ReferenceConfig is must be set");
}
return true;
}
/**
* Parse the directly configured url.
*/
private void parseUrl(Map<String, String> referenceParameters) {
String[] us = SEMICOLON_SPLIT_PATTERN.split(url);
if (ArrayUtils.isNotEmpty(us)) {
for (String u : us) {
URL url = URL.valueOf(u);
if (StringUtils.isEmpty(url.getPath())) {
url = url.setPath(interfaceName);
}
url = url.setScopeModel(getScopeModel());
url = url.setServiceModel(consumerModel);
if (UrlUtils.isRegistry(url)) {
urls.add(url.putAttribute(REFER_KEY, referenceParameters));
} else {
URL peerUrl = getScopeModel()
.getApplicationModel()
.getBeanFactory()
.getBean(ClusterUtils.class)
.mergeUrl(url, referenceParameters);
peerUrl = peerUrl.putAttribute(PEER_KEY, true);
urls.add(peerUrl);
}
}
}
}
/**
* Get URLs from the registry and aggregate them.
*/
private void aggregateUrlFromRegistry(Map<String, String> referenceParameters) {
checkRegistry();
List<URL> us = ConfigValidationUtils.loadRegistries(this, false);
if (CollectionUtils.isNotEmpty(us)) {
for (URL u : us) {
URL monitorUrl = ConfigValidationUtils.loadMonitor(this, u);
if (monitorUrl != null) {
u = u.putAttribute(MONITOR_KEY, monitorUrl);
}
u = u.setScopeModel(getScopeModel());
u = u.setServiceModel(consumerModel);
if (isInjvm() != null && isInjvm()) {
u = u.addParameter(LOCAL_PROTOCOL, true);
}
urls.add(u.putAttribute(REFER_KEY, referenceParameters));
}
}
if (urls.isEmpty() && shouldJvmRefer(referenceParameters)) {
URL injvmUrl = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName())
.addParameters(referenceParameters);
injvmUrl = injvmUrl.setScopeModel(getScopeModel());
injvmUrl = injvmUrl.setServiceModel(consumerModel);
urls.add(injvmUrl.putAttribute(REFER_KEY, referenceParameters));
}
if (urls.isEmpty()) {
throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer "
+ NetUtils.getLocalHost() + " use dubbo version "
+ Version.getVersion()
+ ", please config <dubbo:registry address=\"...\" /> to your spring config.");
}
}
/**
* \create a reference invoker
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private void createInvoker() {
if (urls.size() == 1) {
URL curUrl = urls.get(0);
invoker = protocolSPI.refer(interfaceClass, curUrl);
// registry url, mesh-enable and unloadClusterRelated is true, not need Cluster.
if (!UrlUtils.isRegistry(curUrl) && !curUrl.getParameter(UNLOAD_CLUSTER_RELATED, false)) {
List<Invoker<?>> invokers = new ArrayList<>();
invokers.add(invoker);
invoker = Cluster.getCluster(getScopeModel(), Cluster.DEFAULT)
.join(new StaticDirectory(curUrl, invokers), true);
}
} else {
List<Invoker<?>> invokers = new ArrayList<>();
URL registryUrl = null;
for (URL url : urls) {
// For multi-registry scenarios, it is not checked whether each referInvoker is available.
// Because this invoker may become available later.
invokers.add(protocolSPI.refer(interfaceClass, url));
if (UrlUtils.isRegistry(url)) {
// use last registry url
registryUrl = url;
}
}
if (registryUrl != null) {
// registry url is available
// for multi-subscription scenario, use 'zone-aware' policy by default
String cluster = registryUrl.getParameter(CLUSTER_KEY, ZoneAwareCluster.NAME);
// The invoker wrap sequence would be: ZoneAwareClusterInvoker(StaticDirectory) ->
// FailoverClusterInvoker
// (RegistryDirectory, routing happens here) -> Invoker
invoker = Cluster.getCluster(registryUrl.getScopeModel(), cluster, false)
.join(new StaticDirectory(registryUrl, invokers), false);
} else {
// not a registry url, must be direct invoke.
if (CollectionUtils.isEmpty(invokers)) {
throw new IllegalArgumentException("invokers == null");
}
URL curUrl = invokers.get(0).getUrl();
String cluster = curUrl.getParameter(CLUSTER_KEY, Cluster.DEFAULT);
invoker =
Cluster.getCluster(getScopeModel(), cluster).join(new StaticDirectory(curUrl, invokers), true);
}
}
}
private void checkInvokerAvailable(long timeout) throws IllegalStateException {
if (!shouldCheck()) {
return;
}
boolean available = invoker.isAvailable();
if (available) {
return;
}
long startTime = System.currentTimeMillis();
long checkDeadline = startTime + timeout;
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
available = invoker.isAvailable();
} while (!available && checkDeadline > System.currentTimeMillis());
logger.warn(
LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS,
"",
"",
"Check reference of [" + getUniqueServiceName() + "] failed very beginning. " + "After "
+ (System.currentTimeMillis() - startTime) + "ms reties, finally "
+ (available ? "succeed" : "failed")
+ ".");
if (!available) {
// 2-2 - No provider available.
IllegalStateException illegalStateException =
new IllegalStateException("Failed to check the status of the service "
+ interfaceName
+ ". No provider available for the service "
+ (group == null ? "" : group + "/")
+ interfaceName + (version == null ? "" : ":" + version)
+ " from the url "
+ invoker.getUrl()
+ " to the consumer "
+ NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion());
logger.error(
CLUSTER_NO_VALID_PROVIDER,
"provider not started",
"",
"No provider available.",
illegalStateException);
throw illegalStateException;
}
}
/**
* This method should be called right after the creation of this class's instance, before any property in other config modules is used.
* Check each config modules are created properly and override their properties if necessary.
*/
protected void checkAndUpdateSubConfigs() {
if (StringUtils.isEmpty(interfaceName)) {
throw new IllegalStateException("<dubbo:reference interface=\"\" /> interface not allow null!");
}
// get consumer's global configuration
completeCompoundConfigs();
// init some null configuration.
List<ConfigInitializer> configInitializers = this.getExtensionLoader(ConfigInitializer.class)
.getActivateExtension(URL.valueOf("configInitializer://"), (String[]) null);
configInitializers.forEach(e -> e.initReferConfig(this));
if (getGeneric() == null && getConsumer() != null) {
setGeneric(getConsumer().getGeneric());
}
if (ProtocolUtils.isGeneric(generic)) {
if (interfaceClass != null && !interfaceClass.equals(GenericService.class)) {
logger.warn(
CONFIG_PROPERTY_CONFLICT,
"",
"",
String.format(
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegisterTypeEnum;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.invoker.DelegateProviderMetaDataInvoker;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.metadata.ServiceNameMapping;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.event.MetricsInitEvent;
import org.apache.dubbo.metrics.model.MethodMetric;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.ServerService;
import org.apache.dubbo.rpc.cluster.ConfiguratorFactory;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.service.GenericService;
import java.beans.Transient;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_IP_TO_BIND;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_IP_TO_REGISTRY;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION;
import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.EXT_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.IS_EXTRA;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_EXECUTOR;
import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_NAME_MAPPING_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_METHOD_FOUND;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_SERVER_DISCONNECTED;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNEXPORT_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_USE_RANDOM_PORT;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.utils.NetUtils.getAvailablePort;
import static org.apache.dubbo.common.utils.NetUtils.getLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.isInvalidLocalHost;
import static org.apache.dubbo.common.utils.NetUtils.isInvalidPort;
import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_BIND;
import static org.apache.dubbo.config.Constants.DUBBO_PORT_TO_REGISTRY;
import static org.apache.dubbo.config.Constants.SCOPE_NONE;
import static org.apache.dubbo.registry.Constants.REGISTER_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
import static org.apache.dubbo.remoting.Constants.IS_PU_SERVER_KEY;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
import static org.apache.dubbo.rpc.Constants.SCOPE_KEY;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY;
import static org.apache.dubbo.rpc.support.ProtocolUtils.isGeneric;
public class ServiceConfig<T> extends ServiceConfigBase<T> {
private static final long serialVersionUID = 7868244018230856253L;
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ServiceConfig.class);
/**
* A random port cache, the different protocols who have no port specified have different random port
*/
private static final Map<String, Integer> RANDOM_PORT_MAP = new HashMap<>();
private Protocol protocolSPI;
/**
* A {@link ProxyFactory} implementation that will generate a exported service proxy,the JavassistProxyFactory is its
* default implementation
*/
private ProxyFactory proxyFactory;
private ProviderModel providerModel;
/**
* Whether the provider has been exported
*/
private transient volatile boolean exported;
/**
* The flag whether a service has unexported ,if the method unexported is invoked, the value is true
*/
private transient volatile boolean unexported;
private transient volatile AtomicBoolean initialized = new AtomicBoolean(false);
/**
* The exported services
*/
private final ConcurrentHashMap<RegisterTypeEnum, List<Exporter<?>>> exporters = new ConcurrentHashMap<>();
private final List<ServiceListener> serviceListeners = new ArrayList<>();
/**
* Whether to expose methods in this service as MCP tools, default value is false
*/
private boolean mcpEnabled = false;
public ServiceConfig() {}
public ServiceConfig(ModuleModel moduleModel) {
super(moduleModel);
}
public ServiceConfig(Service service) {
super(service);
}
public ServiceConfig(ModuleModel moduleModel, Service service) {
super(moduleModel, service);
}
@Override
protected void postProcessAfterScopeModelChanged(ScopeModel oldScopeModel, ScopeModel newScopeModel) {
super.postProcessAfterScopeModelChanged(oldScopeModel, newScopeModel);
protocolSPI = this.getExtensionLoader(Protocol.class).getAdaptiveExtension();
proxyFactory = this.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isExported() {
return exported;
}
@Override
@Parameter(excluded = true, attribute = false)
public boolean isUnexported() {
return unexported;
}
@Parameter(attribute = false, key = "mcp.enabled")
public boolean isMcpEnabled() {
return mcpEnabled;
}
public void setMcpEnabled(boolean mcpEnabled) {
this.mcpEnabled = mcpEnabled;
}
@Override
public synchronized void unexport() {
if (!exported) {
return;
}
if (unexported) {
return;
}
if (!exporters.isEmpty()) {
for (List<Exporter<?>> es : exporters.values()) {
for (Exporter<?> exporter : es) {
try {
exporter.unregister();
} catch (Throwable t) {
logger.warn(
CONFIG_UNEXPORT_ERROR,
"",
"",
"Unexpected error occurred when unexport " + exporter,
t);
}
}
}
waitForIdle();
for (List<Exporter<?>> es : exporters.values()) {
for (Exporter<?> exporter : es) {
try {
exporter.unexport();
} catch (Throwable t) {
logger.warn(
CONFIG_UNEXPORT_ERROR,
"",
"",
"Unexpected error occurred when unexport " + exporter,
t);
}
}
}
exporters.clear();
}
unexported = true;
onUnExported();
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
repository.unregisterProvider(providerModel);
}
private void waitForIdle() {
int timeout = ConfigurationUtils.getServerShutdownTimeout(getScopeModel());
long idleTime = System.currentTimeMillis() - providerModel.getLastInvokeTime();
// 1. if service has idle for 10s(shutdown time), un-export directly
if (idleTime > timeout) {
return;
}
// 2. if service has idle for more than 6.7s(2/3 of shutdown time), wait for the rest time, then un-export
// directly
int tick = timeout / 3;
if (timeout - idleTime < tick) {
logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for "
+ (timeout - idleTime) + " ms to un-export");
try {
Thread.sleep(timeout - idleTime);
} catch (InterruptedException e) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", e.getMessage(), e);
Thread.currentThread().interrupt();
}
return;
}
// 3. Wait for 3.33s(1/3 of shutdown time), if service has idle for 3.33s(1/3 of shutdown time), un-export
// directly,
// otherwise wait for the rest time until idle for 3.33s(1/3 of shutdown time). The max wait time is
// 10s(shutdown time).
idleTime = 0;
long startTime = System.currentTimeMillis();
while (idleTime < tick) {
// service idle time.
idleTime = System.currentTimeMillis() - Math.max(providerModel.getLastInvokeTime(), startTime);
if (idleTime >= tick || System.currentTimeMillis() - startTime > timeout) {
return;
}
// idle rest time or timeout rest time
long waitTime = Math.min(tick - idleTime, timeout + startTime - System.currentTimeMillis());
logger.info("Service " + getUniqueServiceName() + " has idle for " + idleTime + " ms, wait for " + waitTime
+ " ms to un-export");
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", e.getMessage(), e);
Thread.currentThread().interrupt();
}
}
}
/**
* for early init serviceMetadata
*/
public void init() {
if (this.initialized.compareAndSet(false, true)) {
// load ServiceListeners from extension
ExtensionLoader<ServiceListener> extensionLoader = this.getExtensionLoader(ServiceListener.class);
this.serviceListeners.addAll(extensionLoader.getSupportedExtensionInstances());
}
initServiceMetadata(provider);
serviceMetadata.setServiceType(getInterfaceClass());
serviceMetadata.setTarget(getRef());
serviceMetadata.generateServiceKey();
}
@Override
public void export(RegisterTypeEnum registerType) {
if (this.exported) {
return;
}
if (getScopeModel().isLifeCycleManagedExternally()) {
// prepare model for reference
getScopeModel().getDeployer().prepare();
} else {
// ensure start module, compatible with old api usage
getScopeModel().getDeployer().start();
}
synchronized (this) {
if (this.exported) {
return;
}
if (!this.isRefreshed()) {
this.refresh();
}
if (this.shouldExport()) {
this.init();
if (shouldDelay()) {
// should register if delay export
doDelayExport();
} else if (Integer.valueOf(-1).equals(getDelay())
&& Boolean.parseBoolean(ConfigurationUtils.getProperty(
getScopeModel(), CommonConstants.DubboProperty.DUBBO_MANUAL_REGISTER_KEY, "false"))) {
// should not register by default
doExport(RegisterTypeEnum.MANUAL_REGISTER);
} else {
doExport(registerType);
}
}
}
getScopeModel().getDeployer().registerServiceInstance();
}
@Override
public void register(boolean byDeployer) {
if (!this.exported) {
return;
}
synchronized (this) {
if (!this.exported) {
return;
}
for (Exporter<?> exporter :
exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER, Collections.emptyList())) {
exporter.register();
}
if (byDeployer) {
for (Exporter<?> exporter :
exporters.getOrDefault(RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER, Collections.emptyList())) {
exporter.register();
}
}
}
}
protected void doDelayExport() {
ExecutorRepository.getInstance(getScopeModel().getApplicationModel())
.getServiceExportExecutor()
.schedule(
() -> {
try {
doExport(RegisterTypeEnum.AUTO_REGISTER);
} catch (Exception e) {
logger.error(
CONFIG_FAILED_EXPORT_SERVICE,
"configuration server disconnected",
"",
"Failed to (async)export service config: " + interfaceName,
e);
}
},
getDelay(),
TimeUnit.MILLISECONDS);
}
protected void exported() {
exported = true;
List<URL> exportedURLs = this.getExportedUrls();
exportedURLs.forEach(url -> {
if (url.getParameter(SERVICE_NAME_MAPPING_KEY, false)) {
ServiceNameMapping serviceNameMapping = ServiceNameMapping.getDefaultExtension(getScopeModel());
ScheduledExecutorService scheduledExecutor = getScopeModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor();
mapServiceName(url, serviceNameMapping, scheduledExecutor);
}
});
onExported();
if (hasRegistrySpecified()) {
getScopeModel().getDeployer().getApplicationDeployer().exportMetadataService();
}
}
public boolean hasRegistrySpecified() {
return CollectionUtils.isNotEmpty(this.getRegistries())
|| CollectionUtils.isNotEmpty(getScopeModel()
.getApplicationModel()
.getApplicationConfigManager()
.getRegistries());
}
protected void mapServiceName(
URL url, ServiceNameMapping serviceNameMapping, ScheduledExecutorService scheduledExecutor) {
if (!exported) {
return;
}
logger.info("[INSTANCE_REGISTER] [METADATA_REGISTER] Try to register interface application mapping for service "
+ url.getServiceKey());
boolean succeeded = false;
try {
succeeded = serviceNameMapping.map(url);
if (succeeded) {
logger.info(
"[INSTANCE_REGISTER][METADATA_REGISTER] Successfully registered interface application mapping for service "
+ url.getServiceKey());
} else {
logger.error(
CONFIG_SERVER_DISCONNECTED,
"configuration server disconnected",
"",
"[INSTANCE_REGISTER] [METADATA_REGISTER] Failed register interface application mapping for service "
+ url.getServiceKey());
}
} catch (Exception e) {
logger.error(
CONFIG_SERVER_DISCONNECTED,
"configuration server disconnected",
"",
"[INSTANCE_REGISTER] [METADATA_REGISTER] Failed register interface application mapping for service "
+ url.getServiceKey(),
e);
}
if (!succeeded && serviceNameMapping.hasValidMetadataCenter()) {
scheduleToMapping(scheduledExecutor, serviceNameMapping, url);
}
}
private void scheduleToMapping(
ScheduledExecutorService scheduledExecutor, ServiceNameMapping serviceNameMapping, URL url) {
Integer mappingRetryInterval = getApplication().getMappingRetryInterval();
scheduledExecutor.schedule(
() -> mapServiceName(url, serviceNameMapping, scheduledExecutor),
mappingRetryInterval == null ? 5000 : mappingRetryInterval,
TimeUnit.MILLISECONDS);
}
private void checkAndUpdateSubConfigs() {
// Use default configs defined explicitly with global scope
completeCompoundConfigs();
checkProtocol();
// init some null configuration.
List<ConfigInitializer> configInitializers = this.getExtensionLoader(ConfigInitializer.class)
.getActivateExtension(URL.valueOf("configInitializer://", getScopeModel()), (String[]) null);
configInitializers.forEach(e -> e.initServiceConfig(this));
// if protocol is not injvm checkRegistry
if (!isOnlyInJvm()) {
checkRegistry();
}
if (StringUtils.isEmpty(interfaceName)) {
throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");
}
if (ref instanceof GenericService) {
interfaceClass = GenericService.class;
if (StringUtils.isEmpty(generic)) {
generic = Boolean.TRUE.toString();
}
} else {
try {
if (getInterfaceClassLoader() != null) {
interfaceClass = Class.forName(interfaceName, true, getInterfaceClassLoader());
} else {
interfaceClass = Class.forName(
interfaceName, true, Thread.currentThread().getContextClassLoader());
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
checkRef();
generic = Boolean.FALSE.toString();
}
if (local != null) {
if ("true".equals(local)) {
local = interfaceName + "Local";
}
Class<?> localClass;
try {
localClass = ClassUtils.forNameWithThreadContextClassLoader(local);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if (!interfaceClass.isAssignableFrom(localClass)) {
throw new IllegalStateException("The local implementation class " + localClass.getName()
+ " not implement interface " + interfaceName);
}
}
if (stub != null) {
if ("true".equals(stub)) {
stub = interfaceName + "Stub";
}
Class<?> stubClass;
try {
stubClass = ClassUtils.forNameWithThreadContextClassLoader(stub);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e.getMessage(), e);
}
if (!interfaceClass.isAssignableFrom(stubClass)) {
throw new IllegalStateException("The stub implementation class " + stubClass.getName()
+ " not implement interface " + interfaceName);
}
}
checkStubAndLocal(interfaceClass);
ConfigValidationUtils.validateServiceConfig(this);
postProcessConfig();
}
@Override
protected void postProcessRefresh() {
super.postProcessRefresh();
checkAndUpdateSubConfigs();
}
protected synchronized void doExport(RegisterTypeEnum registerType) {
if (unexported) {
throw new IllegalStateException("The service " + interfaceClass.getName() + " has already unexported!");
}
if (exported) {
return;
}
if (StringUtils.isEmpty(path)) {
path = interfaceName;
}
doExportUrls(registerType);
exported();
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void doExportUrls(RegisterTypeEnum registerType) {
ModuleServiceRepository repository = getScopeModel().getServiceRepository();
ServiceDescriptor serviceDescriptor;
final boolean serverService = ref instanceof ServerService;
if (serverService) {
serviceDescriptor = ((ServerService) ref).getServiceDescriptor();
if (!this.provider.getUseJavaPackageAsPath()) {
// for stub service, path always interface name or IDL package name
this.path = serviceDescriptor.getInterfaceName();
}
repository.registerService(serviceDescriptor);
} else {
serviceDescriptor = repository.registerService(getInterfaceClass());
}
providerModel = new ProviderModel(
serviceMetadata.getServiceKey(),
ref,
serviceDescriptor,
getScopeModel(),
serviceMetadata,
interfaceClassLoader);
// Compatible with dependencies on ServiceModel#getServiceConfig(), and will be removed in a future version
providerModel.setConfig(this);
providerModel.setDestroyRunner(getDestroyRunner());
repository.registerProvider(providerModel);
List<URL> registryURLs = !Boolean.FALSE.equals(isRegister())
? ConfigValidationUtils.loadRegistries(this, true)
: Collections.emptyList();
for (ProtocolConfig protocolConfig : protocols) {
String pathKey = URL.buildKey(
getContextPath(protocolConfig).map(p -> p + "/" + path).orElse(path), group, version);
// stub service will use generated service name
if (!serverService) {
// In case user specified path, register service one more time to map it to path.
repository.registerService(pathKey, interfaceClass);
}
doExportUrlsFor1Protocol(protocolConfig, registryURLs, registerType);
}
providerModel.setServiceUrls(urls);
}
private void doExportUrlsFor1Protocol(
ProtocolConfig protocolConfig, List<URL> registryURLs, RegisterTypeEnum registerType) {
Map<String, String> map = buildAttributes(protocolConfig);
// remove null key and null value
map.keySet().removeIf(key -> StringUtils.isEmpty(key) || StringUtils.isEmpty(map.get(key)));
// init serviceMetadata attachments
serviceMetadata.getAttachments().putAll(map);
URL url = buildUrl(protocolConfig, map);
processServiceExecutor(url);
if (CollectionUtils.isEmpty(registryURLs)) {
registerType = RegisterTypeEnum.NEVER_REGISTER;
}
exportUrl(url, registryURLs, registerType);
initServiceMethodMetrics(url);
}
private void initServiceMethodMetrics(URL url) {
String[] methods = Optional.ofNullable(url.getParameter(METHODS_KEY))
.map(i -> i.split(","))
.orElse(new String[] {});
boolean serviceLevel = MethodMetric.isServiceLevel(application.getApplicationModel());
Arrays.stream(methods).forEach(method -> {
RpcInvocation invocation = new RpcInvocation(
url.getServiceKey(),
url.getServiceModel(),
method,
interfaceName,
url.getProtocolServiceKey(),
null,
null,
null,
null,
null,
null);
MetricsEventBus.publish(
MetricsInitEvent.toMetricsInitEvent(application.getApplicationModel(), invocation, serviceLevel));
});
}
private void processServiceExecutor(URL url) {
if (getExecutor() != null) {
String mode = application.getExecutorManagementMode();
if (!EXECUTOR_MANAGEMENT_MODE_ISOLATION.equals(mode)) {
logger.warn(
COMMON_ISOLATED_EXECUTOR_CONFIGURATION_ERROR,
"",
"",
"The current executor management mode is " + mode
+ ", the configured service executor cannot take effect unless the mode is configured as "
+ EXECUTOR_MANAGEMENT_MODE_ISOLATION);
return;
}
/**
* Because executor is not a string type, it cannot be attached to the url parameter, so it is added to URL#attributes
* and obtained it in IsolationExecutorRepository#createExecutor method
*/
providerModel.getServiceMetadata().addAttribute(SERVICE_EXECUTOR, getExecutor());
url.getAttributes().put(SERVICE_EXECUTOR, getExecutor());
}
}
private Map<String, String> buildAttributes(ProtocolConfig protocolConfig) {
Map<String, String> map = new HashMap<>();
map.put(SIDE_KEY, PROVIDER_SIDE);
// append params with basic configs,
ServiceConfig.appendRuntimeParameters(map);
AbstractConfig.appendParameters(map, getApplication());
AbstractConfig.appendParameters(map, getModule());
// remove 'default.' prefix for configs from ProviderConfig
// appendParameters(map, provider, Constants.DEFAULT_KEY);
AbstractConfig.appendParameters(map, provider);
AbstractConfig.appendParameters(map, protocolConfig);
AbstractConfig.appendParameters(map, this);
// append params with method configs,
if (CollectionUtils.isNotEmpty(getMethods())) {
getMethods().forEach(method -> appendParametersWithMethod(method, map));
}
if (isGeneric(generic)) {
map.put(GENERIC_KEY, generic);
map.put(METHODS_KEY, ANY_VALUE);
} else {
String revision = Version.getVersion(interfaceClass, version);
if (StringUtils.isNotEmpty(revision)) {
map.put(REVISION_KEY, revision);
}
String[] methods = methods(interfaceClass);
if (methods.length == 0) {
logger.warn(
CONFIG_NO_METHOD_FOUND,
"",
"",
"No method found in service interface: " + interfaceClass.getName());
map.put(METHODS_KEY, ANY_VALUE);
} else {
map.put(METHODS_KEY, StringUtils.join(new TreeSet<>(Arrays.asList(methods)), COMMA_SEPARATOR));
}
}
/**
* Here the token value configured by the provider is used to assign the value to ServiceConfig#token
*/
if (ConfigUtils.isEmpty(token) && provider != null) {
token = provider.getToken();
}
if (!ConfigUtils.isEmpty(token)) {
if (ConfigUtils.isDefault(token)) {
map.put(TOKEN_KEY, UUID.randomUUID().toString());
} else {
map.put(TOKEN_KEY, token);
}
}
if (ref instanceof ServerService) {
map.put(PROXY_KEY, CommonConstants.NATIVE_STUB);
}
return map;
}
private void appendParametersWithMethod(MethodConfig method, Map<String, String> params) {
AbstractConfig.appendParameters(params, method, method.getName());
String retryKey = method.getName() + ".retry";
if (params.containsKey(retryKey)) {
String retryValue = params.remove(retryKey);
if ("false".equals(retryValue)) {
params.put(method.getName() + ".retries", "0");
}
}
List<ArgumentConfig> arguments = method.getArguments();
if (CollectionUtils.isNotEmpty(arguments)) {
Method matchedMethod = findMatchedMethod(method);
if (matchedMethod != null) {
arguments.forEach(argument -> appendArgumentConfig(argument, matchedMethod, params));
}
}
}
private Method findMatchedMethod(MethodConfig methodConfig) {
for (Method method : interfaceClass.getMethods()) {
if (method.getName().equals(methodConfig.getName())) {
return method;
}
}
return null;
}
private void appendArgumentConfig(ArgumentConfig argument, Method method, Map<String, String> params) {
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/MetadataServiceURLParamsMetadataCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.MetadataServiceV2;
import org.apache.dubbo.metadata.util.MetadataServiceVersionUtils;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegationV2;
import org.apache.dubbo.registry.client.metadata.SpringCloudMetadataServiceURLBuilder;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_VERSION_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getMetadataServiceParameter;
/**
* Used to interact with non-dubbo systems, also see {@link SpringCloudMetadataServiceURLBuilder}
*/
public class MetadataServiceURLParamsMetadataCustomizer implements ServiceInstanceCustomizer {
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
Map<String, String> metadata = serviceInstance.getMetadata();
String propertyName = resolveMetadataPropertyName(serviceInstance);
String propertyValue = resolveMetadataPropertyValue(applicationModel);
if (!isBlank(propertyName) && !isBlank(propertyValue)) {
metadata.put(propertyName, propertyValue);
}
String version = resolveMetadataServiceVersion(applicationModel);
metadata.put(METADATA_SERVICE_VERSION_NAME, version);
}
public static String resolveMetadataServiceVersion(ApplicationModel applicationModel) {
boolean needExportV2 = MetadataServiceVersionUtils.needExportV2(applicationModel);
String version;
if (needExportV2) {
version = MetadataServiceDelegationV2.VERSION;
} else {
version = MetadataServiceDelegation.VERSION;
}
return version;
}
private String resolveMetadataPropertyName(ServiceInstance serviceInstance) {
return METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
}
private String resolveMetadataPropertyValue(ApplicationModel applicationModel) {
ModuleServiceRepository serviceRepository =
applicationModel.getInternalModule().getServiceRepository();
String key;
if (MetadataServiceVersionUtils.needExportV2(applicationModel)) {
key = BaseServiceMetadata.buildServiceKey(
MetadataServiceV2.class.getName(),
applicationModel.getApplicationName(),
MetadataServiceDelegationV2.VERSION);
} else {
// If MetadataService and MetadataServiceV2 are both exported, use v1 path for capacity.
// Client will use version and protocol to judge if it needs to refer v2 path.
key = BaseServiceMetadata.buildServiceKey(
MetadataService.class.getName(), applicationModel.getApplicationName(), MetadataService.VERSION);
}
ProviderModel providerModel = serviceRepository.lookupExportedService(key);
String metadataValue = "";
if (providerModel != null) {
List<URL> metadataURLs = providerModel.getServiceUrls();
if (CollectionUtils.isNotEmpty(metadataURLs)) {
metadataValue = getMetadataServiceParameter(metadataURLs.get(0));
}
}
return metadataValue;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ConfigurableMetadataServiceExporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.builders.InternalServiceConfigBuilder;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.MetadataServiceV2;
import org.apache.dubbo.metadata.util.MetadataServiceVersionUtils;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegationV2;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TRIPLE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_METADATA_SERVICE_EXPORTED;
import static org.apache.dubbo.metadata.util.MetadataServiceVersionUtils.V1;
import static org.apache.dubbo.metadata.util.MetadataServiceVersionUtils.V2;
/**
* Export metadata service
*/
public class ConfigurableMetadataServiceExporter {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
@Deprecated
private final MetadataServiceDelegation metadataService;
private final MetadataServiceDelegationV2 metadataServiceV2;
@Deprecated
private volatile ServiceConfig<MetadataService> serviceConfig;
private volatile ServiceConfig<MetadataServiceV2> serviceConfigV2;
private final ApplicationModel applicationModel;
public ConfigurableMetadataServiceExporter(
ApplicationModel applicationModel,
MetadataServiceDelegation metadataService,
MetadataServiceDelegationV2 metadataServiceV2) {
this.applicationModel = applicationModel;
this.metadataService = metadataService;
this.metadataServiceV2 = metadataServiceV2;
}
public synchronized ConfigurableMetadataServiceExporter export() {
if (!isExported()) {
if (MetadataServiceVersionUtils.needExportV1(applicationModel)) {
exportV1();
}
if (MetadataServiceVersionUtils.needExportV2(applicationModel)) {
exportV2();
}
} else {
if (logger.isWarnEnabled()) {
logger.warn(
CONFIG_METADATA_SERVICE_EXPORTED,
"",
"",
"The MetadataService has been exported : " + getExportedUrls());
}
}
return this;
}
/**
* Get exported urls which include v1 and v2 if existed
* @return exported urls
*/
public List<URL> getExportedUrls() {
List<URL> urls = new ArrayList<>();
if (serviceConfig != null) {
urls.addAll(serviceConfig.getExportedUrls());
}
if (serviceConfigV2 != null) {
urls.addAll(serviceConfigV2.getExportedUrls());
}
return urls;
}
private static final String INTERNAL_METADATA_REGISTRY_ID = "internal-metadata-registry";
private void exportV1() {
ExecutorService internalServiceExecutor = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getInternalServiceExecutor();
this.serviceConfig = InternalServiceConfigBuilder.<MetadataService>newBuilder(applicationModel)
.interfaceClass(MetadataService.class)
.protocol(getApplicationConfig().getMetadataServiceProtocol(), METADATA_SERVICE_PROTOCOL_KEY)
.port(getApplicationConfig().getMetadataServicePort(), METADATA_SERVICE_PORT_KEY)
.registryId(INTERNAL_METADATA_REGISTRY_ID)
.executor(internalServiceExecutor)
.ref(metadataService)
.version(V1)
.build(configConsumer -> configConsumer.setMethods(generateMethodConfig()));
serviceConfig.export();
metadataService.setMetadataURL(serviceConfig.getExportedUrls().get(0));
if (logger.isInfoEnabled()) {
logger.info("[SERVICE_PUBLISH] [METADATA_REGISTER] The MetadataService exports urls : "
+ serviceConfig.getExportedUrls());
}
}
private void exportV2() {
ExecutorService internalServiceExecutor = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getInternalServiceExecutor();
this.serviceConfigV2 = InternalServiceConfigBuilder.<MetadataServiceV2>newBuilder(applicationModel)
.interfaceClass(MetadataServiceV2.class)
.protocol(TRIPLE, METADATA_SERVICE_PROTOCOL_KEY)
.port(getApplicationConfig().getMetadataServicePort(), METADATA_SERVICE_PORT_KEY)
.registryId(INTERNAL_METADATA_REGISTRY_ID)
.executor(internalServiceExecutor)
.ref(metadataServiceV2)
.version(V2)
.build();
serviceConfigV2.export();
metadataServiceV2.setMetadataUrl(serviceConfigV2.getExportedUrls().get(0));
if (logger.isInfoEnabled()) {
logger.info("[SERVICE_PUBLISH][METADATA_REGISTER] The MetadataServiceV2 exports urls : "
+ serviceConfigV2.getExportedUrls());
}
}
public ConfigurableMetadataServiceExporter unexport() {
if (isExported()) {
serviceConfig.unexport();
serviceConfigV2.unexport();
metadataService.setMetadataURL(null);
}
return this;
}
private boolean v1Exported() {
return serviceConfig != null && serviceConfig.isExported() && !serviceConfig.isUnexported();
}
private boolean v2Exported() {
return serviceConfigV2 != null && serviceConfigV2.isExported() && !serviceConfigV2.isUnexported();
}
public boolean isExported() {
return v1Exported() || v2Exported();
}
private ApplicationConfig getApplicationConfig() {
return applicationModel.getApplicationConfigManager().getApplication().get();
}
/**
* Generate Method Config for Service Discovery Metadata <p/>
* <p>
* Make {@link MetadataService} support argument callback,
* used to notify {@link org.apache.dubbo.registry.client.ServiceInstance}'s
* metadata change event
*
* @since 3.0
*/
private List<MethodConfig> generateMethodConfig() {
MethodConfig methodConfig = new MethodConfig();
methodConfig.setName("getAndListenInstanceMetadata");
ArgumentConfig argumentConfig = new ArgumentConfig();
argumentConfig.setIndex(1);
argumentConfig.setCallback(true);
methodConfig.setArguments(Collections.singletonList(argumentConfig));
return Collections.singletonList(methodConfig);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/metadata/ExporterDeployListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.metadata;
import org.apache.dubbo.common.deploy.ApplicationDeployListener;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation;
import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegationV2;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
public class ExporterDeployListener implements ApplicationDeployListener, Prioritized {
protected volatile ConfigurableMetadataServiceExporter metadataServiceExporter;
@Override
public void onInitialize(ApplicationModel scopeModel) {}
@Override
public void onStarting(ApplicationModel scopeModel) {}
@Override
public synchronized void onStarted(ApplicationModel applicationModel) {}
@Override
public void onCompletion(ApplicationModel scopeModel) {}
@Override
public synchronized void onStopping(ApplicationModel scopeModel) {}
private String getMetadataType(ApplicationModel applicationModel) {
String type = applicationModel
.getApplicationConfigManager()
.getApplicationOrElseThrow()
.getMetadataType();
if (StringUtils.isEmpty(type)) {
type = DEFAULT_METADATA_STORAGE_TYPE;
}
return type;
}
private String getRegisterMode(ApplicationModel applicationModel) {
String type = applicationModel
.getApplicationConfigManager()
.getApplicationOrElseThrow()
.getRegisterMode();
if (StringUtils.isEmpty(type)) {
type = DEFAULT_REGISTER_MODE;
}
return type;
}
public ConfigurableMetadataServiceExporter getMetadataServiceExporter() {
return metadataServiceExporter;
}
public void setMetadataServiceExporter(ConfigurableMetadataServiceExporter metadataServiceExporter) {
this.metadataServiceExporter = metadataServiceExporter;
}
@Override
public synchronized void onModuleStarted(ApplicationModel applicationModel) {
// start metadata service exporter
@Deprecated
MetadataServiceDelegation metadataService =
applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegation.class);
MetadataServiceDelegationV2 metadataServiceV2 =
applicationModel.getBeanFactory().getOrRegisterBean(MetadataServiceDelegationV2.class);
if (metadataServiceExporter == null) {
metadataServiceExporter =
new ConfigurableMetadataServiceExporter(applicationModel, metadataService, metadataServiceV2);
// fixme, let's disable local metadata service export at this moment
if (!REMOTE_METADATA_STORAGE_TYPE.equals(getMetadataType(applicationModel))
&& !INTERFACE_REGISTER_MODE.equals(getRegisterMode(applicationModel))) {
metadataServiceExporter.export();
}
}
}
@Override
public synchronized void onStopped(ApplicationModel scopeModel) {
if (metadataServiceExporter != null && metadataServiceExporter.isExported()) {
try {
metadataServiceExporter.unexport();
} catch (Exception ignored) {
// ignored
}
}
}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {}
@Override
public int getPriority() {
return MAX_PRIORITY;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.wrapper.CompositeDynamicConfiguration;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.deploy.AbstractDeployer;
import org.apache.dubbo.common.deploy.ApplicationDeployListener;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployListener;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.lang.ShutdownHookCallbacks;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.DubboShutdownHook;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.utils.CompositeReferenceCache;
import org.apache.dubbo.config.utils.ConfigValidationUtils;
import org.apache.dubbo.metadata.report.MetadataReportFactory;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.metrics.collector.DefaultMetricsCollector;
import org.apache.dubbo.metrics.config.event.ConfigCenterEvent;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.report.DefaultMetricsReporterFactory;
import org.apache.dubbo.metrics.report.MetricsReporter;
import org.apache.dubbo.metrics.report.MetricsReporterFactory;
import org.apache.dubbo.metrics.service.MetricsServiceExporter;
import org.apache.dubbo.metrics.utils.MetricsSupportUtil;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.tracing.DubboObservationRegistry;
import org.apache.dubbo.tracing.utils.ObservationSupportUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static org.apache.dubbo.common.config.ConfigurationUtils.parseProperties;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXECUTE_DESTROY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_INIT_CONFIG_CENTER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REFRESH_INSTANCE_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_REGISTER_INSTANCE_ERROR;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
import static org.apache.dubbo.config.Constants.DEFAULT_APP_NAME;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_METADATA_PUBLISH_DELAY;
import static org.apache.dubbo.metadata.MetadataConstants.METADATA_PUBLISH_DELAY_KEY;
import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
/**
* initialize and start application instance
*/
public class DefaultApplicationDeployer extends AbstractDeployer<ApplicationModel> implements ApplicationDeployer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DefaultApplicationDeployer.class);
private final ApplicationModel applicationModel;
private final ConfigManager configManager;
private final Environment environment;
private final ReferenceCache referenceCache;
private final FrameworkExecutorRepository frameworkExecutorRepository;
private final ExecutorRepository executorRepository;
private final AtomicBoolean hasPreparedApplicationInstance = new AtomicBoolean(false);
private volatile boolean hasPreparedInternalModule = false;
private ScheduledFuture<?> asyncMetadataFuture;
private volatile CompletableFuture<Boolean> startFuture;
private final DubboShutdownHook dubboShutdownHook;
private volatile MetricsServiceExporter metricsServiceExporter;
private final Object stateLock = new Object();
private final Object startLock = new Object();
private final Object destroyLock = new Object();
private final Object internalModuleLock = new Object();
public DefaultApplicationDeployer(ApplicationModel applicationModel) {
super(applicationModel);
this.applicationModel = applicationModel;
configManager = applicationModel.getApplicationConfigManager();
environment = applicationModel.modelEnvironment();
referenceCache = new CompositeReferenceCache(applicationModel);
frameworkExecutorRepository =
applicationModel.getFrameworkModel().getBeanFactory().getBean(FrameworkExecutorRepository.class);
executorRepository = ExecutorRepository.getInstance(applicationModel);
dubboShutdownHook = new DubboShutdownHook(applicationModel);
// load spi listener
Set<ApplicationDeployListener> deployListeners = applicationModel
.getExtensionLoader(ApplicationDeployListener.class)
.getSupportedExtensionInstances();
for (ApplicationDeployListener listener : deployListeners) {
this.addDeployListener(listener);
}
}
public static ApplicationDeployer get(ScopeModel moduleOrApplicationModel) {
ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(moduleOrApplicationModel);
ApplicationDeployer applicationDeployer = applicationModel.getDeployer();
if (applicationDeployer == null) {
applicationDeployer = applicationModel.getBeanFactory().getOrRegisterBean(DefaultApplicationDeployer.class);
}
return applicationDeployer;
}
@Override
public ApplicationModel getApplicationModel() {
return applicationModel;
}
private <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
return applicationModel.getExtensionLoader(type);
}
private void unRegisterShutdownHook() {
dubboShutdownHook.unregister();
}
/**
* Enable registration of instance for pure Consumer process by setting registerConsumer to 'true'
* by default is false.
*/
private boolean isRegisterConsumerInstance() {
Boolean registerConsumer = getApplicationOrElseThrow().getRegisterConsumer();
if (registerConsumer == null) {
return false;
}
return Boolean.TRUE.equals(registerConsumer);
}
@Override
public ReferenceCache getReferenceCache() {
return referenceCache;
}
/**
* Initialize
*/
@Override
public void initialize() {
if (initialized) {
return;
}
// Ensure that the initialization is completed when concurrent calls
synchronized (startLock) {
if (initialized) {
return;
}
onInitialize();
// register shutdown hook
registerShutdownHook();
startConfigCenter();
loadApplicationConfigs();
initModuleDeployers();
initMetricsReporter();
initMetricsService();
// @since 3.2.3
initObservationRegistry();
// @since 2.7.8
startMetadataCenter();
initialized = true;
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " has been initialized!");
}
}
}
private void registerShutdownHook() {
dubboShutdownHook.register();
}
private void initModuleDeployers() {
// make sure created default module
applicationModel.getDefaultModule();
// deployer initialize
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().initialize();
}
}
private void loadApplicationConfigs() {
configManager.loadConfigs();
}
private void startConfigCenter() {
// load application config
configManager.loadConfigsOfTypeFromProps(ApplicationConfig.class);
// try set model name
if (StringUtils.isBlank(applicationModel.getModelName())) {
applicationModel.setModelName(applicationModel.tryGetApplicationName());
}
// load config centers
configManager.loadConfigsOfTypeFromProps(ConfigCenterConfig.class);
useRegistryAsConfigCenterIfNecessary();
// check Config Center
Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters();
if (CollectionUtils.isEmpty(configCenters)) {
ConfigCenterConfig configCenterConfig = new ConfigCenterConfig();
configCenterConfig.setScopeModel(applicationModel);
configCenterConfig.refresh();
ConfigValidationUtils.validateConfigCenterConfig(configCenterConfig);
if (configCenterConfig.isValid()) {
configManager.addConfigCenter(configCenterConfig);
configCenters = configManager.getConfigCenters();
}
} else {
for (ConfigCenterConfig configCenterConfig : configCenters) {
configCenterConfig.refresh();
ConfigValidationUtils.validateConfigCenterConfig(configCenterConfig);
}
}
if (CollectionUtils.isNotEmpty(configCenters)) {
CompositeDynamicConfiguration compositeDynamicConfiguration = new CompositeDynamicConfiguration();
for (ConfigCenterConfig configCenter : configCenters) {
// Pass config from ConfigCenterBean to environment
environment.updateExternalConfigMap(configCenter.getExternalConfiguration());
environment.updateAppExternalConfigMap(configCenter.getAppExternalConfiguration());
// Fetch config from remote config center
compositeDynamicConfiguration.addConfiguration(prepareEnvironment(configCenter));
}
environment.setDynamicConfiguration(compositeDynamicConfiguration);
}
}
private void startMetadataCenter() {
useRegistryAsMetadataCenterIfNecessary();
ApplicationConfig applicationConfig = getApplicationOrElseThrow();
String metadataType = applicationConfig.getMetadataType();
// FIXME, multiple metadata config support.
Collection<MetadataReportConfig> metadataReportConfigs = configManager.getMetadataConfigs();
if (CollectionUtils.isEmpty(metadataReportConfigs)) {
if (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
throw new IllegalStateException(
"No MetadataConfig found, Metadata Center address is required when 'metadata=remote' is enabled.");
}
return;
}
MetadataReportInstance metadataReportInstance =
applicationModel.getBeanFactory().getBean(MetadataReportInstance.class);
List<MetadataReportConfig> validMetadataReportConfigs = new ArrayList<>(metadataReportConfigs.size());
for (MetadataReportConfig metadataReportConfig : metadataReportConfigs) {
if (ConfigValidationUtils.isValidMetadataConfig(metadataReportConfig)) {
ConfigValidationUtils.validateMetadataConfig(metadataReportConfig);
validMetadataReportConfigs.add(metadataReportConfig);
}
}
metadataReportInstance.init(validMetadataReportConfigs);
if (!metadataReportInstance.isInitialized()) {
throw new IllegalStateException(String.format(
"%s MetadataConfigs found, but none of them is valid.", metadataReportConfigs.size()));
}
}
/**
* For compatibility purpose, use registry as the default config center when
* there's no config center specified explicitly and
* useAsConfigCenter of registryConfig is null or true
*/
private void useRegistryAsConfigCenterIfNecessary() {
// we use the loading status of DynamicConfiguration to decide whether ConfigCenter has been initiated.
if (environment.getDynamicConfiguration().isPresent()) {
return;
}
if (CollectionUtils.isNotEmpty(configManager.getConfigCenters())) {
return;
}
// load registry
configManager.loadConfigsOfTypeFromProps(RegistryConfig.class);
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
if (!defaultRegistries.isEmpty()) {
defaultRegistries.stream()
.filter(this::isUsedRegistryAsConfigCenter)
.map(this::registryAsConfigCenter)
.forEach(configCenter -> {
if (configManager.getConfigCenter(configCenter.getId()).isPresent()) {
return;
}
configManager.addConfigCenter(configCenter);
logger.info("use registry as config-center: " + configCenter);
});
}
}
private void initMetricsService() {
this.metricsServiceExporter =
getExtensionLoader(MetricsServiceExporter.class).getDefaultExtension();
metricsServiceExporter.init();
}
private void initMetricsReporter() {
if (!MetricsSupportUtil.isSupportMetrics()) {
return;
}
DefaultMetricsCollector collector = applicationModel.getBeanFactory().getBean(DefaultMetricsCollector.class);
Optional<MetricsConfig> configOptional = configManager.getMetrics();
// If no specific metrics type is configured and there is no Prometheus dependency in the dependencies.
MetricsConfig metricsConfig = configOptional.orElse(new MetricsConfig(applicationModel));
if (PROTOCOL_PROMETHEUS.equals(metricsConfig.getProtocol()) && !MetricsSupportUtil.isSupportPrometheus()) {
return;
}
if (StringUtils.isBlank(metricsConfig.getProtocol())) {
metricsConfig.setProtocol(
MetricsSupportUtil.isSupportPrometheus() ? PROTOCOL_PROMETHEUS : PROTOCOL_DEFAULT);
}
collector.setCollectEnabled(true);
collector.collectApplication();
collector.setThreadpoolCollectEnabled(
Optional.ofNullable(metricsConfig.getEnableThreadpool()).orElse(true));
collector.setMetricsInitEnabled(
Optional.ofNullable(metricsConfig.getEnableMetricsInit()).orElse(true));
MetricsReporterFactory metricsReporterFactory =
getExtensionLoader(MetricsReporterFactory.class).getAdaptiveExtension();
MetricsReporter metricsReporter = null;
try {
metricsReporter = metricsReporterFactory.createMetricsReporter(metricsConfig.toUrl());
} catch (IllegalStateException e) {
if (e.getMessage().startsWith("No such extension org.apache.dubbo.metrics.report.MetricsReporterFactory")) {
logger.warn(COMMON_METRICS_COLLECTOR_EXCEPTION, "", "", e.getMessage());
return;
} else {
throw e;
}
}
metricsReporter.init();
applicationModel.getBeanFactory().registerBean(metricsReporter);
// If the protocol is not the default protocol, the default protocol is also initialized.
if (!PROTOCOL_DEFAULT.equals(metricsConfig.getProtocol())) {
DefaultMetricsReporterFactory defaultMetricsReporterFactory =
new DefaultMetricsReporterFactory(applicationModel);
MetricsReporter defaultMetricsReporter =
defaultMetricsReporterFactory.createMetricsReporter(metricsConfig.toUrl());
defaultMetricsReporter.init();
applicationModel.getBeanFactory().registerBean(defaultMetricsReporter);
}
}
/**
* init ObservationRegistry(Micrometer)
*/
private void initObservationRegistry() {
if (!ObservationSupportUtil.isSupportObservation()) {
if (logger.isDebugEnabled()) {
logger.debug(
"Not found micrometer-observation or plz check the version of micrometer-observation version if already introduced, need > 1.10.0");
}
return;
}
if (!ObservationSupportUtil.isSupportTracing()) {
if (logger.isDebugEnabled()) {
logger.debug("Not found micrometer-tracing dependency, skip init ObservationRegistry.");
}
return;
}
Optional<TracingConfig> configOptional = configManager.getTracing();
if (!configOptional.isPresent() || !configOptional.get().getEnabled()) {
return;
}
DubboObservationRegistry dubboObservationRegistry =
new DubboObservationRegistry(applicationModel, configOptional.get());
dubboObservationRegistry.initObservationRegistry();
}
private boolean isUsedRegistryAsConfigCenter(RegistryConfig registryConfig) {
return isUsedRegistryAsCenter(
registryConfig, registryConfig::getUseAsConfigCenter, "config", DynamicConfigurationFactory.class);
}
private ConfigCenterConfig registryAsConfigCenter(RegistryConfig registryConfig) {
String protocol = registryConfig.getProtocol();
Integer port = registryConfig.getPort();
URL url = URL.valueOf(registryConfig.getAddress(), registryConfig.getScopeModel());
String id = "config-center-" + protocol + "-" + url.getHost() + "-" + port;
ConfigCenterConfig cc = new ConfigCenterConfig();
cc.setId(id);
cc.setScopeModel(applicationModel);
if (cc.getParameters() == null) {
cc.setParameters(new HashMap<>());
}
if (CollectionUtils.isNotEmptyMap(registryConfig.getParameters())) {
cc.getParameters().putAll(registryConfig.getParameters()); // copy the parameters
}
cc.getParameters().put(CLIENT_KEY, registryConfig.getClient());
cc.setProtocol(protocol);
cc.setPort(port);
if (StringUtils.isNotEmpty(registryConfig.getGroup())) {
cc.setGroup(registryConfig.getGroup());
}
cc.setAddress(getRegistryCompatibleAddress(registryConfig));
cc.setNamespace(registryConfig.getGroup());
cc.setUsername(registryConfig.getUsername());
cc.setPassword(registryConfig.getPassword());
if (registryConfig.getTimeout() != null) {
cc.setTimeout(registryConfig.getTimeout().longValue());
}
cc.setHighestPriority(false);
return cc;
}
private void useRegistryAsMetadataCenterIfNecessary() {
Collection<MetadataReportConfig> originMetadataConfigs = configManager.getMetadataConfigs();
if (originMetadataConfigs.stream().anyMatch(m -> Objects.nonNull(m.getAddress()))) {
return;
}
Collection<MetadataReportConfig> metadataConfigsToOverride = originMetadataConfigs.stream()
.filter(m -> Objects.isNull(m.getAddress()))
.collect(Collectors.toList());
if (metadataConfigsToOverride.size() > 1) {
return;
}
MetadataReportConfig metadataConfigToOverride =
metadataConfigsToOverride.stream().findFirst().orElse(null);
List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries();
if (!defaultRegistries.isEmpty()) {
defaultRegistries.stream()
.filter(this::isUsedRegistryAsMetadataCenter)
.map(registryConfig -> registryAsMetadataCenter(registryConfig, metadataConfigToOverride))
.forEach(metadataReportConfig ->
overrideMetadataReportConfig(metadataConfigToOverride, metadataReportConfig));
}
}
private void overrideMetadataReportConfig(
MetadataReportConfig metadataConfigToOverride, MetadataReportConfig metadataReportConfig) {
if (metadataReportConfig.getId() == null) {
Collection<MetadataReportConfig> metadataReportConfigs = configManager.getMetadataConfigs();
if (CollectionUtils.isNotEmpty(metadataReportConfigs)) {
for (MetadataReportConfig existedConfig : metadataReportConfigs) {
if (existedConfig.getId() == null
&& existedConfig.getAddress().equals(metadataReportConfig.getAddress())) {
return;
}
}
}
configManager.removeConfig(metadataConfigToOverride);
configManager.addMetadataReport(metadataReportConfig);
} else {
Optional<MetadataReportConfig> configOptional =
configManager.getConfig(MetadataReportConfig.class, metadataReportConfig.getId());
if (configOptional.isPresent()) {
return;
}
configManager.removeConfig(metadataConfigToOverride);
configManager.addMetadataReport(metadataReportConfig);
}
logger.info("use registry as metadata-center: " + metadataReportConfig);
}
private boolean isUsedRegistryAsMetadataCenter(RegistryConfig registryConfig) {
return isUsedRegistryAsCenter(
registryConfig, registryConfig::getUseAsMetadataCenter, "metadata", MetadataReportFactory.class);
}
/**
* Is used the specified registry as a center infrastructure
*
* @param registryConfig the {@link RegistryConfig}
* @param usedRegistryAsCenter the configured value on
* @param centerType the type name of center
* @param extensionClass an extension class of a center infrastructure
* @return
* @since 2.7.8
*/
private boolean isUsedRegistryAsCenter(
RegistryConfig registryConfig,
Supplier<Boolean> usedRegistryAsCenter,
String centerType,
Class<?> extensionClass) {
final boolean supported;
Boolean configuredValue = usedRegistryAsCenter.get();
if (configuredValue != null) { // If configured, take its value.
supported = configuredValue.booleanValue();
} else { // Or check the extension existence
String protocol = registryConfig.getProtocol();
supported = supportsExtension(extensionClass, protocol);
if (logger.isInfoEnabled()) {
logger.info(format(
"No value is configured in the registry, the %s extension[name : %s] %s as the %s center",
extensionClass.getSimpleName(),
protocol,
supported ? "supports" : "does not support",
centerType));
}
}
if (logger.isInfoEnabled()) {
logger.info(format(
"The registry[%s] will be %s as the %s center",
registryConfig, supported ? "used" : "not used", centerType));
}
return supported;
}
/**
* Supports the extension with the specified class and name
*
* @param extensionClass the {@link Class} of extension
* @param name the name of extension
* @return if supports, return <code>true</code>, or <code>false</code>
* @since 2.7.8
*/
private boolean supportsExtension(Class<?> extensionClass, String name) {
if (isNotEmpty(name)) {
ExtensionLoader<?> extensionLoader = getExtensionLoader(extensionClass);
return extensionLoader.hasExtension(name);
}
return false;
}
private MetadataReportConfig registryAsMetadataCenter(
RegistryConfig registryConfig, MetadataReportConfig originMetadataReportConfig) {
MetadataReportConfig metadataReportConfig = originMetadataReportConfig == null
? new MetadataReportConfig(registryConfig.getApplicationModel())
: originMetadataReportConfig;
if (metadataReportConfig.getId() == null) {
metadataReportConfig.setId(registryConfig.getId());
}
metadataReportConfig.setScopeModel(applicationModel);
if (metadataReportConfig.getParameters() == null) {
metadataReportConfig.setParameters(new HashMap<>());
}
if (CollectionUtils.isNotEmptyMap(registryConfig.getParameters())) {
for (Map.Entry<String, String> entry :
registryConfig.getParameters().entrySet()) {
metadataReportConfig
.getParameters()
.putIfAbsent(entry.getKey(), entry.getValue()); // copy the parameters
}
}
metadataReportConfig.getParameters().put(CLIENT_KEY, registryConfig.getClient());
if (metadataReportConfig.getGroup() == null) {
metadataReportConfig.setGroup(registryConfig.getGroup());
}
if (metadataReportConfig.getAddress() == null) {
metadataReportConfig.setAddress(getRegistryCompatibleAddress(registryConfig));
}
if (metadataReportConfig.getUsername() == null) {
metadataReportConfig.setUsername(registryConfig.getUsername());
}
if (metadataReportConfig.getPassword() == null) {
metadataReportConfig.setPassword(registryConfig.getPassword());
}
if (metadataReportConfig.getTimeout() == null) {
metadataReportConfig.setTimeout(registryConfig.getTimeout());
}
return metadataReportConfig;
}
private String getRegistryCompatibleAddress(RegistryConfig registryConfig) {
String registryAddress = registryConfig.getAddress();
String[] addresses = REGISTRY_SPLIT_PATTERN.split(registryAddress);
if (ArrayUtils.isEmpty(addresses)) {
throw new IllegalStateException("Invalid registry address found.");
}
String address = addresses[0];
// since 2.7.8
// Issue : https://github.com/apache/dubbo/issues/6476
StringBuilder metadataAddressBuilder = new StringBuilder();
URL url = URL.valueOf(address, registryConfig.getScopeModel());
String protocolFromAddress = url.getProtocol();
if (isEmpty(protocolFromAddress)) {
// If the protocol from address is missing, is like :
// "dubbo.registry.address = 127.0.0.1:2181"
String protocolFromConfig = registryConfig.getProtocol();
metadataAddressBuilder.append(protocolFromConfig).append("://");
}
metadataAddressBuilder.append(address);
return metadataAddressBuilder.toString();
}
/**
* Start the bootstrap
*
* @return
*/
@Override
public Future start() {
synchronized (startLock) {
if (isStopping() || isStopped() || isFailed()) {
throw new IllegalStateException(getIdentifier() + " is stopping or stopped, can not start again");
}
try {
// maybe call start again after add new module, check if any new module
boolean hasPendingModule = hasPendingModule();
if (isStarting()) {
// currently, is starting, maybe both start by module and application
// if it has new modules, start them
if (hasPendingModule) {
startModules();
}
// if it is starting, reuse previous startFuture
return startFuture;
}
// if is started and no new module, just return
if ((isStarted() || isCompletion()) && !hasPendingModule) {
return CompletableFuture.completedFuture(false);
}
// pending -> starting : first start app
// started -> starting : re-start app
onStarting();
initialize();
doStart();
} catch (Throwable e) {
onFailed(getIdentifier() + " start failure", e);
throw e;
}
return startFuture;
}
}
private boolean hasPendingModule() {
boolean found = false;
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.getDeployer().isPending()) {
found = true;
break;
}
}
return found;
}
@Override
public Future getStartFuture() {
return startFuture;
}
private void doStart() {
startModules();
// prepare application instance
// prepareApplicationInstance();
// Ignore checking new module after start
// executorRepository.getSharedExecutor().submit(() -> {
// try {
// while (isStarting()) {
// // notify when any module state changed
// synchronized (stateLock) {
// try {
// stateLock.wait(500);
// } catch (InterruptedException e) {
// // ignore
// }
// }
//
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/FrameworkModelCleaner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModelDestroyListener;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNDEFINED_PROTOCOL;
/**
* A cleaner to release resources of framework model
*/
public class FrameworkModelCleaner implements ScopeModelDestroyListener<FrameworkModel> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(FrameworkModelCleaner.class);
private final AtomicBoolean protocolDestroyed = new AtomicBoolean(false);
@Override
public boolean isProtocol() {
return true;
}
@Override
public void onDestroy(FrameworkModel frameworkModel) {
destroyFrameworkResources(frameworkModel);
}
/**
* Destroy all framework resources.
*/
private void destroyFrameworkResources(FrameworkModel frameworkModel) {
// destroy protocol in framework scope
destroyProtocols(frameworkModel);
}
/**
* Destroy all the protocols.
*/
private void destroyProtocols(FrameworkModel frameworkModel) {
if (protocolDestroyed.compareAndSet(false, true)) {
ExtensionLoader<Protocol> loader = frameworkModel.getExtensionLoader(Protocol.class);
for (String protocolName : loader.getLoadedExtensions()) {
try {
Protocol protocol = loader.getLoadedExtension(protocolName);
if (protocol != null) {
protocol.destroy();
}
} catch (Throwable t) {
logger.warn(CONFIG_UNDEFINED_PROTOCOL, "", "", t.getMessage(), t);
}
}
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultMetricsServiceExporter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.bootstrap.builders.InternalServiceConfigBuilder;
import org.apache.dubbo.metrics.service.MetricsService;
import org.apache.dubbo.metrics.service.MetricsServiceExporter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_DEFAULT;
import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS;
/**
* Export metrics service
*/
public class DefaultMetricsServiceExporter implements MetricsServiceExporter, ScopeModelAware {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private ApplicationModel applicationModel;
private MetricsService metricsService;
private volatile ServiceConfig<MetricsService> serviceConfig;
@Override
public void init() {
initialize();
}
private void initialize() {
MetricsConfig metricsConfig =
applicationModel.getApplicationConfigManager().getMetrics().orElse(null);
// TODO compatible with old usage of metrics, remove protocol check after new metrics is ready for use.
if (metricsConfig != null && metricsService == null) {
String protocol = Optional.ofNullable(metricsConfig.getProtocol()).orElse(PROTOCOL_PROMETHEUS);
if (PROTOCOL_DEFAULT.equals(protocol) || PROTOCOL_PROMETHEUS.equals(protocol)) {
this.metricsService = applicationModel
.getExtensionLoader(MetricsService.class)
.getDefaultExtension();
} else {
logger.warn(
COMMON_METRICS_COLLECTOR_EXCEPTION,
"",
"",
"Protocol " + protocol + " not support for new metrics mechanism. "
+ "Using old metrics mechanism instead.");
}
}
}
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public MetricsServiceExporter export() {
if (metricsService != null) {
if (!isExported()) {
ExecutorService internalServiceExecutor = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getInternalServiceExecutor();
ServiceConfig<MetricsService> serviceConfig = InternalServiceConfigBuilder.<MetricsService>newBuilder(
applicationModel)
.interfaceClass(MetricsService.class)
.protocol(getMetricsConfig().getExportServiceProtocol())
.port(getMetricsConfig().getExportServicePort())
.executor(internalServiceExecutor)
.ref(metricsService)
.registryId("internal-metrics-registry")
.build();
// export
serviceConfig.export();
if (logger.isInfoEnabled()) {
logger.info("The MetricsService exports urls : " + serviceConfig.getExportedUrls());
}
this.serviceConfig = serviceConfig;
} else {
if (logger.isWarnEnabled()) {
logger.warn(
LoggerCodeConstants.INTERNAL_ERROR,
"",
"",
"The MetricsService has been exported : " + serviceConfig.getExportedUrls());
}
}
} else {
if (logger.isInfoEnabled()) {
logger.info("The MetricsConfig not exist, will not export metrics service.");
}
}
return this;
}
@Override
public MetricsServiceExporter unexport() {
if (isExported()) {
serviceConfig.unexport();
}
return this;
}
private MetricsConfig getMetricsConfig() {
Optional<MetricsConfig> metricsConfig =
applicationModel.getApplicationConfigManager().getMetrics();
if (metricsConfig.isPresent()) {
return metricsConfig.get();
} else {
throw new IllegalStateException("There's no MetricsConfig specified.");
}
}
private boolean isExported() {
return serviceConfig != null && serviceConfig.isExported() && !serviceConfig.isUnexported();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/deploy/DefaultModuleDeployer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.deploy;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.constants.RegisterTypeEnum;
import org.apache.dubbo.common.deploy.AbstractDeployer;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployListener;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.common.deploy.ModuleDeployListener;
import org.apache.dubbo.common.deploy.ModuleDeployer;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.utils.SimpleReferenceCache;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_EXPORT_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_REFERENCE_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_REFER_SERVICE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_WAIT_EXPORT_REFER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_UNABLE_DESTROY_MODEL;
/**
* Export/refer services of module
*/
public class DefaultModuleDeployer extends AbstractDeployer<ModuleModel> implements ModuleDeployer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DefaultModuleDeployer.class);
private final List<CompletableFuture<?>> asyncExportingFutures = new ArrayList<>();
private final List<CompletableFuture<?>> asyncReferringFutures = new ArrayList<>();
private final List<ServiceConfigBase<?>> exportedServices = new ArrayList<>();
private final ModuleModel moduleModel;
private final FrameworkExecutorRepository frameworkExecutorRepository;
private final ExecutorRepository executorRepository;
private final ModuleConfigManager configManager;
private final SimpleReferenceCache referenceCache;
private final ApplicationDeployer applicationDeployer;
private CompletableFuture startFuture;
private Boolean background;
private Boolean exportAsync;
private Boolean referAsync;
private boolean registryInteracted;
private CompletableFuture<?> exportFuture;
private CompletableFuture<?> referFuture;
public DefaultModuleDeployer(ModuleModel moduleModel) {
super(moduleModel);
this.moduleModel = moduleModel;
configManager = moduleModel.getConfigManager();
frameworkExecutorRepository = moduleModel
.getApplicationModel()
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class);
executorRepository = ExecutorRepository.getInstance(moduleModel.getApplicationModel());
referenceCache = SimpleReferenceCache.newCache();
applicationDeployer = DefaultApplicationDeployer.get(moduleModel);
// load spi listener
Set<ModuleDeployListener> listeners =
moduleModel.getExtensionLoader(ModuleDeployListener.class).getSupportedExtensionInstances();
for (ModuleDeployListener listener : listeners) {
this.addDeployListener(listener);
}
}
@Override
public void initialize() throws IllegalStateException {
if (initialized) {
return;
}
// Ensure that the initialization is completed when concurrent calls
synchronized (this) {
if (initialized) {
return;
}
onInitialize();
loadConfigs();
// read ModuleConfig
ModuleConfig moduleConfig = moduleModel
.getConfigManager()
.getModule()
.orElseThrow(() -> new IllegalStateException("Default module config is not initialized"));
exportAsync = Boolean.TRUE.equals(moduleConfig.getExportAsync());
referAsync = Boolean.TRUE.equals(moduleConfig.getReferAsync());
// start in background
background = moduleConfig.getBackground();
if (background == null) {
// compatible with old usages
background = isExportBackground() || isReferBackground();
}
initialized = true;
if (logger.isInfoEnabled()) {
logger.info(getIdentifier() + " has been initialized!");
}
}
}
@Override
public Future start() throws IllegalStateException {
// initialize,maybe deadlock applicationDeployer lock & moduleDeployer lock
applicationDeployer.initialize();
return startSync();
}
private synchronized Future startSync() throws IllegalStateException {
if (isStopping() || isStopped() || isFailed()) {
throw new IllegalStateException(getIdentifier() + " is stopping or stopped, can not start again");
}
try {
if (isStarting() || isStarted() || isCompletion()) {
return startFuture;
}
onModuleStarting();
initialize();
// export services
exportServices();
// prepare application instance
// exclude internal module to avoid wait itself
if (moduleModel != moduleModel.getApplicationModel().getInternalModule()) {
applicationDeployer.prepareInternalModule();
}
// refer services
referServices();
// if no async export/refer services, just set started
if (asyncExportingFutures.isEmpty() && asyncReferringFutures.isEmpty()) {
// publish module started event
onModuleStarted();
// register services to registry
registerServices();
// check reference config
checkReferences();
// publish module completion event
onModuleCompletion();
// complete module start future after application state changed
completeStartFuture(true);
} else {
frameworkExecutorRepository.getSharedExecutor().submit(() -> {
try {
// wait for export finish
waitExportFinish();
// wait for refer finish
waitReferFinish();
// publish module started event
onModuleStarted();
// register services to registry
registerServices();
// check reference config
checkReferences();
// publish module completion event
onModuleCompletion();
} catch (Throwable e) {
logger.warn(
CONFIG_FAILED_WAIT_EXPORT_REFER,
"",
"",
"wait for export/refer services occurred an exception",
e);
onModuleFailed(getIdentifier() + " start failed: " + e, e);
} finally {
// complete module start future after application state changed
completeStartFuture(true);
}
});
}
} catch (Throwable e) {
onModuleFailed(getIdentifier() + " start failed: " + e, e);
throw e;
}
return startFuture;
}
@Override
public Future getStartFuture() {
return startFuture;
}
private boolean hasExportedServices() {
return !configManager.getServices().isEmpty();
}
@Override
public void stop() throws IllegalStateException {
moduleModel.destroy();
}
@Override
public void preDestroy() throws IllegalStateException {
if (isStopping() || isStopped()) {
return;
}
onModuleStopping();
offline();
}
private void offline() {
try {
ModuleServiceRepository serviceRepository = moduleModel.getServiceRepository();
List<ProviderModel> exportedServices = serviceRepository.getExportedServices();
for (ProviderModel exportedService : exportedServices) {
List<ProviderModel.RegisterStatedURL> statedUrls = exportedService.getStatedUrl();
for (ProviderModel.RegisterStatedURL statedURL : statedUrls) {
if (statedURL.isRegistered()) {
doOffline(statedURL);
}
}
}
} catch (Throwable t) {
logger.error(
LoggerCodeConstants.INTERNAL_ERROR, "", "", "Exceptions occurred when unregister services.", t);
}
}
private void doOffline(ProviderModel.RegisterStatedURL statedURL) {
RegistryFactory registryFactory = statedURL
.getRegistryUrl()
.getOrDefaultApplicationModel()
.getExtensionLoader(RegistryFactory.class)
.getAdaptiveExtension();
Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl());
registry.unregister(statedURL.getProviderUrl());
statedURL.setRegistered(false);
}
@Override
public synchronized void postDestroy() throws IllegalStateException {
if (isStopped()) {
return;
}
unexportServices();
unreferServices();
ModuleServiceRepository serviceRepository = moduleModel.getServiceRepository();
if (serviceRepository != null) {
List<ConsumerModel> consumerModels = serviceRepository.getReferredServices();
for (ConsumerModel consumerModel : consumerModels) {
try {
if (consumerModel.getDestroyRunner() != null) {
consumerModel.getDestroyRunner().run();
}
} catch (Throwable t) {
logger.error(
CONFIG_UNABLE_DESTROY_MODEL,
"there are problems with the custom implementation.",
"",
"Unable to destroy model: consumerModel.",
t);
}
}
List<ProviderModel> exportedServices = serviceRepository.getExportedServices();
for (ProviderModel providerModel : exportedServices) {
try {
if (providerModel.getDestroyRunner() != null) {
providerModel.getDestroyRunner().run();
}
} catch (Throwable t) {
logger.error(
CONFIG_UNABLE_DESTROY_MODEL,
"there are problems with the custom implementation.",
"",
"Unable to destroy model: providerModel.",
t);
}
}
serviceRepository.destroy();
}
onModuleStopped();
}
private void onInitialize() {
for (DeployListener<ModuleModel> listener : listeners) {
try {
listener.onInitialize(moduleModel);
} catch (Throwable e) {
logger.error(
CONFIG_FAILED_START_MODEL,
"",
"",
getIdentifier() + " an exception occurred when handle initialize event",
e);
}
}
}
private void onModuleStarting() {
setStarting();
startFuture = new CompletableFuture();
logger.info(getIdentifier() + " is starting.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STARTING);
}
private void onModuleStarted() {
if (isStarting()) {
setStarted();
logger.info(getIdentifier() + " has started.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STARTED);
}
}
private void onModuleCompletion() {
if (isStarted()) {
setCompletion();
logger.info(getIdentifier() + " has completed.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.COMPLETION);
}
}
private void onModuleFailed(String msg, Throwable ex) {
try {
try {
// un-export all services if start failure
unexportServices();
} catch (Throwable t) {
logger.info("Failed to un-export services after module failed.", t);
}
setFailed(ex);
logger.error(CONFIG_FAILED_START_MODEL, "", "", "Model start failed: " + msg, ex);
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.FAILED);
} finally {
completeStartFuture(false);
}
}
private void completeStartFuture(boolean value) {
if (startFuture != null && !startFuture.isDone()) {
startFuture.complete(value);
}
if (exportFuture != null && !exportFuture.isDone()) {
exportFuture.cancel(true);
}
if (referFuture != null && !referFuture.isDone()) {
referFuture.cancel(true);
}
}
private void onModuleStopping() {
try {
setStopping();
logger.info(getIdentifier() + " is stopping.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STOPPING);
} finally {
completeStartFuture(false);
}
}
private void onModuleStopped() {
try {
setStopped();
logger.info(getIdentifier() + " has stopped.");
applicationDeployer.notifyModuleChanged(moduleModel, DeployState.STOPPED);
} finally {
completeStartFuture(false);
}
}
private void loadConfigs() {
// load module configs
moduleModel.getConfigManager().loadConfigs();
moduleModel.getConfigManager().refreshAll();
}
private void exportServices() {
for (ServiceConfigBase sc : configManager.getServices()) {
exportServiceInternal(sc);
}
}
private void registerServices() {
for (ServiceConfigBase sc : configManager.getServices()) {
if (!Boolean.FALSE.equals(sc.isRegister())) {
registerServiceInternal(sc);
}
}
applicationDeployer.refreshServiceInstance();
}
private void checkReferences() {
Optional<ModuleConfig> module = configManager.getModule();
long timeout = module.map(ModuleConfig::getCheckReferenceTimeout).orElse(30000L);
for (ReferenceConfigBase<?> rc : configManager.getReferences()) {
referenceCache.check(rc, timeout);
}
}
private void exportServiceInternal(ServiceConfigBase sc) {
ServiceConfig<?> serviceConfig = (ServiceConfig<?>) sc;
if (!serviceConfig.isRefreshed()) {
serviceConfig.refresh();
}
if (sc.isExported()) {
return;
}
if (exportAsync || sc.shouldExportAsync()) {
ExecutorService executor = executorRepository.getServiceExportExecutor();
CompletableFuture<Void> future = CompletableFuture.runAsync(
() -> {
try {
if (!sc.isExported()) {
sc.export();
exportedServices.add(sc);
}
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to async export service config: " + getIdentifier() + " , catch error : "
+ t.getMessage(),
t);
}
},
executor);
asyncExportingFutures.add(future);
} else {
if (!sc.isExported()) {
sc.export(RegisterTypeEnum.AUTO_REGISTER_BY_DEPLOYER);
exportedServices.add(sc);
}
}
if (serviceConfig.hasRegistrySpecified()) {
registryInteracted = true;
}
}
private void registerServiceInternal(ServiceConfigBase sc) {
ServiceConfig<?> serviceConfig = (ServiceConfig<?>) sc;
if (!serviceConfig.isRefreshed()) {
serviceConfig.refresh();
}
if (!sc.isExported()) {
return;
}
if (sc.shouldDelay()) {
return;
}
sc.register(true);
}
private void unexportServices() {
exportedServices.forEach(sc -> {
try {
configManager.removeConfig(sc);
sc.unexport();
} catch (Throwable t) {
logger.info("Failed to un-export service. Service Key: " + sc.getUniqueServiceName(), t);
}
});
exportedServices.clear();
asyncExportingFutures.forEach(future -> {
if (!future.isDone()) {
future.cancel(true);
}
});
asyncExportingFutures.clear();
}
private void referServices() {
configManager.getReferences().forEach(rc -> {
try {
ReferenceConfig<?> referenceConfig = (ReferenceConfig<?>) rc;
if (!referenceConfig.isRefreshed()) {
referenceConfig.refresh();
}
if (rc.shouldInit()) {
if (referAsync || rc.shouldReferAsync()) {
ExecutorService executor = executorRepository.getServiceReferExecutor();
CompletableFuture<Void> future = CompletableFuture.runAsync(
() -> {
try {
referenceCache.get(rc, false);
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_EXPORT_SERVICE,
"",
"",
"Failed to async export service config: " + getIdentifier()
+ " , catch error : " + t.getMessage(),
t);
}
},
executor);
asyncReferringFutures.add(future);
} else {
referenceCache.get(rc, false);
}
}
} catch (Throwable t) {
logger.error(
CONFIG_FAILED_REFERENCE_MODEL,
"",
"",
"Model reference failed: " + getIdentifier() + " , catch error : " + t.getMessage(),
t);
referenceCache.destroy(rc);
throw t;
}
});
}
private void unreferServices() {
try {
asyncReferringFutures.forEach(future -> {
if (!future.isDone()) {
future.cancel(true);
}
});
asyncReferringFutures.clear();
referenceCache.destroyAll();
for (ReferenceConfigBase<?> rc : configManager.getReferences()) {
rc.destroy();
}
} catch (Exception ignored) {
}
}
private void waitExportFinish() {
try {
logger.info(getIdentifier() + " waiting services exporting ...");
exportFuture = CompletableFuture.allOf(asyncExportingFutures.toArray(new CompletableFuture[0]));
exportFuture.get();
} catch (Throwable e) {
logger.warn(
CONFIG_FAILED_EXPORT_SERVICE,
"",
"",
getIdentifier() + " export services occurred an exception: " + e.toString());
} finally {
logger.info(getIdentifier() + " export services finished.");
asyncExportingFutures.clear();
}
}
private void waitReferFinish() {
try {
logger.info(getIdentifier() + " waiting services referring ...");
referFuture = CompletableFuture.allOf(asyncReferringFutures.toArray(new CompletableFuture[0]));
referFuture.get();
} catch (Throwable e) {
logger.warn(
CONFIG_FAILED_REFER_SERVICE,
"",
"",
getIdentifier() + " refer services occurred an exception: " + e.toString());
} finally {
logger.info(getIdentifier() + " refer services finished.");
asyncReferringFutures.clear();
}
}
@Override
public boolean isBackground() {
return background;
}
private boolean isExportBackground() {
return moduleModel.getConfigManager().getProviders().stream()
.map(ProviderConfig::getExportBackground)
.anyMatch(k -> k != null && k);
}
private boolean isReferBackground() {
return moduleModel.getConfigManager().getConsumers().stream()
.map(ConsumerConfig::getReferBackground)
.anyMatch(k -> k != null && k);
}
@Override
public ReferenceCache getReferenceCache() {
return referenceCache;
}
@Override
public void registerServiceInstance() {
applicationDeployer.registerServiceInstance();
}
/**
* Prepare for export/refer service, trigger initializing application and module
*/
@Override
public void prepare() {
applicationDeployer.initialize();
this.initialize();
}
@Override
public boolean hasRegistryInteraction() {
return registryInteracted;
}
@Override
public ApplicationDeployer getApplicationDeployer() {
return applicationDeployer;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrap.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap;
import org.apache.dubbo.common.config.Environment;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.deploy.ApplicationDeployer;
import org.apache.dubbo.common.deploy.DeployListenerAdapter;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.ExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.bootstrap.builders.ApplicationBuilder;
import org.apache.dubbo.config.bootstrap.builders.ConfigCenterBuilder;
import org.apache.dubbo.config.bootstrap.builders.ConsumerBuilder;
import org.apache.dubbo.config.bootstrap.builders.MetadataReportBuilder;
import org.apache.dubbo.config.bootstrap.builders.ProtocolBuilder;
import org.apache.dubbo.config.bootstrap.builders.ProviderBuilder;
import org.apache.dubbo.config.bootstrap.builders.ReferenceBuilder;
import org.apache.dubbo.config.bootstrap.builders.RegistryBuilder;
import org.apache.dubbo.config.bootstrap.builders.ServiceBuilder;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import static java.util.Collections.singletonList;
/**
* See {@link ApplicationModel} and {@link ExtensionLoader} for why this class is designed to be singleton.
* <p>
* The bootstrap class of Dubbo
* <p>
* Get singleton instance by calling static method {@link #getInstance()}.
* Designed as singleton because some classes inside Dubbo, such as ExtensionLoader, are designed only for one instance per process.
*
* @since 2.7.5
*/
public final class DubboBootstrap {
private static final String NAME = DubboBootstrap.class.getSimpleName();
private static final Logger logger = LoggerFactory.getLogger(DubboBootstrap.class);
private static final ConcurrentMap<ApplicationModel, DubboBootstrap> instanceMap = new ConcurrentHashMap<>();
private static volatile DubboBootstrap instance;
private final AtomicBoolean awaited = new AtomicBoolean(false);
private volatile BootstrapTakeoverMode takeoverMode = BootstrapTakeoverMode.AUTO;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private final ExecutorRepository executorRepository;
private final Environment environment;
private final ApplicationModel applicationModel;
private final ConfigManager configManager;
private final ApplicationDeployer applicationDeployer;
/**
* See {@link ApplicationModel} and {@link ExtensionLoader} for why DubboBootstrap is designed to be singleton.
*/
public static DubboBootstrap getInstance() {
if (instance == null) {
synchronized (DubboBootstrap.class) {
if (instance == null) {
instance = DubboBootstrap.getInstance(ApplicationModel.defaultModel());
}
}
}
return instance;
}
public static DubboBootstrap getInstance(ApplicationModel applicationModel) {
return ConcurrentHashMapUtils.computeIfAbsent(
instanceMap, applicationModel, _k -> new DubboBootstrap(applicationModel));
}
public static DubboBootstrap newInstance() {
return getInstance(FrameworkModel.defaultModel().newApplication());
}
public static DubboBootstrap newInstance(FrameworkModel frameworkModel) {
return getInstance(frameworkModel.newApplication());
}
/**
* Try reset dubbo status for new instance.
*
* @deprecated For testing purposes only
*/
@Deprecated
public static void reset() {
reset(true);
}
/**
* Try reset dubbo status for new instance.
*
* @deprecated For testing purposes only
*/
@Deprecated
public static void reset(boolean destroy) {
if (destroy) {
if (instance != null) {
instance.destroy();
instance = null;
}
FrameworkModel.destroyAll();
} else {
instance = null;
}
ApplicationModel.reset();
}
private DubboBootstrap(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
configManager = applicationModel.getApplicationConfigManager();
environment = applicationModel.modelEnvironment();
executorRepository = ExecutorRepository.getInstance(applicationModel);
applicationDeployer = applicationModel.getDeployer();
// listen deploy events
applicationDeployer.addDeployListener(new DeployListenerAdapter<ApplicationModel>() {
@Override
public void onStarted(ApplicationModel scopeModel) {
notifyStarted(applicationModel);
}
@Override
public void onStopped(ApplicationModel scopeModel) {
notifyStopped(applicationModel);
}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {
notifyStopped(applicationModel);
}
});
// register DubboBootstrap bean
applicationModel.getBeanFactory().registerBean(this);
}
private void notifyStarted(ApplicationModel applicationModel) {
ExtensionLoader<DubboBootstrapStartStopListener> exts =
applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class);
exts.getSupportedExtensionInstances().forEach(ext -> ext.onStart(DubboBootstrap.this));
}
private void notifyStopped(ApplicationModel applicationModel) {
ExtensionLoader<DubboBootstrapStartStopListener> exts =
applicationModel.getExtensionLoader(DubboBootstrapStartStopListener.class);
exts.getSupportedExtensionInstances().forEach(ext -> ext.onStop(DubboBootstrap.this));
executeMutually(() -> {
awaited.set(true);
condition.signalAll();
});
instanceMap.remove(applicationModel);
}
/**
* Initialize
*/
public void initialize() {
applicationDeployer.initialize();
}
/**
* Start dubbo application and wait for finish
*/
public DubboBootstrap start() {
this.start(true);
return this;
}
/**
* Start dubbo application
*
* @param wait If true, wait for startup to complete, or else no waiting.
* @return
*/
public DubboBootstrap start(boolean wait) {
Future future = applicationDeployer.start();
if (wait) {
try {
future.get();
} catch (Exception e) {
throw new IllegalStateException("await dubbo application start finish failure", e);
}
}
return this;
}
/**
* Start dubbo application but no wait for finish.
*
* @return the future object
*/
public Future asyncStart() {
return applicationDeployer.start();
}
/**
* Stop dubbo application
*
* @return
* @throws IllegalStateException
*/
public DubboBootstrap stop() throws IllegalStateException {
destroy();
return this;
}
public void destroy() {
applicationModel.destroy();
}
public boolean isInitialized() {
return applicationDeployer.isInitialized();
}
public boolean isPending() {
return applicationDeployer.isPending();
}
/**
* @return true if the dubbo application is starting or has been started.
*/
public boolean isRunning() {
return applicationDeployer.isRunning();
}
/**
* @return true if the dubbo application is starting.
* @see #isStarted()
*/
public boolean isStarting() {
return applicationDeployer.isStarting();
}
/**
* @return true if the dubbo application has been started.
* @see #start()
* @see #isStarting()
*/
public boolean isStarted() {
return applicationDeployer.isStarted();
}
public boolean isCompletion() {
return applicationDeployer.isCompletion();
}
/**
* @return true if the dubbo application is stopping.
* @see #isStopped()
*/
public boolean isStopping() {
return applicationDeployer.isStopping();
}
/**
* @return true if the dubbo application is stopping.
* @see #isStopped()
*/
public boolean isStopped() {
return applicationDeployer.isStopped();
}
/**
* Block current thread to be await.
*
* @return {@link DubboBootstrap}
*/
public DubboBootstrap await() {
// if has been waited, no need to wait again, return immediately
if (!awaited.get()) {
if (!isStopped()) {
executeMutually(() -> {
while (!awaited.get()) {
if (logger.isInfoEnabled()) {
logger.info(NAME + " awaiting ...");
}
try {
condition.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
}
return this;
}
public ReferenceCache getCache() {
return applicationDeployer.getReferenceCache();
}
private void executeMutually(Runnable runnable) {
try {
lock.lock();
runnable.run();
} finally {
lock.unlock();
}
}
public ApplicationConfig getApplication() {
return configManager.getApplicationOrElseThrow();
}
public void setTakeoverMode(BootstrapTakeoverMode takeoverMode) {
// TODO this.started.set(false);
this.takeoverMode = takeoverMode;
}
public BootstrapTakeoverMode getTakeoverMode() {
return takeoverMode;
}
public ApplicationModel getApplicationModel() {
return applicationModel;
}
public ConfigManager getConfigManager() {
return configManager;
}
// MetadataReportConfig correlative methods
public DubboBootstrap metadataReport(Consumer<MetadataReportBuilder> consumerBuilder) {
return metadataReport(null, consumerBuilder);
}
public DubboBootstrap metadataReport(String id, Consumer<MetadataReportBuilder> consumerBuilder) {
MetadataReportBuilder metadataReportBuilder = createMetadataReportBuilder(id);
consumerBuilder.accept(metadataReportBuilder);
return this;
}
public DubboBootstrap metadataReport(MetadataReportConfig metadataReportConfig) {
configManager.addMetadataReport(metadataReportConfig);
return this;
}
public DubboBootstrap metadataReports(List<MetadataReportConfig> metadataReportConfigs) {
if (CollectionUtils.isEmpty(metadataReportConfigs)) {
return this;
}
configManager.addMetadataReports(metadataReportConfigs);
return this;
}
// {@link ApplicationConfig} correlative methods
/**
* Set the name of application
*
* @param name the name of application
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(String name) {
return application(name, builder -> {
// DO NOTHING
});
}
/**
* Set the name of application and it's future build
*
* @param name the name of application
* @param consumerBuilder {@link ApplicationBuilder}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(String name, Consumer<ApplicationBuilder> consumerBuilder) {
ApplicationBuilder builder = createApplicationBuilder(name);
consumerBuilder.accept(builder);
return application(builder.build());
}
/**
* Set the {@link ApplicationConfig}
*
* @param applicationConfig the {@link ApplicationConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap application(ApplicationConfig applicationConfig) {
applicationConfig.setScopeModel(applicationModel);
configManager.setApplication(applicationConfig);
return this;
}
// {@link RegistryConfig} correlative methods
/**
* Add an instance of {@link RegistryConfig}
*
* @param consumerBuilder the {@link Consumer} of {@link RegistryBuilder}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(Consumer<RegistryBuilder> consumerBuilder) {
return registry(null, consumerBuilder);
}
/**
* Add an instance of {@link RegistryConfig} with the specified ID
*
* @param id the {@link RegistryConfig#getId() id} of {@link RegistryConfig}
* @param consumerBuilder the {@link Consumer} of {@link RegistryBuilder}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(String id, Consumer<RegistryBuilder> consumerBuilder) {
RegistryBuilder builder = createRegistryBuilder(id);
consumerBuilder.accept(builder);
return registry(builder.build());
}
/**
* Add an instance of {@link RegistryConfig}
*
* @param registryConfig an instance of {@link RegistryConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registry(RegistryConfig registryConfig) {
registryConfig.setScopeModel(applicationModel);
configManager.addRegistry(registryConfig);
return this;
}
/**
* Add an instance of {@link RegistryConfig}
*
* @param registryConfigs the multiple instances of {@link RegistryConfig}
* @return current {@link DubboBootstrap} instance
*/
public DubboBootstrap registries(List<RegistryConfig> registryConfigs) {
if (CollectionUtils.isEmpty(registryConfigs)) {
return this;
}
registryConfigs.forEach(this::registry);
return this;
}
// {@link ProtocolConfig} correlative methods
public DubboBootstrap protocol(Consumer<ProtocolBuilder> consumerBuilder) {
return protocol(null, consumerBuilder);
}
public DubboBootstrap protocol(String id, Consumer<ProtocolBuilder> consumerBuilder) {
ProtocolBuilder builder = createProtocolBuilder(id);
consumerBuilder.accept(builder);
return protocol(builder.build());
}
public DubboBootstrap protocol(ProtocolConfig protocolConfig) {
return protocols(singletonList(protocolConfig));
}
public DubboBootstrap protocols(List<ProtocolConfig> protocolConfigs) {
if (CollectionUtils.isEmpty(protocolConfigs)) {
return this;
}
for (ProtocolConfig protocolConfig : protocolConfigs) {
protocolConfig.setScopeModel(applicationModel);
configManager.addProtocol(protocolConfig);
}
return this;
}
// {@link ServiceConfig} correlative methods
public <S> DubboBootstrap service(Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(null, consumerBuilder);
}
public <S> DubboBootstrap service(String id, Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(createServiceConfig(id, consumerBuilder));
}
private <S> ServiceConfig createServiceConfig(String id, Consumer<ServiceBuilder<S>> consumerBuilder) {
ServiceBuilder builder = createServiceBuilder(id);
consumerBuilder.accept(builder);
return builder.build();
}
public DubboBootstrap services(List<ServiceConfig> serviceConfigs) {
if (CollectionUtils.isEmpty(serviceConfigs)) {
return this;
}
for (ServiceConfig serviceConfig : serviceConfigs) {
this.service(serviceConfig);
}
return this;
}
public DubboBootstrap service(ServiceConfig<?> serviceConfig) {
this.service(serviceConfig, applicationModel.getDefaultModule());
return this;
}
public DubboBootstrap service(ServiceConfig<?> serviceConfig, ModuleModel moduleModel) {
serviceConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addService(serviceConfig);
return this;
}
// {@link Reference} correlative methods
public <S> DubboBootstrap reference(Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(null, consumerBuilder);
}
public <S> DubboBootstrap reference(String id, Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(createReferenceConfig(id, consumerBuilder));
}
private <S> ReferenceConfig createReferenceConfig(String id, Consumer<ReferenceBuilder<S>> consumerBuilder) {
ReferenceBuilder builder = createReferenceBuilder(id);
consumerBuilder.accept(builder);
return builder.build();
}
public DubboBootstrap references(List<ReferenceConfig> referenceConfigs) {
if (CollectionUtils.isEmpty(referenceConfigs)) {
return this;
}
for (ReferenceConfig referenceConfig : referenceConfigs) {
this.reference(referenceConfig);
}
return this;
}
public DubboBootstrap reference(ReferenceConfig<?> referenceConfig) {
return reference(referenceConfig, applicationModel.getDefaultModule());
}
public DubboBootstrap reference(ReferenceConfig<?> referenceConfig, ModuleModel moduleModel) {
referenceConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addReference(referenceConfig);
return this;
}
// {@link ProviderConfig} correlative methods
public DubboBootstrap provider(Consumer<ProviderBuilder> builderConsumer) {
provider(null, builderConsumer);
return this;
}
public DubboBootstrap provider(String id, Consumer<ProviderBuilder> builderConsumer) {
this.provider(createProviderConfig(id, builderConsumer));
return this;
}
private ProviderConfig createProviderConfig(String id, Consumer<ProviderBuilder> builderConsumer) {
ProviderBuilder builder = createProviderBuilder(id);
builderConsumer.accept(builder);
return builder.build();
}
public DubboBootstrap provider(ProviderConfig providerConfig) {
return this.provider(providerConfig, applicationModel.getDefaultModule());
}
public DubboBootstrap providers(List<ProviderConfig> providerConfigs) {
for (ProviderConfig providerConfig : providerConfigs) {
this.provider(providerConfig, applicationModel.getDefaultModule());
}
return this;
}
public DubboBootstrap provider(ProviderConfig providerConfig, ModuleModel moduleModel) {
providerConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addProvider(providerConfig);
return this;
}
// {@link ConsumerConfig} correlative methods
public DubboBootstrap consumer(Consumer<ConsumerBuilder> builderConsumer) {
return consumer(null, builderConsumer);
}
public DubboBootstrap consumer(String id, Consumer<ConsumerBuilder> builderConsumer) {
return consumer(createConsumerConfig(id, builderConsumer));
}
private ConsumerConfig createConsumerConfig(String id, Consumer<ConsumerBuilder> builderConsumer) {
ConsumerBuilder builder = createConsumerBuilder(id);
builderConsumer.accept(builder);
return builder.build();
}
public DubboBootstrap consumer(ConsumerConfig consumerConfig) {
return this.consumer(consumerConfig, applicationModel.getDefaultModule());
}
public DubboBootstrap consumers(List<ConsumerConfig> consumerConfigs) {
for (ConsumerConfig consumerConfig : consumerConfigs) {
this.consumer(consumerConfig, applicationModel.getDefaultModule());
}
return this;
}
public DubboBootstrap consumer(ConsumerConfig consumerConfig, ModuleModel moduleModel) {
consumerConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().addConsumer(consumerConfig);
return this;
}
public DubboBootstrap module(ModuleConfig moduleConfig) {
this.module(moduleConfig, applicationModel.getDefaultModule());
return this;
}
public DubboBootstrap module(ModuleConfig moduleConfig, ModuleModel moduleModel) {
moduleConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().setModule(moduleConfig);
return this;
}
// module configs end
// {@link ConfigCenterConfig} correlative methods
public DubboBootstrap configCenter(Consumer<ConfigCenterBuilder> consumerBuilder) {
return configCenter(null, consumerBuilder);
}
public DubboBootstrap configCenter(String id, Consumer<ConfigCenterBuilder> consumerBuilder) {
ConfigCenterBuilder configCenterBuilder = createConfigCenterBuilder(id);
consumerBuilder.accept(configCenterBuilder);
return this;
}
public DubboBootstrap configCenter(ConfigCenterConfig configCenterConfig) {
configCenterConfig.setScopeModel(applicationModel);
configManager.addConfigCenter(configCenterConfig);
return this;
}
public DubboBootstrap configCenters(List<ConfigCenterConfig> configCenterConfigs) {
if (CollectionUtils.isEmpty(configCenterConfigs)) {
return this;
}
for (ConfigCenterConfig configCenterConfig : configCenterConfigs) {
this.configCenter(configCenterConfig);
}
return this;
}
public DubboBootstrap monitor(MonitorConfig monitor) {
monitor.setScopeModel(applicationModel);
configManager.setMonitor(monitor);
return this;
}
public DubboBootstrap metrics(MetricsConfig metrics) {
metrics.setScopeModel(applicationModel);
configManager.setMetrics(metrics);
return this;
}
public DubboBootstrap tracing(TracingConfig tracing) {
tracing.setScopeModel(applicationModel);
configManager.setTracing(tracing);
return this;
}
public DubboBootstrap ssl(SslConfig sslConfig) {
sslConfig.setScopeModel(applicationModel);
configManager.setSsl(sslConfig);
return this;
}
/* serve for builder apis, begin */
private ApplicationBuilder createApplicationBuilder(String name) {
return new ApplicationBuilder().name(name);
}
private RegistryBuilder createRegistryBuilder(String id) {
return new RegistryBuilder().id(id);
}
private MetadataReportBuilder createMetadataReportBuilder(String id) {
return new MetadataReportBuilder().id(id);
}
private ConfigCenterBuilder createConfigCenterBuilder(String id) {
return new ConfigCenterBuilder().id(id);
}
private ProtocolBuilder createProtocolBuilder(String id) {
return new ProtocolBuilder().id(id);
}
private ServiceBuilder createServiceBuilder(String id) {
return new ServiceBuilder().id(id);
}
private ReferenceBuilder createReferenceBuilder(String id) {
return new ReferenceBuilder().id(id);
}
private ProviderBuilder createProviderBuilder(String id) {
return new ProviderBuilder().id(id);
}
private ConsumerBuilder createConsumerBuilder(String id) {
return new ConsumerBuilder().id(id);
}
/* serve for builder apis, end */
public Module newModule() {
return new Module(applicationModel.newModule());
}
public Module newModule(ModuleConfig moduleConfig) {
ModuleModel moduleModel = applicationModel.newModule();
moduleConfig.setScopeModel(moduleModel);
moduleModel.getConfigManager().setModule(moduleConfig);
return new Module(moduleModel);
}
public DubboBootstrap endModule() {
return this;
}
public class Module {
private ModuleModel moduleModel;
private DubboBootstrap bootstrap;
public Module(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
this.bootstrap = DubboBootstrap.this;
}
public DubboBootstrap endModule() {
return this.bootstrap.endModule();
}
public ModuleModel getModuleModel() {
return moduleModel;
}
public Module config(ModuleConfig moduleConfig) {
this.moduleModel.getConfigManager().setModule(moduleConfig);
return this;
}
// {@link ServiceConfig} correlative methods
public <S> Module service(Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(null, consumerBuilder);
}
public <S> Module service(String id, Consumer<ServiceBuilder<S>> consumerBuilder) {
return service(createServiceConfig(id, consumerBuilder));
}
public Module services(List<ServiceConfig> serviceConfigs) {
if (CollectionUtils.isEmpty(serviceConfigs)) {
return this;
}
for (ServiceConfig serviceConfig : serviceConfigs) {
this.service(serviceConfig);
}
return this;
}
public Module service(ServiceConfig<?> serviceConfig) {
DubboBootstrap.this.service(serviceConfig, moduleModel);
return this;
}
// {@link Reference} correlative methods
public <S> Module reference(Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(null, consumerBuilder);
}
public <S> Module reference(String id, Consumer<ReferenceBuilder<S>> consumerBuilder) {
return reference(createReferenceConfig(id, consumerBuilder));
}
public Module reference(ReferenceConfig<?> referenceConfig) {
DubboBootstrap.this.reference(referenceConfig, moduleModel);
return this;
}
public Module references(List<ReferenceConfig> referenceConfigs) {
if (CollectionUtils.isEmpty(referenceConfigs)) {
return this;
}
for (ReferenceConfig referenceConfig : referenceConfigs) {
this.reference(referenceConfig);
}
return this;
}
// {@link ProviderConfig} correlative methods
public Module provider(Consumer<ProviderBuilder> builderConsumer) {
return provider(null, builderConsumer);
}
public Module provider(String id, Consumer<ProviderBuilder> builderConsumer) {
return provider(createProviderConfig(id, builderConsumer));
}
public Module provider(ProviderConfig providerConfig) {
DubboBootstrap.this.provider(providerConfig, moduleModel);
return this;
}
public Module providers(List<ProviderConfig> providerConfigs) {
if (CollectionUtils.isEmpty(providerConfigs)) {
return this;
}
for (ProviderConfig providerConfig : providerConfigs) {
DubboBootstrap.this.provider(providerConfig, moduleModel);
}
return this;
}
// {@link ConsumerConfig} correlative methods
public Module consumer(Consumer<ConsumerBuilder> builderConsumer) {
return consumer(null, builderConsumer);
}
public Module consumer(String id, Consumer<ConsumerBuilder> builderConsumer) {
return consumer(createConsumerConfig(id, builderConsumer));
}
public Module consumer(ConsumerConfig consumerConfig) {
DubboBootstrap.this.consumer(consumerConfig, moduleModel);
return this;
}
public Module consumers(List<ConsumerConfig> consumerConfigs) {
if (CollectionUtils.isEmpty(consumerConfigs)) {
return this;
}
for (ConsumerConfig consumerConfig : consumerConfigs) {
DubboBootstrap.this.consumer(consumerConfig, moduleModel);
}
return this;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/BootstrapTakeoverMode.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/BootstrapTakeoverMode.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap;
import org.apache.dubbo.config.ServiceConfig;
/**
* Mode of which of DubboBootstrap lifecycle being takeover
* SPRING: will be controlled by spring context
* MANUAL: will be controlled by users, after all services init, should call {@link DubboBootstrap#start()} to init app-level env
* AUTO: env will be init once {@link ServiceConfig#export()} finished
* SERVLET: will be controlled by java servlet container
*/
public enum BootstrapTakeoverMode {
SPRING,
MANUAL,
AUTO,
SERVLET
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrapStartStopListener.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/DubboBootstrapStartStopListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap;
import org.apache.dubbo.common.extension.SPI;
/**
* call on DubboBootstrap start or stop.
*
* @scene 2.7.9
* @see DubboBootstrap
*/
@SPI
@Deprecated
public interface DubboBootstrapStartStopListener {
void onStart(DubboBootstrap bootstrap);
void onStop(DubboBootstrap bootstrap);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractMethodConfig;
import java.util.Map;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractMethodBuilder<T extends AbstractMethodConfig, B extends AbstractMethodBuilder<T, B>>
extends AbstractBuilder<T, B> {
/**
* The timeout for remote invocation in milliseconds
*/
protected Integer timeout;
/**
* The retry times
*/
protected Integer retries;
/**
* max concurrent invocations
*/
protected Integer actives;
/**
* The load balance
*/
protected String loadbalance;
/**
* Whether to async
* note that: it is an unreliable asynchronism that ignores return values and does not block threads.
*/
protected Boolean async;
/**
* Whether to ack async-sent
*/
protected Boolean sent;
/**
* The name of mock class which gets called when a service fails to execute
*
* note that: the mock doesn't support on the provider side,and the mock is executed when a non-business exception
* occurs after a remote service call
*/
protected String mock;
/**
* Merger
*/
protected String merger;
/**
* Cache the return result with the call parameter as key, the following options are available: lru, threadlocal,
* jcache, etc.
*/
protected String cache;
/**
* Whether JSR303 standard annotation validation is enabled or not, if enabled, annotations on method parameters will
* be validated
*/
protected String validation;
/**
* The customized parameters
*/
protected Map<String, String> parameters;
/**
* Forks for forking cluster
*/
protected Integer forks;
public B timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
}
public B retries(Integer retries) {
this.retries = retries;
return getThis();
}
public B actives(Integer actives) {
this.actives = actives;
return getThis();
}
public B loadbalance(String loadbalance) {
this.loadbalance = loadbalance;
return getThis();
}
public B async(Boolean async) {
this.async = async;
return getThis();
}
public B sent(Boolean sent) {
this.sent = sent;
return getThis();
}
public B mock(String mock) {
this.mock = mock;
return getThis();
}
public B mock(Boolean mock) {
if (mock != null) {
this.mock = mock.toString();
} else {
this.mock = null;
}
return getThis();
}
public B merger(String merger) {
this.merger = merger;
return getThis();
}
public B cache(String cache) {
this.cache = cache;
return getThis();
}
public B validation(String validation) {
this.validation = validation;
return getThis();
}
public B appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public B appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public B forks(Integer forks) {
this.forks = forks;
return getThis();
}
@Override
@SuppressWarnings("unchecked")
public void build(T instance) {
super.build(instance);
if (actives != null) {
instance.setActives(actives);
}
if (async != null) {
instance.setAsync(async);
}
if (!StringUtils.isEmpty(cache)) {
instance.setCache(cache);
}
if (forks != null) {
instance.setForks(forks);
}
if (!StringUtils.isEmpty(loadbalance)) {
instance.setLoadbalance(loadbalance);
}
if (!StringUtils.isEmpty(merger)) {
instance.setMerger(merger);
}
if (!StringUtils.isEmpty(mock)) {
instance.setMock(mock);
}
if (retries != null) {
instance.setRetries(retries);
}
if (sent != null) {
instance.setSent(sent);
}
if (timeout != null) {
instance.setTimeout(timeout);
}
if (!StringUtils.isEmpty(validation)) {
instance.setValidation(validation);
}
if (parameters != null) {
instance.setParameters(parameters);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ArgumentConfig;
/**
* This is a builder for build {@link ArgumentConfig}.
* @since 2.7
*/
public class ArgumentBuilder {
/**
* The argument index: index -1 represents not set
*/
private Integer index = -1;
/**
* Argument type
*/
private String type;
/**
* Whether the argument is the callback interface
*/
private Boolean callback;
public static ArgumentBuilder newBuilder() {
return new ArgumentBuilder();
}
public ArgumentBuilder index(Integer index) {
this.index = index;
return this;
}
public ArgumentBuilder type(String type) {
this.type = type;
return this;
}
public ArgumentBuilder callback(Boolean callback) {
this.callback = callback;
return this;
}
public ArgumentConfig build() {
ArgumentConfig argumentConfig = new ArgumentConfig();
argumentConfig.setIndex(index);
argumentConfig.setType(type);
argumentConfig.setCallback(callback);
return argumentConfig;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractInterfaceConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.Filter;
import java.util.ArrayList;
import java.util.List;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractInterfaceBuilder<
T extends AbstractInterfaceConfig, B extends AbstractInterfaceBuilder<T, B>>
extends AbstractMethodBuilder<T, B> {
/**
* Local impl class name for the service interface
*/
protected String local;
/**
* Local stub class name for the service interface
*/
protected String stub;
/**
* Service monitor
*/
protected MonitorConfig monitor;
/**
* Strategies for generating dynamic agents,there are two strategies can be chosen: jdk and javassist
*/
protected String proxy;
/**
* Cluster type
*/
protected String cluster;
/**
* The {@link Filter} when the provider side exposed a service or the customer side references a remote service used,
* if there are more than one, you can use commas to separate them
*/
protected String filter;
/**
* The Listener when the provider side exposes a service or the customer side references a remote service used
* if there are more than one, you can use commas to separate them
*/
protected String listener;
/**
* The owner of the service providers
*/
protected String owner;
/**
* Connection limits, 0 means shared connection, otherwise it defines the connections delegated to the current service
*/
protected Integer connections;
/**
* The layer of service providers
*/
protected String layer;
/**
* The application info
*/
protected ApplicationConfig application;
/**
* The module info
*/
protected ModuleConfig module;
/**
* Registry centers
*/
protected List<RegistryConfig> registries;
protected String registryIds;
// connection events
protected String onconnect;
/**
* Disconnection events
*/
protected String ondisconnect;
protected MetadataReportConfig metadataReportConfig;
protected ConfigCenterConfig configCenter;
// callback limits
private Integer callbacks;
// the scope for referring/exporting a service, if it's local, it means searching in current JVM only.
private String scope;
private String tag;
/**
* @param local
* @see AbstractInterfaceBuilder#stub(String)
* @deprecated Replace to <code>stub(String)</code>
*/
@Deprecated
public B local(String local) {
this.local = local;
return getThis();
}
/**
* @param local
* @see AbstractInterfaceBuilder#stub(Boolean)
* @deprecated Replace to <code>stub(Boolean)</code>
*/
@Deprecated
public B local(Boolean local) {
if (local != null) {
this.local = local.toString();
} else {
this.local = null;
}
return getThis();
}
public B stub(String stub) {
this.stub = stub;
return getThis();
}
public B stub(Boolean stub) {
if (stub != null) {
this.stub = stub.toString();
} else {
this.stub = null;
}
return getThis();
}
public B monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
}
public B monitor(String monitor) {
this.monitor = new MonitorConfig(monitor);
return getThis();
}
public B proxy(String proxy) {
this.proxy = proxy;
return getThis();
}
public B cluster(String cluster) {
this.cluster = cluster;
return getThis();
}
public B filter(String filter) {
this.filter = filter;
return getThis();
}
public B listener(String listener) {
this.listener = listener;
return getThis();
}
public B owner(String owner) {
this.owner = owner;
return getThis();
}
public B connections(Integer connections) {
this.connections = connections;
return getThis();
}
public B layer(String layer) {
this.layer = layer;
return getThis();
}
public B application(ApplicationConfig application) {
this.application = application;
return getThis();
}
public B module(ModuleConfig module) {
this.module = module;
return getThis();
}
public B addRegistries(List<RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
}
public B addRegistry(RegistryConfig registry) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.add(registry);
return getThis();
}
public B registryIds(String registryIds) {
this.registryIds = registryIds;
return getThis();
}
public B onconnect(String onconnect) {
this.onconnect = onconnect;
return getThis();
}
public B ondisconnect(String ondisconnect) {
this.ondisconnect = ondisconnect;
return getThis();
}
public B metadataReportConfig(MetadataReportConfig metadataReportConfig) {
this.metadataReportConfig = metadataReportConfig;
return getThis();
}
public B configCenter(ConfigCenterConfig configCenter) {
this.configCenter = configCenter;
return getThis();
}
public B callbacks(Integer callbacks) {
this.callbacks = callbacks;
return getThis();
}
public B scope(String scope) {
this.scope = scope;
return getThis();
}
public B tag(String tag) {
this.tag = tag;
return getThis();
}
@Override
public void build(T instance) {
super.build(instance);
if (!StringUtils.isEmpty(local)) {
instance.setLocal(local);
}
if (!StringUtils.isEmpty(stub)) {
instance.setStub(stub);
}
if (monitor != null) {
instance.setMonitor(monitor);
}
if (!StringUtils.isEmpty(proxy)) {
instance.setProxy(proxy);
}
if (!StringUtils.isEmpty(cluster)) {
instance.setCluster(cluster);
}
if (!StringUtils.isEmpty(filter)) {
instance.setFilter(filter);
}
if (!StringUtils.isEmpty(listener)) {
instance.setListener(listener);
}
if (!StringUtils.isEmpty(owner)) {
instance.setOwner(owner);
}
if (connections != null) {
instance.setConnections(connections);
}
if (!StringUtils.isEmpty(layer)) {
instance.setLayer(layer);
}
if (application != null) {
instance.setApplication(application);
}
if (module != null) {
instance.setModule(module);
}
if (registries != null) {
instance.setRegistries(registries);
}
if (!StringUtils.isEmpty(registryIds)) {
instance.setRegistryIds(registryIds);
}
if (!StringUtils.isEmpty(onconnect)) {
instance.setOnconnect(onconnect);
}
if (!StringUtils.isEmpty(ondisconnect)) {
instance.setOndisconnect(ondisconnect);
}
if (metadataReportConfig != null) {
instance.setMetadataReportConfig(metadataReportConfig);
}
if (configCenter != null) {
instance.setConfigCenter(configCenter);
}
if (callbacks != null) {
instance.setCallbacks(callbacks);
}
if (!StringUtils.isEmpty(scope)) {
instance.setScope(scope);
}
if (StringUtils.isNotEmpty(tag)) {
instance.setTag(tag);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/TripleBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/TripleBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.nested.TripleConfig;
/**
* This is a builder for build {@link TripleConfig}.
*
* @since 3.3
*/
public class TripleBuilder {
/**
* Maximum allowed size for HTTP1 request bodies.
* Limits the size of request to prevent excessively large request.
* <p>The default value is 8MiB.
*/
private Integer maxBodySize;
/**
* Maximum allowed size for HTTP1 response bodies.
* Limits the size of responses to prevent excessively large response.
* <p>The default value is 8MiB.
*/
private Integer maxResponseBodySize;
/**
* Set the maximum chunk size.
* HTTP requests and responses can be quite large, in which case it's better to process the data as a stream of
* chunks.
* This sets the limit, in bytes, at which Netty will send a chunk down the pipeline.
* <p>The default value is 8KiB.
*/
private Integer maxChunkSize;
/**
* Set the maximum line length of header lines.
* This limits how much memory Netty will use when parsing HTTP header key-value pairs.
* You would typically set this to the same value as {@link #maxInitialLineLength(Integer)}.
* <p>The default value is 8KiB.
*/
private Integer maxHeaderSize;
/**
* Set the maximum length of the first line of the HTTP header.
* This limits how much memory Netty will use when parsed the initial HTTP header line.
* You would typically set this to the same value as {@link #maxHeaderSize(Integer)}.
* <p>The default value is 4096.
*/
private Integer maxInitialLineLength;
/**
* Set the initial size of the temporary buffer used when parsing the lines of the HTTP headers.
* <p>The default value is 128 octets.
*/
private Integer initialBufferSize;
/**
* The header table size.
*/
private Integer headerTableSize;
/**
* Whether to enable push, default is false.
*/
private Boolean enablePush;
/**
* Maximum concurrent streams.
*/
private Integer maxConcurrentStreams;
/**
* Initial window size.
*/
private Integer initialWindowSize;
/**
* Connection initial window size.
*/
private Integer connectionInitialWindowSize;
/**
* Maximum frame size.
*/
private Integer maxFrameSize;
/**
* Maximum header list size.
*/
private Integer maxHeaderListSize;
public static TripleBuilder newBuilder() {
return new TripleBuilder();
}
public TripleBuilder maxBodySize(Integer maxBodySize) {
this.maxBodySize = maxBodySize;
return getThis();
}
public TripleBuilder maxResponseBodySize(Integer maxResponseBodySize) {
this.maxResponseBodySize = maxResponseBodySize;
return getThis();
}
public TripleBuilder maxChunkSize(Integer maxChunkSize) {
this.maxChunkSize = maxChunkSize;
return getThis();
}
public TripleBuilder maxHeaderSize(Integer maxHeaderSize) {
this.maxHeaderSize = maxHeaderSize;
return getThis();
}
public TripleBuilder maxInitialLineLength(Integer maxInitialLineLength) {
this.maxInitialLineLength = maxInitialLineLength;
return getThis();
}
public TripleBuilder initialBufferSize(Integer initialBufferSize) {
this.initialBufferSize = initialBufferSize;
return getThis();
}
public TripleBuilder headerTableSize(Integer headerTableSize) {
this.headerTableSize = headerTableSize;
return getThis();
}
public TripleBuilder enablePush(Boolean enablePush) {
this.enablePush = enablePush;
return getThis();
}
public TripleBuilder maxConcurrentStreams(Integer maxConcurrentStreams) {
this.maxConcurrentStreams = maxConcurrentStreams;
return getThis();
}
public TripleBuilder initialWindowSize(Integer initialWindowSize) {
this.initialWindowSize = initialWindowSize;
return getThis();
}
public TripleBuilder connectionInitialWindowSize(Integer connectionInitialWindowSize) {
this.connectionInitialWindowSize = connectionInitialWindowSize;
return getThis();
}
public TripleBuilder maxFrameSize(Integer maxFrameSize) {
this.maxFrameSize = maxFrameSize;
return getThis();
}
public TripleBuilder maxHeaderListSize(Integer maxHeaderListSize) {
this.maxHeaderListSize = maxHeaderListSize;
return getThis();
}
protected TripleBuilder getThis() {
return this;
}
public TripleConfig build() {
TripleConfig triple = new TripleConfig();
if (maxBodySize != null) {
triple.setMaxBodySize(maxBodySize);
}
if (maxResponseBodySize != null) {
triple.setMaxResponseBodySize(maxResponseBodySize);
}
if (maxChunkSize != null) {
triple.setMaxChunkSize(maxChunkSize);
}
if (maxHeaderSize != null) {
triple.setMaxHeaderSize(maxHeaderSize);
}
if (maxInitialLineLength != null) {
triple.setMaxInitialLineLength(maxInitialLineLength);
}
if (initialBufferSize != null) {
triple.setInitialBufferSize(initialBufferSize);
}
if (headerTableSize != null) {
triple.setHeaderTableSize(headerTableSize);
}
if (enablePush != null) {
triple.setEnablePush(enablePush);
}
if (maxConcurrentStreams != null) {
triple.setMaxConcurrentStreams(maxConcurrentStreams);
}
if (initialWindowSize != null) {
triple.setInitialWindowSize(initialWindowSize);
}
if (connectionInitialWindowSize != null) {
triple.setConnectionInitialWindowSize(connectionInitialWindowSize);
}
if (maxFrameSize != null) {
triple.setMaxFrameSize(maxFrameSize);
}
if (maxHeaderListSize != null) {
triple.setMaxHeaderListSize(maxHeaderListSize);
}
return triple;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractServiceConfig;
import org.apache.dubbo.config.ProtocolConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractServiceBuilder<T extends AbstractServiceConfig, B extends AbstractServiceBuilder<T, B>>
extends AbstractInterfaceBuilder<T, B> {
/**
* The service version
*/
protected String version;
/**
* The service group
*/
protected String group;
/**
* whether the service is deprecated
*/
protected Boolean deprecated;
/**
* The time delay register service (milliseconds)
*/
protected Integer delay;
/**
* Whether to export the service
*/
protected Boolean export;
/**
* The service weight
*/
protected Integer weight;
/**
* Document center
*/
protected String document;
/**
* Whether to register as a dynamic service or not on register center, it the value is false, the status will be disabled
* after the service registered,and it needs to be enabled manually; if you want to disable the service, you also need
* manual processing
*/
protected Boolean dynamic;
/**
* Whether to use token
*/
protected String token;
/**
* Whether to export access logs to logs
*/
protected String accesslog;
/**
* The protocol list the service will export with
*/
protected List<ProtocolConfig> protocols;
protected String protocolIds;
// max allowed execute times
private Integer executes;
/**
* Whether to register
*/
private Boolean register;
/**
* Warm up period
*/
private Integer warmup;
/**
* The serialization type
*/
private String serialization;
/**
* used for thread pool isolation between services
*/
private Executor executor;
/**
* The prefer serialization type
*/
private String preferSerialization;
public B version(String version) {
this.version = version;
return getThis();
}
public B group(String group) {
this.group = group;
return getThis();
}
public B deprecated(Boolean deprecated) {
this.deprecated = deprecated;
return getThis();
}
public B delay(Integer delay) {
this.delay = delay;
return getThis();
}
public B export(Boolean export) {
this.export = export;
return getThis();
}
public B weight(Integer weight) {
this.weight = weight;
return getThis();
}
public B document(String document) {
this.document = document;
return getThis();
}
public B dynamic(Boolean dynamic) {
this.dynamic = dynamic;
return getThis();
}
public B token(String token) {
this.token = token;
return getThis();
}
public B token(Boolean token) {
if (token != null) {
this.token = token.toString();
} else {
this.token = null;
}
return getThis();
}
public B accesslog(String accesslog) {
this.accesslog = accesslog;
return getThis();
}
public B accesslog(Boolean accesslog) {
if (accesslog != null) {
this.accesslog = accesslog.toString();
} else {
this.accesslog = null;
}
return getThis();
}
public B addProtocols(List<ProtocolConfig> protocols) {
if (this.protocols == null) {
this.protocols = new ArrayList<>();
}
this.protocols.addAll(protocols);
return getThis();
}
public B addProtocol(ProtocolConfig protocol) {
if (this.protocols == null) {
this.protocols = new ArrayList<>();
}
this.protocols.add(protocol);
return getThis();
}
public B protocolIds(String protocolIds) {
this.protocolIds = protocolIds;
return getThis();
}
public B executes(Integer executes) {
this.executes = executes;
return getThis();
}
public B register(Boolean register) {
this.register = register;
return getThis();
}
public B warmup(Integer warmup) {
this.warmup = warmup;
return getThis();
}
public B serialization(String serialization) {
this.serialization = serialization;
return getThis();
}
public B executor(Executor executor) {
this.executor = executor;
return getThis();
}
/**
* The prefer serialization type
*
* @param preferSerialization prefer serialization type
* @return {@link B}
*/
public B preferSerialization(String preferSerialization) {
this.preferSerialization = preferSerialization;
return getThis();
}
@Override
public void build(T instance) {
super.build(instance);
if (!StringUtils.isEmpty(version)) {
instance.setVersion(version);
}
if (!StringUtils.isEmpty(group)) {
instance.setGroup(group);
}
if (deprecated != null) {
instance.setDeprecated(deprecated);
}
if (delay != null) {
instance.setDelay(delay);
}
if (export != null) {
instance.setExport(export);
}
if (weight != null) {
instance.setWeight(weight);
}
if (!StringUtils.isEmpty(document)) {
instance.setDocument(document);
}
if (dynamic != null) {
instance.setDynamic(dynamic);
}
if (!StringUtils.isEmpty(token)) {
instance.setToken(token);
}
if (!StringUtils.isEmpty(accesslog)) {
instance.setAccesslog(accesslog);
}
if (protocols != null) {
instance.setProtocols(protocols);
}
if (!StringUtils.isEmpty(protocolIds)) {
instance.setProtocolIds(protocolIds);
}
if (executes != null) {
instance.setExecutes(executes);
}
if (register != null) {
instance.setRegister(register);
}
if (warmup != null) {
instance.setWarmup(warmup);
}
if (!StringUtils.isEmpty(serialization)) {
instance.setSerialization(serialization);
}
if (executor != null) {
instance.setExecutor(executor);
}
if (StringUtils.isNotBlank(preferSerialization)) {
instance.setPreferSerialization(preferSerialization);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/package-info.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A bunch of builder classes to facilitate programming of raw API.
* TODO, these are experimental APIs and are possible to change at any time before marked as production.
*/
package org.apache.dubbo.config.bootstrap.builders;
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.RegistryConfig;
import java.util.Map;
/**
* This is a builder for build {@link RegistryConfig}.
*
* @since 2.7
*/
public class RegistryBuilder extends AbstractBuilder<RegistryConfig, RegistryBuilder> {
/**
* Register center address
*/
private String address;
/**
* Username to login register center
*/
private String username;
/**
* Password to login register center
*/
private String password;
/**
* Default port for register center
*/
private Integer port;
/**
* Protocol for register center
*/
private String protocol;
/**
* Network transmission type
*/
private String transporter;
private String server;
private String client;
private String cluster;
/**
* The group the services registry in
*/
private String group;
private String version;
/**
* Request timeout in milliseconds for register center
*/
private Integer timeout;
/**
* Session timeout in milliseconds for register center
*/
private Integer session;
/**
* File for saving register center dynamic list
*/
private String file;
/**
* Wait time before stop
*/
private Integer wait;
/**
* Whether to check if register center is available when boot up
*/
private Boolean check;
/**
* Whether to allow dynamic service to register on the register center
*/
private Boolean dynamic;
/**
* Whether to export service on the register center
*/
private Boolean register;
/**
* Whether allow to subscribe service on the register center
*/
private Boolean subscribe;
/**
* The customized parameters
*/
private Map<String, String> parameters;
/**
* Whether it's default
*/
private Boolean isDefault;
/**
* Simple the registry. both useful for provider and consumer
*
* @since 2.7.0
*/
private Boolean simplified;
/**
* After simplify the registry, should add some parameter individually. just for provider.
* <p>
* such as: extra-keys = A,b,c,d
*
* @since 2.7.0
*/
private String extraKeys;
/**
* the address work as config center or not
*/
private Boolean useAsConfigCenter;
/**
* the address work as remote metadata center or not
*/
private Boolean useAsMetadataCenter;
/**
* list of rpc protocols accepted by this registry, for example, "dubbo,rest"
*/
private String accepts;
/**
* Always use this registry first if set to true, useful when subscribe to multiple registries
*/
private Boolean preferred;
/**
* Affects traffic distribution among registries, useful when subscribe to multiple registries
* Take effect only when no preferred registry is specified.
*/
private Integer weight;
public static RegistryBuilder newBuilder() {
return new RegistryBuilder();
}
public RegistryBuilder id(String id) {
return super.id(id);
}
public RegistryBuilder address(String address) {
this.address = address;
return getThis();
}
public RegistryBuilder username(String username) {
this.username = username;
return getThis();
}
public RegistryBuilder password(String password) {
this.password = password;
return getThis();
}
public RegistryBuilder port(Integer port) {
this.port = port;
return getThis();
}
public RegistryBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public RegistryBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
/**
* @param transport
* @see #transporter(String)
* @deprecated
*/
@Deprecated
public RegistryBuilder transport(String transport) {
this.transporter = transport;
return getThis();
}
public RegistryBuilder server(String server) {
this.server = server;
return getThis();
}
public RegistryBuilder client(String client) {
this.client = client;
return getThis();
}
public RegistryBuilder cluster(String cluster) {
this.cluster = cluster;
return getThis();
}
public RegistryBuilder group(String group) {
this.group = group;
return getThis();
}
public RegistryBuilder version(String version) {
this.version = version;
return getThis();
}
public RegistryBuilder timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
}
public RegistryBuilder session(Integer session) {
this.session = session;
return getThis();
}
public RegistryBuilder file(String file) {
this.file = file;
return getThis();
}
/**
* @param wait
* @see ProviderBuilder#wait(Integer)
* @deprecated
*/
@Deprecated
public RegistryBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
}
public RegistryBuilder isCheck(Boolean check) {
this.check = check;
return getThis();
}
public RegistryBuilder isDynamic(Boolean dynamic) {
this.dynamic = dynamic;
return getThis();
}
public RegistryBuilder register(Boolean register) {
this.register = register;
return getThis();
}
public RegistryBuilder subscribe(Boolean subscribe) {
this.subscribe = subscribe;
return getThis();
}
public RegistryBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
/**
* @param name the parameter name
* @param value the parameter value
* @return {@link RegistryBuilder}
* @since 2.7.8
*/
public RegistryBuilder parameter(String name, String value) {
return appendParameter(name, value);
}
public RegistryBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public RegistryBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public RegistryBuilder simplified(Boolean simplified) {
this.simplified = simplified;
return getThis();
}
public RegistryBuilder extraKeys(String extraKeys) {
this.extraKeys = extraKeys;
return getThis();
}
public RegistryBuilder useAsConfigCenter(Boolean useAsConfigCenter) {
this.useAsConfigCenter = useAsConfigCenter;
return getThis();
}
public RegistryBuilder useAsMetadataCenter(Boolean useAsMetadataCenter) {
this.useAsMetadataCenter = useAsMetadataCenter;
return getThis();
}
public RegistryBuilder preferred(Boolean preferred) {
this.preferred = preferred;
return getThis();
}
public RegistryBuilder accepts(String accepts) {
this.accepts = accepts;
return getThis();
}
public RegistryBuilder weight(Integer weight) {
this.weight = weight;
return getThis();
}
@Override
public RegistryConfig build() {
RegistryConfig registry = new RegistryConfig();
super.build(registry);
registry.setCheck(check);
registry.setClient(client);
registry.setCluster(cluster);
registry.setDefault(isDefault);
registry.setDynamic(dynamic);
registry.setExtraKeys(extraKeys);
registry.setFile(file);
registry.setGroup(group);
registry.setParameters(parameters);
registry.setPassword(password);
registry.setPort(port);
registry.setProtocol(protocol);
registry.setRegister(register);
registry.setServer(server);
registry.setSession(session);
registry.setSimplified(simplified);
registry.setSubscribe(subscribe);
registry.setTimeout(timeout);
registry.setTransporter(transporter);
registry.setUsername(username);
registry.setVersion(version);
registry.setWait(wait);
registry.setUseAsConfigCenter(useAsConfigCenter);
registry.setUseAsMetadataCenter(useAsMetadataCenter);
registry.setAccepts(accepts);
registry.setPreferred(preferred);
registry.setWeight(weight);
registry.setAddress(address);
return registry;
}
@Override
protected RegistryBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.MethodConfig;
import java.util.ArrayList;
import java.util.List;
/**
* This is a builder for build {@link MethodConfig}.
*
* @since 2.7
*/
public class MethodBuilder extends AbstractMethodBuilder<MethodConfig, MethodBuilder> {
/**
* The method name
*/
private String name;
/**
* Stat
*/
private Integer stat;
/**
* Whether to retry
*/
private Boolean retry;
/**
* If it's reliable
*/
private Boolean reliable;
/**
* Thread limits for method invocations
*/
private Integer executes;
/**
* If it's deprecated
*/
private Boolean deprecated;
/**
* Whether to enable sticky
*/
private Boolean sticky;
/**
* Whether need to return
*/
private Boolean isReturn;
/**
* Callback instance when async-call is invoked
*/
private Object oninvoke;
/**
* Callback method when async-call is invoked
*/
private String oninvokeMethod;
/**
* Callback instance when async-call is returned
*/
private Object onreturn;
/**
* Callback method when async-call is returned
*/
private String onreturnMethod;
/**
* Callback instance when async-call has exception thrown
*/
private Object onthrow;
/**
* Callback method when async-call has exception thrown
*/
private String onthrowMethod;
/**
* The method arguments
*/
private List<ArgumentConfig> arguments;
/**
* These properties come from MethodConfig's parent Config module, they will neither be collected directly from xml or API nor be delivered to url
*/
private String service;
private String serviceId;
public static MethodBuilder newBuilder() {
return new MethodBuilder();
}
public MethodBuilder name(String name) {
this.name = name;
return getThis();
}
public MethodBuilder stat(Integer stat) {
this.stat = stat;
return getThis();
}
public MethodBuilder retry(Boolean retry) {
this.retry = retry;
return getThis();
}
public MethodBuilder reliable(Boolean reliable) {
this.reliable = reliable;
return getThis();
}
public MethodBuilder executes(Integer executes) {
this.executes = executes;
return getThis();
}
public MethodBuilder deprecated(Boolean deprecated) {
this.deprecated = deprecated;
return getThis();
}
public MethodBuilder sticky(Boolean sticky) {
this.sticky = sticky;
return getThis();
}
public MethodBuilder isReturn(Boolean isReturn) {
this.isReturn = isReturn;
return getThis();
}
public MethodBuilder oninvoke(Object oninvoke) {
this.oninvoke = oninvoke;
return getThis();
}
public MethodBuilder oninvokeMethod(String oninvokeMethod) {
this.oninvokeMethod = oninvokeMethod;
return getThis();
}
public MethodBuilder onreturn(Object onreturn) {
this.onreturn = onreturn;
return getThis();
}
public MethodBuilder onreturnMethod(String onreturnMethod) {
this.onreturnMethod = onreturnMethod;
return getThis();
}
public MethodBuilder onthrow(Object onthrow) {
this.onthrow = onthrow;
return getThis();
}
public MethodBuilder onthrowMethod(String onthrowMethod) {
this.onthrowMethod = onthrowMethod;
return getThis();
}
public MethodBuilder addArguments(List<? extends ArgumentConfig> arguments) {
if (this.arguments == null) {
this.arguments = new ArrayList<>();
}
this.arguments.addAll(arguments);
return getThis();
}
public MethodBuilder addArgument(ArgumentConfig argument) {
if (this.arguments == null) {
this.arguments = new ArrayList<>();
}
this.arguments.add(argument);
return getThis();
}
public MethodBuilder service(String service) {
this.service = service;
return getThis();
}
public MethodBuilder serviceId(String serviceId) {
this.serviceId = serviceId;
return getThis();
}
@Override
public MethodConfig build() {
MethodConfig methodConfig = new MethodConfig();
super.build(methodConfig);
methodConfig.setArguments(arguments);
methodConfig.setDeprecated(deprecated);
methodConfig.setExecutes(executes);
methodConfig.setName(name);
methodConfig.setOninvoke(oninvoke);
methodConfig.setOninvokeMethod(oninvokeMethod);
methodConfig.setOnreturn(onreturn);
methodConfig.setOnreturnMethod(onreturnMethod);
methodConfig.setOnthrow(onthrow);
methodConfig.setOnthrowMethod(onthrowMethod);
methodConfig.setReturn(isReturn);
methodConfig.setService(service);
methodConfig.setServiceId(serviceId);
methodConfig.setSticky(sticky);
methodConfig.setReliable(reliable);
methodConfig.setStat(stat);
methodConfig.setRetry(retry);
return methodConfig;
}
@Override
protected MethodBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ConfigCenterConfig;
import java.util.Map;
/**
* This is a builder for build {@link ConfigCenterConfig}.
*
* @since 2.7
*/
public class ConfigCenterBuilder extends AbstractBuilder<ConfigCenterConfig, ConfigCenterBuilder> {
private String protocol;
private String address;
private String cluster;
private String namespace = "dubbo";
private String group = "dubbo";
private String username;
private String password;
private Long timeout = 3000L;
private Boolean highestPriority = true;
private Boolean check = true;
private String configFile = "dubbo.properties";
private String appConfigFile;
private Map<String, String> parameters;
public static ConfigCenterBuilder newBuilder() {
return new ConfigCenterBuilder();
}
public ConfigCenterBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public ConfigCenterBuilder address(String address) {
this.address = address;
return getThis();
}
public ConfigCenterBuilder cluster(String cluster) {
this.cluster = cluster;
return getThis();
}
public ConfigCenterBuilder namespace(String namespace) {
this.namespace = namespace;
return getThis();
}
public ConfigCenterBuilder group(String group) {
this.group = group;
return getThis();
}
public ConfigCenterBuilder username(String username) {
this.username = username;
return getThis();
}
public ConfigCenterBuilder password(String password) {
this.password = password;
return getThis();
}
public ConfigCenterBuilder timeout(Long timeout) {
this.timeout = timeout;
return getThis();
}
public ConfigCenterBuilder highestPriority(Boolean highestPriority) {
this.highestPriority = highestPriority;
return getThis();
}
public ConfigCenterBuilder check(Boolean check) {
this.check = check;
return getThis();
}
public ConfigCenterBuilder configFile(String configFile) {
this.configFile = configFile;
return getThis();
}
public ConfigCenterBuilder appConfigFile(String appConfigFile) {
this.appConfigFile = appConfigFile;
return getThis();
}
public ConfigCenterBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(this.parameters, appendParameters);
return getThis();
}
public ConfigCenterBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(this.parameters, key, value);
return getThis();
}
@Override
public ConfigCenterConfig build() {
ConfigCenterConfig configCenter = new ConfigCenterConfig();
super.build(configCenter);
configCenter.setProtocol(protocol);
configCenter.setAddress(address);
configCenter.setCluster(cluster);
configCenter.setNamespace(namespace);
configCenter.setGroup(group);
configCenter.setUsername(username);
configCenter.setPassword(password);
configCenter.setTimeout(timeout);
configCenter.setHighestPriority(highestPriority);
configCenter.setCheck(check);
configCenter.setConfigFile(configFile);
configCenter.setAppConfigFile(appConfigFile);
configCenter.setParameters(parameters);
return configCenter;
}
@Override
protected ConfigCenterBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ProviderConfig;
/**
* This is a builder for build {@link ProviderConfig}.
*
* @since 2.7
*/
public class ProviderBuilder extends AbstractServiceBuilder<ProviderConfig, ProviderBuilder> {
/**
* Service ip addresses (used when there are multiple network cards available)
*/
private String host;
/**
* Service port
*/
private Integer port;
/**
* Context path
*/
private String contextpath;
/**
* Thread pool
*/
private String threadpool;
/**
* Thread pool name
*/
private String threadname;
/**
* Thread pool size (fixed size)
*/
private Integer threads;
/**
* IO thread pool size (fixed size)
*/
private Integer iothreads;
/**
* Thread pool keepAliveTime, default unit TimeUnit.MILLISECONDS
*/
private Integer alive;
/**
* Thread pool queue length
*/
private Integer queues;
/**
* Max acceptable connections
*/
private Integer accepts;
/**
* Protocol codec
*/
private String codec;
/**
* The serialization charset
*/
private String charset;
/**
* Payload max length
*/
private Integer payload;
/**
* The network io buffer size
*/
private Integer buffer;
/**
* Transporter
*/
private String transporter;
/**
* How information gets exchanged
*/
private String exchanger;
/**
* Thread dispatching mode
*/
private String dispatcher;
/**
* Networker
*/
private String networker;
/**
* The server-side implementation model of the protocol
*/
private String server;
/**
* The client-side implementation model of the protocol
*/
private String client;
/**
* Supported telnet commands, separated with comma.
*/
private String telnet;
/**
* Command line prompt
*/
private String prompt;
/**
* Status check
*/
private String status;
/**
* Wait time when stop
*/
private Integer wait;
/**
* Whether to use the default protocol
*/
private Boolean isDefault;
public static ProviderBuilder newBuilder() {
return new ProviderBuilder();
}
public ProviderBuilder host(String host) {
this.host = host;
return getThis();
}
public ProviderBuilder port(Integer port) {
this.port = port;
return getThis();
}
public ProviderBuilder contextPath(String contextPath) {
this.contextpath = contextPath;
return getThis();
}
public ProviderBuilder threadPool(String threadPool) {
this.threadpool = threadPool;
return getThis();
}
public ProviderBuilder threadName(String threadName) {
this.threadname = threadName;
return getThis();
}
public ProviderBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ProviderBuilder ioThreads(Integer ioThreads) {
this.iothreads = ioThreads;
return getThis();
}
public ProviderBuilder alive(Integer alive) {
this.alive = alive;
return getThis();
}
public ProviderBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ProviderBuilder accepts(Integer accepts) {
this.accepts = accepts;
return getThis();
}
public ProviderBuilder codec(String codec) {
this.codec = codec;
return getThis();
}
public ProviderBuilder charset(String charset) {
this.charset = charset;
return getThis();
}
public ProviderBuilder payload(Integer payload) {
this.payload = payload;
return getThis();
}
public ProviderBuilder buffer(Integer buffer) {
this.buffer = buffer;
return getThis();
}
public ProviderBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
public ProviderBuilder exchanger(String exchanger) {
this.exchanger = exchanger;
return getThis();
}
public ProviderBuilder dispatcher(String dispatcher) {
this.dispatcher = dispatcher;
return getThis();
}
public ProviderBuilder networker(String networker) {
this.networker = networker;
return getThis();
}
public ProviderBuilder server(String server) {
this.server = server;
return getThis();
}
public ProviderBuilder client(String client) {
this.client = client;
return getThis();
}
public ProviderBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
}
public ProviderBuilder prompt(String prompt) {
this.prompt = prompt;
return getThis();
}
public ProviderBuilder status(String status) {
this.status = status;
return getThis();
}
public ProviderBuilder wait(Integer wait) {
this.wait = wait;
return getThis();
}
public ProviderBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ProviderConfig build() {
ProviderConfig provider = new ProviderConfig();
super.build(provider);
provider.setHost(host);
provider.setPort(port);
provider.setContextpath(contextpath);
provider.setThreadpool(threadpool);
provider.setThreadname(threadname);
provider.setThreads(threads);
provider.setIothreads(iothreads);
provider.setAlive(alive);
provider.setQueues(queues);
provider.setAccepts(accepts);
provider.setCodec(codec);
provider.setPayload(payload);
provider.setCharset(charset);
provider.setBuffer(buffer);
provider.setTransporter(transporter);
provider.setExchanger(exchanger);
provider.setDispatcher(dispatcher);
provider.setNetworker(networker);
provider.setServer(server);
provider.setClient(client);
provider.setTelnet(telnet);
provider.setPrompt(prompt);
provider.setStatus(status);
provider.setWait(wait);
provider.setDefault(isDefault);
return provider;
}
@Override
protected ProviderBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.MonitorConfig;
import java.util.Map;
/**
* This is a builder for build {@link MonitorConfig}.
*
* @since 2.7
*/
public class MonitorBuilder extends AbstractBuilder<MonitorConfig, MonitorBuilder> {
/**
* The protocol of the monitor, if the value is registry, it will search the monitor address from the registry center,
* otherwise, it will directly connect to the monitor center
*/
private String protocol;
/**
* The monitor address
*/
private String address;
/**
* The monitor user name
*/
private String username;
/**
* The password
*/
private String password;
private String group;
private String version;
private String interval;
/**
* customized parameters
*/
private Map<String, String> parameters;
/**
* If it's default
*/
private Boolean isDefault;
public static MonitorBuilder newBuilder() {
return new MonitorBuilder();
}
public MonitorBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public MonitorBuilder address(String address) {
this.address = address;
return getThis();
}
public MonitorBuilder username(String username) {
this.username = username;
return getThis();
}
public MonitorBuilder password(String password) {
this.password = password;
return getThis();
}
public MonitorBuilder group(String group) {
this.group = group;
return getThis();
}
public MonitorBuilder version(String version) {
this.version = version;
return getThis();
}
public MonitorBuilder interval(String interval) {
this.interval = interval;
return getThis();
}
public MonitorBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public MonitorBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public MonitorBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
@Override
public MonitorConfig build() {
MonitorConfig monitorConfig = new MonitorConfig();
super.build(monitorConfig);
monitorConfig.setProtocol(protocol);
monitorConfig.setAddress(address);
monitorConfig.setUsername(username);
monitorConfig.setPassword(password);
monitorConfig.setGroup(group);
monitorConfig.setVersion(version);
monitorConfig.setInterval(interval);
monitorConfig.setParameters(parameters);
monitorConfig.setDefault(isDefault);
return monitorConfig;
}
@Override
protected MonitorBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractReferenceConfig;
/**
* AbstractBuilder
*
* @since 2.7
*/
public abstract class AbstractReferenceBuilder<
T extends AbstractReferenceConfig, B extends AbstractReferenceBuilder<T, B>>
extends AbstractInterfaceBuilder<T, B> {
/**
* Check if service provider exists, if not exists, it will be fast fail
*/
protected Boolean check;
/**
* Whether to eagle-init
*/
protected Boolean init;
/**
* Whether to use generic interface
*/
protected String generic;
/**
* Whether to find reference's instance from the current JVM
*/
protected Boolean injvm;
/**
* Lazy create connection
*/
protected Boolean lazy;
protected String reconnect;
protected Boolean sticky;
/**
* The remote service version the customer side will reference
*/
protected String version;
/**
* The remote service group the customer side will reference
*/
protected String group;
public B check(Boolean check) {
this.check = check;
return getThis();
}
public B init(Boolean init) {
this.init = init;
return getThis();
}
public B generic(String generic) {
this.generic = generic;
return getThis();
}
public B generic(Boolean generic) {
if (generic != null) {
this.generic = generic.toString();
} else {
this.generic = null;
}
return getThis();
}
/**
* @param injvm
* @see AbstractInterfaceBuilder#scope(String)
* @deprecated instead, use the parameter <b>scope</b> to judge if it's in jvm, scope=local
*/
@Deprecated
public B injvm(Boolean injvm) {
this.injvm = injvm;
return getThis();
}
public B lazy(Boolean lazy) {
this.lazy = lazy;
return getThis();
}
public B reconnect(String reconnect) {
this.reconnect = reconnect;
return getThis();
}
public B sticky(Boolean sticky) {
this.sticky = sticky;
return getThis();
}
public B version(String version) {
this.version = version;
return getThis();
}
public B group(String group) {
this.group = group;
return getThis();
}
@Override
public void build(T instance) {
super.build(instance);
if (check != null) {
instance.setCheck(check);
}
if (init != null) {
instance.setInit(init);
}
if (!StringUtils.isEmpty(generic)) {
instance.setGeneric(generic);
}
if (injvm != null) {
instance.setInjvm(injvm);
}
if (lazy != null) {
instance.setLazy(lazy);
}
if (!StringUtils.isEmpty(reconnect)) {
instance.setReconnect(reconnect);
}
if (sticky != null) {
instance.setSticky(sticky);
}
if (!StringUtils.isEmpty(version)) {
instance.setVersion(version);
}
if (!StringUtils.isEmpty(group)) {
instance.setGroup(group);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ProtocolConfig;
import java.util.Map;
/**
* This is a builder for build {@link ProtocolConfig}.
*
* @since 2.7
*/
public class ProtocolBuilder extends AbstractBuilder<ProtocolConfig, ProtocolBuilder> {
/**
* Protocol name
*/
private String name;
/**
* Service ip address (when there are multiple network cards available)
*/
private String host;
/**
* Service port
*/
private Integer port;
/**
* Context path
*/
private String contextpath;
/**
* Thread pool
*/
private String threadpool;
/**
* Thread pool core thread size
*/
private Integer corethreads;
/**
* Thread pool size (fixed size)
*/
private Integer threads;
/**
* IO thread pool size (fixed size)
*/
private Integer iothreads;
/**
* Thread pool's queue length
*/
private Integer queues;
/**
* Max acceptable connections
*/
private Integer accepts;
/**
* Protocol codec
*/
private String codec;
/**
* Serialization
*/
private String serialization;
/**
* Charset
*/
private String charset;
/**
* Payload max length
*/
private Integer payload;
/**
* Buffer size
*/
private Integer buffer;
/**
* Heartbeat interval
*/
private Integer heartbeat;
/**
* Access log
*/
private String accesslog;
/**
* Transporter
*/
private String transporter;
/**
* How information is exchanged
*/
private String exchanger;
/**
* Thread dispatch mode
*/
private String dispatcher;
/**
* Networker
*/
private String networker;
/**
* Sever impl
*/
private String server;
/**
* Client impl
*/
private String client;
/**
* Supported telnet commands, separated with comma.
*/
private String telnet;
/**
* Command line prompt
*/
private String prompt;
/**
* Status check
*/
private String status;
/**
* Whether to register
*/
private Boolean register;
/**
* whether it is a persistent connection
*/
// TODO add this to provider config
private Boolean keepAlive;
// TODO add this to provider config
private String optimizer;
/**
* The extension
*/
private String extension;
/**
* The customized parameters
*/
private Map<String, String> parameters;
private Boolean sslEnabled;
/*
* Extra Protocol for this service, using Port Unification Server
*/
private String extProtocol;
/**
* If it's default
*/
private Boolean isDefault;
public static ProtocolBuilder newBuilder() {
return new ProtocolBuilder();
}
public ProtocolBuilder id(String id) {
return super.id(id);
}
public ProtocolBuilder name(String name) {
this.name = name;
return getThis();
}
public ProtocolBuilder host(String host) {
this.host = host;
return getThis();
}
public ProtocolBuilder port(Integer port) {
this.port = port;
return getThis();
}
public ProtocolBuilder contextpath(String contextpath) {
this.contextpath = contextpath;
return getThis();
}
/**
* @param path
* @return ProtocolBuilder
* @see ProtocolBuilder#contextpath(String)
*/
@Deprecated
public ProtocolBuilder path(String path) {
this.contextpath = path;
return getThis();
}
public ProtocolBuilder threadpool(String threadpool) {
this.threadpool = threadpool;
return getThis();
}
public ProtocolBuilder corethreads(Integer corethreads) {
this.corethreads = corethreads;
return getThis();
}
public ProtocolBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ProtocolBuilder iothreads(Integer iothreads) {
this.iothreads = iothreads;
return getThis();
}
public ProtocolBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ProtocolBuilder accepts(Integer accepts) {
this.accepts = accepts;
return getThis();
}
public ProtocolBuilder codec(String codec) {
this.codec = codec;
return getThis();
}
public ProtocolBuilder serialization(String serialization) {
this.serialization = serialization;
return getThis();
}
public ProtocolBuilder charset(String charset) {
this.charset = charset;
return getThis();
}
public ProtocolBuilder payload(Integer payload) {
this.payload = payload;
return getThis();
}
public ProtocolBuilder buffer(Integer buffer) {
this.buffer = buffer;
return getThis();
}
public ProtocolBuilder heartbeat(Integer heartbeat) {
this.heartbeat = heartbeat;
return getThis();
}
public ProtocolBuilder accesslog(String accesslog) {
this.accesslog = accesslog;
return getThis();
}
public ProtocolBuilder transporter(String transporter) {
this.transporter = transporter;
return getThis();
}
public ProtocolBuilder exchanger(String exchanger) {
this.exchanger = exchanger;
return getThis();
}
public ProtocolBuilder dispatcher(String dispatcher) {
this.dispatcher = dispatcher;
return getThis();
}
/**
* @param dispather
* @return ProtocolBuilder
* @see ProtocolBuilder#dispatcher(String)
*/
@Deprecated
public ProtocolBuilder dispather(String dispather) {
this.dispatcher = dispather;
return getThis();
}
public ProtocolBuilder networker(String networker) {
this.networker = networker;
return getThis();
}
public ProtocolBuilder server(String server) {
this.server = server;
return getThis();
}
public ProtocolBuilder client(String client) {
this.client = client;
return getThis();
}
public ProtocolBuilder telnet(String telnet) {
this.telnet = telnet;
return getThis();
}
public ProtocolBuilder prompt(String prompt) {
this.prompt = prompt;
return getThis();
}
public ProtocolBuilder status(String status) {
this.status = status;
return getThis();
}
public ProtocolBuilder register(Boolean register) {
this.register = register;
return getThis();
}
public ProtocolBuilder keepAlive(Boolean keepAlive) {
this.keepAlive = keepAlive;
return getThis();
}
public ProtocolBuilder optimizer(String optimizer) {
this.optimizer = optimizer;
return getThis();
}
public ProtocolBuilder extension(String extension) {
this.extension = extension;
return getThis();
}
public ProtocolBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public ProtocolBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public ProtocolBuilder isSslEnabled(Boolean sslEnabled) {
this.sslEnabled = sslEnabled;
return getThis();
}
public ProtocolBuilder extProtocol(String extProtocol) {
this.extProtocol = extProtocol;
return getThis();
}
public ProtocolBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
@Override
public ProtocolConfig build() {
ProtocolConfig protocolConfig = new ProtocolConfig();
super.build(protocolConfig);
protocolConfig.setAccepts(accepts);
protocolConfig.setAccesslog(accesslog);
protocolConfig.setBuffer(buffer);
protocolConfig.setCharset(charset);
protocolConfig.setClient(client);
protocolConfig.setCodec(codec);
protocolConfig.setContextpath(contextpath);
protocolConfig.setCorethreads(corethreads);
protocolConfig.setDefault(isDefault);
protocolConfig.setDispatcher(dispatcher);
protocolConfig.setExchanger(exchanger);
protocolConfig.setExtension(extension);
protocolConfig.setHeartbeat(heartbeat);
protocolConfig.setHost(host);
protocolConfig.setIothreads(iothreads);
protocolConfig.setKeepAlive(keepAlive);
protocolConfig.setName(name);
protocolConfig.setNetworker(networker);
protocolConfig.setOptimizer(optimizer);
protocolConfig.setParameters(parameters);
protocolConfig.setPayload(payload);
protocolConfig.setPort(port);
protocolConfig.setPrompt(prompt);
protocolConfig.setQueues(queues);
protocolConfig.setRegister(register);
protocolConfig.setSerialization(serialization);
protocolConfig.setServer(server);
protocolConfig.setStatus(status);
protocolConfig.setTelnet(telnet);
protocolConfig.setThreadpool(threadpool);
protocolConfig.setThreads(threads);
protocolConfig.setTransporter(transporter);
protocolConfig.setSslEnabled(sslEnabled);
protocolConfig.setExtProtocol(extProtocol);
return protocolConfig;
}
@Override
protected ProtocolBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/InternalServiceConfigBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/InternalServiceConfigBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY;
public class InternalServiceConfigBuilder<T> {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private static final Set<String> ACCEPTABLE_PROTOCOL =
Stream.of("dubbo", "tri", "injvm").collect(Collectors.toSet());
private final ApplicationModel applicationModel;
private String protocol;
private Integer port;
private String registryId;
private Class<T> interfaceClass;
private Executor executor;
private T ref;
private String version;
private InternalServiceConfigBuilder(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public static <T> InternalServiceConfigBuilder<T> newBuilder(ApplicationModel applicationModel) {
return new InternalServiceConfigBuilder<>(applicationModel);
}
public InternalServiceConfigBuilder<T> interfaceClass(Class<T> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public InternalServiceConfigBuilder<T> executor(Executor executor) {
this.executor = executor;
return getThis();
}
public InternalServiceConfigBuilder<T> ref(T ref) {
this.ref = ref;
return getThis();
}
public InternalServiceConfigBuilder<T> registryId(String registryId) {
this.registryId = registryId;
return getThis();
}
public InternalServiceConfigBuilder<T> protocol(String protocol, String key) {
if (StringUtils.isEmpty(protocol) && StringUtils.isNotBlank(key)) {
Map<String, String> params = getApplicationConfig().getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
protocol = params.get(key);
}
}
this.protocol = StringUtils.isNotEmpty(protocol) ? protocol : getRelatedOrDefaultProtocol();
return getThis();
}
public InternalServiceConfigBuilder<T> version(String version) {
this.version = version;
return getThis();
}
/**
* Get other configured protocol from environment in priority order. If get nothing, use default dubbo.
*
* @return
*/
private String getRelatedOrDefaultProtocol() {
String protocol = "";
// <dubbo:protocol/>
if (StringUtils.isEmpty(protocol)) {
Collection<ProtocolConfig> protocols =
applicationModel.getApplicationConfigManager().getProtocols();
if (CollectionUtils.isNotEmpty(protocols)) {
protocol = protocols.stream()
.map(ProtocolConfig::getName)
.filter(StringUtils::isNotEmpty)
.filter(p -> ACCEPTABLE_PROTOCOL.contains(p))
.findFirst()
.orElse("");
}
}
// <dubbo:provider/>
List<ModuleModel> moduleModels = applicationModel.getPubModuleModels();
if (StringUtils.isEmpty(protocol)) {
Stream<ProviderConfig> providerConfigStream = moduleModels.stream()
.map(ModuleModel::getConfigManager)
.map(ModuleConfigManager::getProviders)
.filter(CollectionUtils::isNotEmpty)
.flatMap(Collection::stream);
protocol = providerConfigStream
.filter((providerConfig) -> providerConfig.getProtocol() != null
|| CollectionUtils.isNotEmpty(providerConfig.getProtocols()))
.map(providerConfig -> {
if (providerConfig.getProtocol() != null
&& StringUtils.isNotEmpty(
providerConfig.getProtocol().getName())) {
return providerConfig.getProtocol().getName();
} else {
return providerConfig.getProtocols().stream()
.map(ProtocolConfig::getName)
.filter(StringUtils::isNotEmpty)
.findFirst()
.orElse("");
}
})
.filter(StringUtils::isNotEmpty)
.filter(p -> ACCEPTABLE_PROTOCOL.contains(p))
.findFirst()
.orElse("");
}
// <dubbo:application/>
if (StringUtils.isEmpty(protocol)) {
protocol = getApplicationConfig().getProtocol();
if (StringUtils.isEmpty(protocol)) {
Map<String, String> params = getApplicationConfig().getParameters();
if (CollectionUtils.isNotEmptyMap(params)) {
protocol = params.get(APPLICATION_PROTOCOL_KEY);
}
}
}
// <dubbo:consumer/>
if (StringUtils.isEmpty(protocol)) {
protocol = moduleModels.stream()
.map(ModuleModel::getConfigManager)
.map(ModuleConfigManager::getConsumers)
.filter(CollectionUtils::isNotEmpty)
.flatMap(Collection::stream)
.map(ConsumerConfig::getProtocol)
.filter(StringUtils::isNotEmpty)
.filter(p -> ACCEPTABLE_PROTOCOL.contains(p))
.findFirst()
.orElse("");
}
return StringUtils.isNotEmpty(protocol) && ACCEPTABLE_PROTOCOL.contains(protocol) ? protocol : DUBBO_PROTOCOL;
}
public InternalServiceConfigBuilder<T> protocol(String protocol) {
this.protocol(protocol, null);
return getThis();
}
public InternalServiceConfigBuilder<T> port(Integer specPort) {
return port(specPort, null);
}
public InternalServiceConfigBuilder<T> port(Integer specPort, String key) {
Assert.notEmptyString(this.protocol, "export protocol is null");
Assert.notNull(this.interfaceClass, "export interfaceClass is null");
if (specPort != null) {
this.port = specPort;
return getThis();
}
Map<String, String> params = getApplicationConfig().getParameters();
if (CollectionUtils.isNotEmptyMap(params) && StringUtils.isNotBlank(key)) {
String rawPort = getApplicationConfig().getParameters().get(key);
if (StringUtils.isNotEmpty(rawPort)) {
specPort = Integer.parseInt(rawPort);
}
}
if (specPort == null || specPort < -1) {
try {
if (logger.isInfoEnabled()) {
logger.info(interfaceClass.getName()
+ "Service Port hasn't been set will use default protocol defined in protocols.");
}
Protocol protocol =
applicationModel.getExtensionLoader(Protocol.class).getExtension(this.protocol);
if (protocol != null && protocol.getServers() != null) {
Iterator<ProtocolServer> it = protocol.getServers().iterator();
// export service may export before normal service export, it.hasNext() will return false.
// so need use specified protocol port.
if (it.hasNext()) {
ProtocolServer server = it.next();
String rawPort = server.getUrl().getParameter(BIND_PORT_KEY);
if (rawPort == null) {
String addr = server.getAddress();
rawPort = addr.substring(addr.indexOf(":") + 1);
}
this.port = Integer.parseInt(rawPort);
} else {
ProtocolConfig specifiedProtocolConfig = getProtocolConfig();
if (specifiedProtocolConfig != null) {
Integer protocolPort = specifiedProtocolConfig.getPort();
if (null != protocolPort && protocolPort != -1) {
this.port = protocolPort;
}
}
}
}
} catch (Exception e) {
logger.error(
INTERNAL_ERROR,
"invalid specified " + port + " port, error " + e.getMessage(),
"",
"Failed to find any valid protocol, will use random port to export service.",
e);
}
}
if (this.port == null) {
this.port = -1;
}
return getThis();
}
private ProtocolConfig getProtocolConfig() {
return applicationModel
.getApplicationConfigManager()
.getProtocol(protocol)
.orElse(null);
}
public ServiceConfig<T> build(Consumer<ServiceConfig<T>> configConsumer) {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName(this.protocol);
protocolConfig.setPort(this.port);
this.nullAssert();
logger.info("[SERVICE_PUBLISH] [METADATA_REGISTER] Using " + this.protocol + " protocol to export "
+ interfaceClass.getName() + " service on port " + protocolConfig.getPort());
applicationModel
.getApplicationConfigManager()
.getProtocol(this.protocol)
.ifPresent(p -> {
protocolConfig.mergeProtocol(p);
// clear extra protocols possibly merged from global ProtocolConfig
protocolConfig.setExtProtocol(null);
});
ApplicationConfig applicationConfig = getApplicationConfig();
ServiceConfig<T> serviceConfig = new ServiceConfig<>();
serviceConfig.setScopeModel(applicationModel.getInternalModule());
serviceConfig.setApplication(applicationConfig);
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.refresh();
registryConfig.setNeedRefresh(false);
registryConfig.setId(this.registryId);
registryConfig.setAddress("N/A");
registryConfig.setScopeModel(this.applicationModel);
serviceConfig.setRegistry(registryConfig);
serviceConfig.setRegister(false);
serviceConfig.setProtocol(protocolConfig);
serviceConfig.setDelay(0);
serviceConfig.setInterface(interfaceClass);
serviceConfig.setRef(this.ref);
serviceConfig.setGroup(applicationConfig.getName());
if (StringUtils.isNotEmpty(version)) {
serviceConfig.setVersion(version);
} else {
serviceConfig.setVersion("1.0.0");
}
serviceConfig.setFilter("-default");
serviceConfig.setExecutor(executor);
if (null != configConsumer) {
configConsumer.accept(serviceConfig);
}
return serviceConfig;
}
public ServiceConfig<T> build() {
return build(null);
}
private void nullAssert() {
Assert.notNull(port, "export service port is null");
Assert.notNull(protocol, "export service protocol is null");
Assert.notNull(interfaceClass, "export service interfaceClass is null");
Assert.notNull(ref, "export service ref is null");
Assert.notNull(registryId, "export service registryId is null");
}
protected InternalServiceConfigBuilder<T> getThis() {
return this;
}
private ApplicationConfig getApplicationConfig() {
return applicationModel.getApplicationConfigManager().getApplicationOrElseThrow();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.ServiceConfigBase;
import java.util.ArrayList;
import java.util.List;
/**
* This is a builder for build {@link ServiceConfigBase}.
*
* @since 2.7
*/
public class ServiceBuilder<U> extends AbstractServiceBuilder<ServiceConfig<U>, ServiceBuilder<U>> {
/**
* The interface name of the exported service
*/
private String interfaceName;
/**
* The interface class of the exported service
*/
private Class<?> interfaceClass;
/**
* The reference of the interface implementation
*/
private U ref;
/**
* The service name
*/
private String path;
/**
* The method configuration
*/
private List<MethodConfig> methods;
/**
* The provider configuration
*/
private ProviderConfig provider;
/**
* The providerIds
*/
private String providerIds;
/**
* whether it is a GenericService
*/
private String generic;
public static <T> ServiceBuilder<T> newBuilder() {
return new ServiceBuilder<>();
}
public ServiceBuilder<U> id(String id) {
return super.id(id);
}
public ServiceBuilder<U> interfaceName(String interfaceName) {
this.interfaceName = interfaceName;
return getThis();
}
public ServiceBuilder<U> interfaceClass(Class<?> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public ServiceBuilder<U> ref(U ref) {
this.ref = ref;
return getThis();
}
public ServiceBuilder<U> path(String path) {
this.path = path;
return getThis();
}
public ServiceBuilder<U> addMethod(MethodConfig method) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.add(method);
return getThis();
}
public ServiceBuilder<U> addMethods(List<? extends MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
}
public ServiceBuilder<U> provider(ProviderConfig provider) {
this.provider = provider;
return getThis();
}
public ServiceBuilder<U> providerIds(String providerIds) {
this.providerIds = providerIds;
return getThis();
}
public ServiceBuilder<U> generic(String generic) {
this.generic = generic;
return getThis();
}
// @Override
// public ServiceBuilder<U> mock(String mock) {
// throw new IllegalArgumentException("mock doesn't support on provider side");
// }
// @Override
// public ServiceBuilder<U> mock(Boolean mock) {
// throw new IllegalArgumentException("mock doesn't support on provider side");
// }
@Override
public ServiceConfig<U> build() {
ServiceConfig<U> serviceConfig = new ServiceConfig<>();
super.build(serviceConfig);
serviceConfig.setInterface(interfaceName);
serviceConfig.setInterface(interfaceClass);
serviceConfig.setRef(ref);
serviceConfig.setPath(path);
serviceConfig.setMethods(methods);
serviceConfig.setProvider(provider);
serviceConfig.setProviderIds(providerIds);
serviceConfig.setGeneric(generic);
return serviceConfig;
}
@Override
protected ServiceBuilder<U> getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MetricsBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MetricsBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.nested.AggregationConfig;
import org.apache.dubbo.config.nested.HistogramConfig;
import org.apache.dubbo.config.nested.PrometheusConfig;
/**
* This is a builder for build {@link MetricsConfig}.
*/
public class MetricsBuilder extends AbstractBuilder<MetricsConfig, MetricsBuilder> {
private String protocol;
/**
* Enable jvm metrics when collecting.
*/
private Boolean enableJvm;
/**
* Enable threadpool metrics when collecting.
*/
private Boolean enableThreadpool;
/**
* Enable registry metrics.
*/
private Boolean enableRegistry;
/**
* Enable metadata metrics.
*/
private Boolean enableMetadata;
/**
* Export metrics service.
*/
private Boolean exportMetricsService;
/**
* Enable metrics init.
*/
private Boolean enableMetricsInit;
/**
* Enable collector sync.
*/
private Boolean enableCollectorSync;
/**
* Collector sync period.
*/
private Integer collectorSyncPeriod;
/**
* The prometheus metrics config
*/
private PrometheusConfig prometheus;
/**
* The metrics aggregation config
*/
private AggregationConfig aggregation;
private HistogramConfig histogram;
private String exportServiceProtocol;
private Integer exportServicePort;
/**
* Decide whether to use the global registry of the micrometer.
*/
private Boolean useGlobalRegistry;
/**
* Enable rpc metrics.
*/
private Boolean enableRpc;
/**
* The level of the metrics, the value can be "SERVICE", "METHOD", default is method.
*/
private String rpcLevel;
public static MetricsBuilder newBuilder() {
return new MetricsBuilder();
}
public MetricsBuilder protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
public MetricsBuilder enableJvm(Boolean enableJvm) {
this.enableJvm = enableJvm;
return getThis();
}
public MetricsBuilder enableThreadPool(Boolean enableThreadPool) {
this.enableThreadpool = enableThreadPool;
return getThis();
}
public MetricsBuilder enableRegistry(Boolean enableRegistry) {
this.enableRegistry = enableRegistry;
return getThis();
}
public MetricsBuilder enableMetadata(Boolean enableMetadata) {
this.enableMetadata = enableMetadata;
return getThis();
}
public MetricsBuilder exportMetricsService(Boolean exportMetricsService) {
this.exportMetricsService = exportMetricsService;
return getThis();
}
public MetricsBuilder enableMetricsInit(Boolean enableMetricsInit) {
this.enableMetricsInit = enableMetricsInit;
return getThis();
}
public MetricsBuilder enableCollectorSync(Boolean enableCollectorSync) {
this.enableCollectorSync = enableCollectorSync;
return getThis();
}
public MetricsBuilder collectorSyncPeriod(Integer collectorSyncPeriod) {
this.collectorSyncPeriod = collectorSyncPeriod;
return getThis();
}
public MetricsBuilder prometheus(PrometheusConfig prometheus) {
this.prometheus = prometheus;
return getThis();
}
public MetricsBuilder aggregation(AggregationConfig aggregation) {
this.aggregation = aggregation;
return getThis();
}
public MetricsBuilder histogram(HistogramConfig histogram) {
this.histogram = histogram;
return getThis();
}
public MetricsBuilder exportServiceProtocol(String exportServiceProtocol) {
this.exportServiceProtocol = exportServiceProtocol;
return getThis();
}
public MetricsBuilder exportServicePort(Integer exportServicePort) {
this.exportServicePort = exportServicePort;
return getThis();
}
public MetricsBuilder useGlobalRegistry(Boolean useGlobalRegistry) {
this.useGlobalRegistry = useGlobalRegistry;
return getThis();
}
public MetricsBuilder enableRpc(Boolean enableRpc) {
this.enableRpc = enableRpc;
return getThis();
}
public MetricsBuilder rpcLevel(String rpcLevel) {
this.rpcLevel = rpcLevel;
return getThis();
}
@Override
public MetricsConfig build() {
MetricsConfig metrics = new MetricsConfig();
super.build(metrics);
metrics.setProtocol(protocol);
metrics.setEnableJvm(enableJvm);
metrics.setEnableThreadpool(enableThreadpool);
metrics.setEnableRegistry(enableRegistry);
metrics.setEnableMetadata(enableMetadata);
metrics.setExportMetricsService(exportMetricsService);
metrics.setEnableMetricsInit(enableMetricsInit);
metrics.setEnableCollectorSync(enableCollectorSync);
metrics.setCollectorSyncPeriod(collectorSyncPeriod);
metrics.setPrometheus(prometheus);
metrics.setAggregation(aggregation);
metrics.setHistogram(histogram);
metrics.setExportServiceProtocol(exportServiceProtocol);
metrics.setExportServicePort(exportServicePort);
metrics.setUseGlobalRegistry(useGlobalRegistry);
metrics.setEnableRpc(enableRpc);
metrics.setRpcLevel(rpcLevel);
return metrics;
}
@Override
protected MetricsBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.MetadataReportConfig;
import java.util.Map;
/**
* This is a builder for build {@link MetadataReportConfig}.
*
* @since 2.7
*/
public class MetadataReportBuilder extends AbstractBuilder<MetadataReportConfig, MetadataReportBuilder> {
/**
* Register center address
*/
private String address;
/**
* Username to login register center
*/
private String username;
/**
* Password to login register center
*/
private String password;
/**
* Request timeout in milliseconds for register center
*/
private Integer timeout;
/**
* The group the metadata in . It is the same as registry
*/
private String group;
/**
* Customized parameters
*/
private Map<String, String> parameters;
private Integer retryTimes;
private Integer retryPeriod;
/**
* By default the metadata store will store full metadata repeatedly every day .
*/
private Boolean cycleReport;
/**
* Sync report, default async
*/
private Boolean syncReport;
/**
* Decide the behaviour when initial connection try fails,
* 'true' means interrupt the whole process once fail.
* The default value is true
*/
private Boolean check;
public static MetadataReportBuilder newBuilder() {
return new MetadataReportBuilder();
}
public MetadataReportBuilder address(String address) {
this.address = address;
return getThis();
}
public MetadataReportBuilder username(String username) {
this.username = username;
return getThis();
}
public MetadataReportBuilder password(String password) {
this.password = password;
return getThis();
}
public MetadataReportBuilder timeout(Integer timeout) {
this.timeout = timeout;
return getThis();
}
public MetadataReportBuilder group(String group) {
this.group = group;
return getThis();
}
public MetadataReportBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(this.parameters, appendParameters);
return getThis();
}
public MetadataReportBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(this.parameters, key, value);
return getThis();
}
public MetadataReportBuilder retryTimes(Integer retryTimes) {
this.retryTimes = retryTimes;
return getThis();
}
public MetadataReportBuilder retryPeriod(Integer retryPeriod) {
this.retryPeriod = retryPeriod;
return getThis();
}
public MetadataReportBuilder cycleReport(Boolean cycleReport) {
this.cycleReport = cycleReport;
return getThis();
}
public MetadataReportBuilder syncReport(Boolean syncReport) {
this.syncReport = syncReport;
return getThis();
}
public MetadataReportBuilder check(Boolean check) {
this.check = check;
return getThis();
}
@Override
public MetadataReportConfig build() {
MetadataReportConfig metadataReport = new MetadataReportConfig();
super.build(metadataReport);
metadataReport.setAddress(address);
metadataReport.setUsername(username);
metadataReport.setPassword(password);
metadataReport.setTimeout(timeout);
metadataReport.setGroup(group);
metadataReport.setParameters(parameters);
metadataReport.setRetryTimes(retryTimes);
metadataReport.setRetryPeriod(retryPeriod);
metadataReport.setCycleReport(cycleReport);
metadataReport.setSyncReport(syncReport);
metadataReport.setCheck(check);
return metadataReport;
}
@Override
protected MetadataReportBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.apache.dubbo.config.Constants.PRODUCTION_ENVIRONMENT;
/**
* This is a builder for build {@link ApplicationConfig}.
* @since 2.7
*/
public class ApplicationBuilder extends AbstractBuilder<ApplicationConfig, ApplicationBuilder> {
private String name;
private String metadata;
private String version;
private String owner;
private String organization;
private String architecture;
private String environment = PRODUCTION_ENVIRONMENT;
private String compiler;
private String logger;
private List<RegistryConfig> registries;
private String registryIds;
private MonitorConfig monitor;
private Boolean isDefault;
private String dumpDirectory;
private Boolean qosEnable;
private Integer qosPort;
private Boolean qosAcceptForeignIp;
private Map<String, String> parameters;
private String shutwait;
private Integer metadataServicePort;
private String livenessProbe;
private String readinessProbe;
private String startupProbe;
public static ApplicationBuilder newBuilder() {
return new ApplicationBuilder();
}
public ApplicationBuilder name(String name) {
this.name = name;
return getThis();
}
public ApplicationBuilder metadata(String metadata) {
this.metadata = metadata;
return getThis();
}
public ApplicationBuilder version(String version) {
this.version = version;
return getThis();
}
public ApplicationBuilder owner(String owner) {
this.owner = owner;
return getThis();
}
public ApplicationBuilder organization(String organization) {
this.organization = organization;
return getThis();
}
public ApplicationBuilder architecture(String architecture) {
this.architecture = architecture;
return getThis();
}
public ApplicationBuilder environment(String environment) {
this.environment = environment;
return getThis();
}
public ApplicationBuilder compiler(String compiler) {
this.compiler = compiler;
return getThis();
}
public ApplicationBuilder logger(String logger) {
this.logger = logger;
return getThis();
}
public ApplicationBuilder addRegistry(RegistryConfig registry) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.add(registry);
return getThis();
}
public ApplicationBuilder addRegistries(List<? extends RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
}
public ApplicationBuilder registryIds(String registryIds) {
this.registryIds = registryIds;
return getThis();
}
public ApplicationBuilder monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
}
public ApplicationBuilder monitor(String monitor) {
this.monitor = new MonitorConfig(monitor);
return getThis();
}
public ApplicationBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ApplicationBuilder dumpDirectory(String dumpDirectory) {
this.dumpDirectory = dumpDirectory;
return getThis();
}
public ApplicationBuilder qosEnable(Boolean qosEnable) {
this.qosEnable = qosEnable;
return getThis();
}
public ApplicationBuilder qosPort(Integer qosPort) {
this.qosPort = qosPort;
return getThis();
}
public ApplicationBuilder qosAcceptForeignIp(Boolean qosAcceptForeignIp) {
this.qosAcceptForeignIp = qosAcceptForeignIp;
return getThis();
}
public ApplicationBuilder shutwait(String shutwait) {
this.shutwait = shutwait;
return getThis();
}
public ApplicationBuilder appendParameter(String key, String value) {
this.parameters = appendParameter(parameters, key, value);
return getThis();
}
public ApplicationBuilder appendParameters(Map<String, String> appendParameters) {
this.parameters = appendParameters(parameters, appendParameters);
return getThis();
}
public ApplicationBuilder metadataServicePort(Integer metadataServicePort) {
this.metadataServicePort = metadataServicePort;
return getThis();
}
public ApplicationBuilder livenessProbe(String livenessProbe) {
this.livenessProbe = livenessProbe;
return getThis();
}
public ApplicationBuilder readinessProbe(String readinessProbe) {
this.readinessProbe = readinessProbe;
return getThis();
}
public ApplicationBuilder startupProbe(String startupProbe) {
this.startupProbe = startupProbe;
return getThis();
}
public ApplicationConfig build() {
ApplicationConfig config = new ApplicationConfig();
super.build(config);
config.setName(name);
config.setMetadataType(metadata);
config.setVersion(this.version);
config.setOwner(this.owner);
config.setOrganization(this.organization);
config.setArchitecture(this.architecture);
config.setEnvironment(this.environment);
config.setCompiler(this.compiler);
config.setLogger(this.logger);
config.setRegistries(this.registries);
config.setRegistryIds(this.registryIds);
config.setMonitor(this.monitor);
config.setDefault(this.isDefault);
config.setDumpDirectory(this.dumpDirectory);
config.setQosEnable(this.qosEnable);
config.setQosPort(this.qosPort);
config.setQosAcceptForeignIp(this.qosAcceptForeignIp);
config.setMetadataServicePort(this.metadataServicePort);
config.setLivenessProbe(this.livenessProbe);
config.setReadinessProbe(this.readinessProbe);
config.setStartupProbe(this.startupProbe);
config.setParameters(this.parameters);
if (!StringUtils.isEmpty(shutwait)) {
config.setShutwait(shutwait);
}
return config;
}
@Override
protected ApplicationBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.ReferenceConfigBase;
import java.util.ArrayList;
import java.util.List;
import static org.apache.dubbo.common.utils.StringUtils.toCommaDelimitedString;
/**
* This is a builder for build {@link ReferenceConfigBase}.
*
* @since 2.7
*/
public class ReferenceBuilder<T> extends AbstractReferenceBuilder<ReferenceConfig<T>, ReferenceBuilder<T>> {
/**
* The interface name of the reference service
*/
private String interfaceName;
/**
* The interface class of the reference service
*/
private Class<?> interfaceClass;
/**
* client type
*/
private String client;
/**
* The url for peer-to-peer invocation
*/
private String url;
/**
* The method configs
*/
private List<MethodConfig> methods;
/**
* The consumer config (default)
*/
private ConsumerConfig consumer;
/**
* Only the service provider of the specified protocol is invoked, and other protocols are ignored.
*/
private String protocol;
/**
* The string presenting the service names that the Dubbo interface subscribed
*
* @since 2.7.8
*/
private String services;
public static <T> ReferenceBuilder<T> newBuilder() {
return new ReferenceBuilder<>();
}
public ReferenceBuilder<T> id(String id) {
return super.id(id);
}
public ReferenceBuilder<T> interfaceName(String interfaceName) {
this.interfaceName = interfaceName;
return getThis();
}
public ReferenceBuilder<T> interfaceClass(Class<?> interfaceClass) {
this.interfaceClass = interfaceClass;
return getThis();
}
public ReferenceBuilder<T> client(String client) {
this.client = client;
return getThis();
}
public ReferenceBuilder<T> url(String url) {
this.url = url;
return getThis();
}
public ReferenceBuilder<T> addMethods(List<MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
}
public ReferenceBuilder<T> addMethod(MethodConfig method) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.add(method);
return getThis();
}
public ReferenceBuilder<T> consumer(ConsumerConfig consumer) {
this.consumer = consumer;
return getThis();
}
public ReferenceBuilder<T> protocol(String protocol) {
this.protocol = protocol;
return getThis();
}
/**
* @param service one service name
* @param otherServices other service names
* @return {@link ReferenceBuilder}
* @since 2.7.8
*/
public ReferenceBuilder<T> services(String service, String... otherServices) {
this.services = toCommaDelimitedString(service, otherServices);
return getThis();
}
@Override
public ReferenceConfig<T> build() {
ReferenceConfig<T> reference = new ReferenceConfig<>();
super.build(reference);
reference.setInterface(interfaceName);
if (interfaceClass != null) {
reference.setInterface(interfaceClass);
}
reference.setClient(client);
reference.setUrl(url);
reference.setMethods(methods);
reference.setConsumer(consumer);
reference.setProtocol(protocol);
// @since 2.7.8
reference.setServices(services);
return reference;
}
@Override
protected ReferenceBuilder<T> getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractConfig;
import java.util.HashMap;
import java.util.Map;
/**
* AbstractBuilder
*
* @param <C> The type of {@link AbstractConfig Config}
* @param <B> The type of {@link AbstractBuilder Builder}
* @since 2.7
*/
public abstract class AbstractBuilder<C extends AbstractConfig, B extends AbstractBuilder> {
/**
* The config id
*/
protected String id;
public B id(String id) {
this.id = id;
return getThis();
}
protected abstract B getThis();
protected static Map<String, String> appendParameter(Map<String, String> parameters, String key, String value) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put(key, value);
return parameters;
}
protected static Map<String, String> appendParameters(
Map<String, String> parameters, Map<String, String> appendParameters) {
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.putAll(appendParameters);
return parameters;
}
protected void build(C instance) {
if (!StringUtils.isEmpty(id)) {
instance.setId(id);
}
}
/**
* Build an instance of {@link AbstractConfig config}
*
* @return an instance of {@link AbstractConfig config}
*/
public abstract C build();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ConsumerConfig;
/**
* This is a builder for build {@link ConsumerConfig}.
*
* @since 2.7
*/
public class ConsumerBuilder extends AbstractReferenceBuilder<ConsumerConfig, ConsumerBuilder> {
/**
* Whether to use the default protocol
*/
private Boolean isDefault;
/**
* Networking framework client uses: netty, mina, etc.
*/
private String client;
/**
* Consumer thread pool type: cached, fixed, limit, eager
*/
private String threadpool;
/**
* Consumer threadpool core thread size
*/
private Integer corethreads;
/**
* Consumer threadpool thread size
*/
private Integer threads;
/**
* Consumer threadpool queue size
*/
private Integer queues;
/**
* By default, a TCP long-connection communication is shared between the consumer process and the provider process.
* This property can be set to share multiple TCP long-connection communications. Note that only the dubbo protocol takes effect.
*/
private Integer shareconnections;
/**
* Url Merge Processor
* Used to customize the URL merge of consumer and provider
*/
private String urlMergeProcessor;
public static ConsumerBuilder newBuilder() {
return new ConsumerBuilder();
}
public ConsumerBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
public ConsumerBuilder client(String client) {
this.client = client;
return getThis();
}
public ConsumerBuilder threadPool(String threadPool) {
this.threadpool = threadPool;
return getThis();
}
public ConsumerBuilder coreThreads(Integer coreThreads) {
this.corethreads = coreThreads;
return getThis();
}
public ConsumerBuilder threads(Integer threads) {
this.threads = threads;
return getThis();
}
public ConsumerBuilder queues(Integer queues) {
this.queues = queues;
return getThis();
}
public ConsumerBuilder shareConnections(Integer shareConnections) {
this.shareconnections = shareConnections;
return getThis();
}
public ConsumerBuilder urlMergeProcessor(String urlMergeProcessor) {
this.urlMergeProcessor = urlMergeProcessor;
return getThis();
}
@Override
public ConsumerConfig build() {
ConsumerConfig consumer = new ConsumerConfig();
super.build(consumer);
consumer.setDefault(isDefault);
consumer.setClient(client);
consumer.setThreadpool(threadpool);
consumer.setCorethreads(corethreads);
consumer.setThreads(threads);
consumer.setQueues(queues);
consumer.setShareconnections(shareconnections);
consumer.setUrlMergeProcessor(urlMergeProcessor);
return consumer;
}
@Override
protected ConsumerBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilder.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.bootstrap.builders;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.util.ArrayList;
import java.util.List;
/**
* This is a builder for build {@link ModuleConfig}.
*
* @since 2.7
*/
public class ModuleBuilder extends AbstractBuilder<ModuleConfig, ModuleBuilder> {
/**
* Module name
*/
private String name;
/**
* Module version
*/
private String version;
/**
* Module owner
*/
private String owner;
/**
* Module's organization
*/
private String organization;
/**
* Registry centers
*/
private List<RegistryConfig> registries;
/**
* Monitor center
*/
private MonitorConfig monitor;
/**
* If it's default
*/
private Boolean isDefault;
public static ModuleBuilder newBuilder() {
return new ModuleBuilder();
}
public ModuleBuilder name(String name) {
this.name = name;
return getThis();
}
public ModuleBuilder version(String version) {
this.version = version;
return getThis();
}
public ModuleBuilder owner(String owner) {
this.owner = owner;
return getThis();
}
public ModuleBuilder organization(String organization) {
this.organization = organization;
return getThis();
}
public ModuleBuilder addRegistries(List<? extends RegistryConfig> registries) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.addAll(registries);
return getThis();
}
public ModuleBuilder addRegistry(RegistryConfig registry) {
if (this.registries == null) {
this.registries = new ArrayList<>();
}
this.registries.add(registry);
return getThis();
}
public ModuleBuilder monitor(MonitorConfig monitor) {
this.monitor = monitor;
return getThis();
}
public ModuleBuilder isDefault(Boolean isDefault) {
this.isDefault = isDefault;
return getThis();
}
@Override
public ModuleConfig build() {
ModuleConfig moduleConfig = new ModuleConfig();
super.build(moduleConfig);
moduleConfig.setDefault(isDefault);
moduleConfig.setMonitor(monitor);
moduleConfig.setName(name);
moduleConfig.setOrganization(organization);
moduleConfig.setOwner(owner);
moduleConfig.setRegistries(registries);
moduleConfig.setVersion(version);
return moduleConfig;
}
@Override
protected ModuleBuilder getThis() {
return this;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/ConfigValidationUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.PropertiesConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.SystemPropertyConfigUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.AbstractInterfaceConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.monitor.MonitorFactory;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.Dispatcher;
import org.apache.dubbo.remoting.Transporter;
import org.apache.dubbo.remoting.exchange.Exchanger;
import org.apache.dubbo.remoting.telnet.TelnetHandler;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_IP_TO_REGISTRY;
import static org.apache.dubbo.common.constants.CommonConstants.DubboProperty.DUBBO_MONITOR_ADDRESS;
import static org.apache.dubbo.common.constants.CommonConstants.FILE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.FILTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.HOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.LOCALHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.PASSWORD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOVE_VALUE_PREFIX;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.USERNAME_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_ALL;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INSTANCE;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_REGISTER_MODE_INTERFACE;
import static org.apache.dubbo.common.constants.RegistryConstants.DUBBO_REGISTER_MODE_DEFAULT_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL_TYPE;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_PROTOCOL;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isNotEmpty;
import static org.apache.dubbo.config.Constants.ARCHITECTURE;
import static org.apache.dubbo.config.Constants.CONTEXTPATH_KEY;
import static org.apache.dubbo.config.Constants.ENVIRONMENT;
import static org.apache.dubbo.config.Constants.IGNORE_CHECK_KEYS;
import static org.apache.dubbo.config.Constants.LAYER_KEY;
import static org.apache.dubbo.config.Constants.NAME;
import static org.apache.dubbo.config.Constants.ORGANIZATION;
import static org.apache.dubbo.config.Constants.OWNER;
import static org.apache.dubbo.config.Constants.REGISTER_KEY;
import static org.apache.dubbo.config.Constants.STATUS_KEY;
import static org.apache.dubbo.monitor.Constants.LOGSTAT_PROTOCOL;
import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY;
import static org.apache.dubbo.registry.Constants.SUBSCRIBE_KEY;
import static org.apache.dubbo.remoting.Constants.CLIENT_KEY;
import static org.apache.dubbo.remoting.Constants.CODEC_KEY;
import static org.apache.dubbo.remoting.Constants.DISPATCHER_KEY;
import static org.apache.dubbo.remoting.Constants.EXCHANGER_KEY;
import static org.apache.dubbo.remoting.Constants.PREFER_SERIALIZATION_KEY;
import static org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY;
import static org.apache.dubbo.remoting.Constants.SERVER_KEY;
import static org.apache.dubbo.remoting.Constants.TELNET_KEY;
import static org.apache.dubbo.remoting.Constants.TRANSPORTER_KEY;
import static org.apache.dubbo.rpc.Constants.FAIL_PREFIX;
import static org.apache.dubbo.rpc.Constants.FORCE_PREFIX;
import static org.apache.dubbo.rpc.Constants.LOCAL_KEY;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_PREFIX;
import static org.apache.dubbo.rpc.Constants.THROW_PREFIX;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
public class ConfigValidationUtils {
private static ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(ConfigValidationUtils.class);
/**
* The maximum length of a <b>parameter's value</b>
*/
private static final int MAX_LENGTH = 200;
/**
* The maximum length of a <b>path</b>
*/
private static final int MAX_PATH_LENGTH = 200;
/**
* The rule qualification for <b>name</b>
*/
private static final Pattern PATTERN_NAME = Pattern.compile("[\\-._0-9a-zA-Z]+");
/**
* The rule qualification for <b>multiply name</b>
*/
private static final Pattern PATTERN_MULTI_NAME = Pattern.compile("[,\\-._0-9a-zA-Z]+");
/**
* The rule qualification for <b>method names</b>
*/
private static final Pattern PATTERN_METHOD_NAME = Pattern.compile("[a-zA-Z][0-9a-zA-Z]*");
/**
* The rule qualification for <b>path</b>
*/
private static final Pattern PATTERN_PATH = Pattern.compile("[/\\-$._0-9a-zA-Z]+");
/**
* The pattern matches a value who has a symbol
*/
private static final Pattern PATTERN_NAME_HAS_SYMBOL = Pattern.compile("[:*,\\s/\\-._0-9a-zA-Z]+");
/**
* The pattern matches a property key
*/
private static final Pattern PATTERN_KEY = Pattern.compile("[*,\\-._0-9a-zA-Z]+");
public static final String IPV6_START_MARK = "[";
public static final String IPV6_END_MARK = "]";
public static List<URL> loadRegistries(AbstractInterfaceConfig interfaceConfig, boolean provider) {
// check && override if necessary
List<URL> registryList = new ArrayList<>();
ApplicationConfig application = interfaceConfig.getApplication();
List<RegistryConfig> registries = interfaceConfig.getRegistries();
if (CollectionUtils.isNotEmpty(registries)) {
for (RegistryConfig config : registries) {
// try to refresh registry in case it is set directly by user using config.setRegistries()
if (!config.isRefreshed()) {
config.refresh();
}
String address = config.getAddress();
if (StringUtils.isEmpty(address)) {
address = ANYHOST_VALUE;
}
if (!RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) {
Map<String, String> map = new HashMap<>();
AbstractConfig.appendParameters(map, application);
AbstractConfig.appendParameters(map, config);
map.put(PATH_KEY, RegistryService.class.getName());
AbstractInterfaceConfig.appendRuntimeParameters(map);
if (!map.containsKey(PROTOCOL_KEY)) {
map.put(PROTOCOL_KEY, DUBBO_PROTOCOL);
}
String registryCluster = config.getId();
if (isEmpty(registryCluster)) {
registryCluster = DEFAULT_KEY;
}
if (map.containsKey(CONFIG_NAMESPACE_KEY)) {
registryCluster += ":" + map.get(CONFIG_NAMESPACE_KEY);
}
map.put(REGISTRY_CLUSTER_KEY, registryCluster);
List<URL> urls = UrlUtils.parseURLs(address, map);
for (URL url : urls) {
url = URLBuilder.from(url)
.addParameter(REGISTRY_KEY, url.getProtocol())
.setProtocol(extractRegistryType(url))
.setScopeModel(interfaceConfig.getScopeModel())
.build();
// provider delay register state will be checked in RegistryProtocol#export
if (provider && url.getParameter(REGISTER_KEY, true)) {
registryList.add(url);
}
if (!provider && url.getParameter(SUBSCRIBE_KEY, true)) {
registryList.add(url);
}
}
}
}
}
return genCompatibleRegistries(interfaceConfig.getScopeModel(), registryList, provider);
}
private static List<URL> genCompatibleRegistries(ScopeModel scopeModel, List<URL> registryList, boolean provider) {
List<URL> result = new ArrayList<>(registryList.size());
registryList.forEach(registryURL -> {
if (provider) {
// for registries enabled service discovery, automatically register interface compatible addresses.
String registerMode;
if (SERVICE_REGISTRY_PROTOCOL.equals(registryURL.getProtocol())) {
registerMode = registryURL.getParameter(
REGISTER_MODE_KEY,
ConfigurationUtils.getCachedDynamicProperty(
scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_INSTANCE));
if (!isValidRegisterMode(registerMode)) {
registerMode = DEFAULT_REGISTER_MODE_INSTANCE;
}
result.add(registryURL);
if (DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)
&& registryNotExists(registryURL, registryList, REGISTRY_PROTOCOL)) {
URL interfaceCompatibleRegistryURL = URLBuilder.from(registryURL)
.setProtocol(REGISTRY_PROTOCOL)
.removeParameter(REGISTRY_TYPE_KEY)
.build();
result.add(interfaceCompatibleRegistryURL);
}
} else {
registerMode = registryURL.getParameter(
REGISTER_MODE_KEY,
ConfigurationUtils.getCachedDynamicProperty(
scopeModel, DUBBO_REGISTER_MODE_DEFAULT_KEY, DEFAULT_REGISTER_MODE_ALL));
if (!isValidRegisterMode(registerMode)) {
registerMode = DEFAULT_REGISTER_MODE_INTERFACE;
}
if ((DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(registerMode)
|| DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode))
&& registryNotExists(registryURL, registryList, SERVICE_REGISTRY_PROTOCOL)) {
URL serviceDiscoveryRegistryURL = URLBuilder.from(registryURL)
.setProtocol(SERVICE_REGISTRY_PROTOCOL)
.removeParameter(REGISTRY_TYPE_KEY)
.build();
result.add(serviceDiscoveryRegistryURL);
}
if (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(registerMode)
|| DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(registerMode)) {
result.add(registryURL);
}
}
FrameworkStatusReportService reportService = ScopeModelUtil.getApplicationModel(scopeModel)
.getBeanFactory()
.getBean(FrameworkStatusReportService.class);
reportService.reportRegistrationStatus(reportService.createRegistrationReport(registerMode));
} else {
result.add(registryURL);
}
});
return result;
}
private static boolean isValidRegisterMode(String mode) {
return isNotEmpty(mode)
&& (DEFAULT_REGISTER_MODE_INTERFACE.equalsIgnoreCase(mode)
|| DEFAULT_REGISTER_MODE_INSTANCE.equalsIgnoreCase(mode)
|| DEFAULT_REGISTER_MODE_ALL.equalsIgnoreCase(mode));
}
private static boolean registryNotExists(URL registryURL, List<URL> registryList, String registryType) {
return registryList.stream()
.noneMatch(url -> registryType.equals(url.getProtocol())
&& registryURL.getBackupAddress().equals(url.getBackupAddress()));
}
public static URL loadMonitor(AbstractInterfaceConfig interfaceConfig, URL registryURL) {
Map<String, String> map = new HashMap<>();
map.put(INTERFACE_KEY, MonitorService.class.getName());
AbstractInterfaceConfig.appendRuntimeParameters(map);
// set ip
String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
if (StringUtils.isEmpty(hostToRegistry)) {
hostToRegistry = NetUtils.getLocalHost();
} else if (NetUtils.isInvalidLocalHost(hostToRegistry)) {
throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY
+ ", value:" + hostToRegistry);
}
map.put(REGISTER_IP_KEY, hostToRegistry);
MonitorConfig monitor = interfaceConfig.getMonitor();
ApplicationConfig application = interfaceConfig.getApplication();
AbstractConfig.appendParameters(map, monitor);
AbstractConfig.appendParameters(map, application);
String address = null;
String sysAddress = SystemPropertyConfigUtils.getSystemProperty(DUBBO_MONITOR_ADDRESS);
if (sysAddress != null && sysAddress.length() > 0) {
address = sysAddress;
} else if (monitor != null) {
address = monitor.getAddress();
}
String protocol = monitor == null ? null : monitor.getProtocol();
if (monitor != null
&& (REGISTRY_PROTOCOL.equals(protocol) || SERVICE_REGISTRY_PROTOCOL.equals(protocol))
&& registryURL != null) {
return URLBuilder.from(registryURL)
.setProtocol(DUBBO_PROTOCOL)
.addParameter(PROTOCOL_KEY, protocol)
.putAttribute(REFER_KEY, map)
.build();
} else if (ConfigUtils.isNotEmpty(address) || ConfigUtils.isNotEmpty(protocol)) {
if (!map.containsKey(PROTOCOL_KEY)) {
if (interfaceConfig
.getScopeModel()
.getExtensionLoader(MonitorFactory.class)
.hasExtension(LOGSTAT_PROTOCOL)) {
map.put(PROTOCOL_KEY, LOGSTAT_PROTOCOL);
} else if (ConfigUtils.isNotEmpty(protocol)) {
map.put(PROTOCOL_KEY, protocol);
} else {
map.put(PROTOCOL_KEY, DUBBO_PROTOCOL);
}
}
if (ConfigUtils.isEmpty(address)) {
address = LOCALHOST_VALUE;
}
return UrlUtils.parseURL(address, map);
}
return null;
}
public static void validateAbstractInterfaceConfig(AbstractInterfaceConfig config) {
checkName(LOCAL_KEY, config.getLocal());
checkName("stub", config.getStub());
checkMultiName("owner", config.getOwner());
checkExtension(config.getScopeModel(), ProxyFactory.class, PROXY_KEY, config.getProxy());
checkExtension(config.getScopeModel(), Cluster.class, CLUSTER_KEY, config.getCluster());
checkMultiExtension(
config.getScopeModel(),
Arrays.asList(Filter.class, ClusterFilter.class),
FILTER_KEY,
config.getFilter());
checkNameHasSymbol(LAYER_KEY, config.getLayer());
List<MethodConfig> methods = config.getMethods();
if (CollectionUtils.isNotEmpty(methods)) {
methods.forEach(ConfigValidationUtils::validateMethodConfig);
}
}
public static void validateServiceConfig(ServiceConfig config) {
checkKey(VERSION_KEY, config.getVersion());
checkKey(GROUP_KEY, config.getGroup());
checkName(TOKEN_KEY, config.getToken());
checkPathName(PATH_KEY, config.getPath());
checkMultiExtension(config.getScopeModel(), ExporterListener.class, "listener", config.getListener());
validateAbstractInterfaceConfig(config);
List<RegistryConfig> registries = config.getRegistries();
if (registries != null) {
for (RegistryConfig registry : registries) {
validateRegistryConfig(registry);
}
}
List<ProtocolConfig> protocols = config.getProtocols();
if (protocols != null) {
for (ProtocolConfig protocol : protocols) {
validateProtocolConfig(protocol);
}
}
ProviderConfig providerConfig = config.getProvider();
if (providerConfig != null) {
validateProviderConfig(providerConfig);
}
}
public static void validateReferenceConfig(ReferenceConfig config) {
checkMultiExtension(config.getScopeModel(), InvokerListener.class, "listener", config.getListener());
checkKey(VERSION_KEY, config.getVersion());
checkKey(GROUP_KEY, config.getGroup());
checkName(CLIENT_KEY, config.getClient());
validateAbstractInterfaceConfig(config);
List<RegistryConfig> registries = config.getRegistries();
if (registries != null) {
for (RegistryConfig registry : registries) {
validateRegistryConfig(registry);
}
}
ConsumerConfig consumerConfig = config.getConsumer();
if (consumerConfig != null) {
validateConsumerConfig(consumerConfig);
}
}
public static void validateConfigCenterConfig(ConfigCenterConfig config) {
if (config != null) {
checkParameterName(config.getParameters());
}
}
public static void validateApplicationConfig(ApplicationConfig config) {
if (config == null) {
return;
}
if (!config.isValid()) {
throw new IllegalStateException("No application config found or it's not a valid config! "
+ "Please add <dubbo:application name=\"...\" /> to your spring config.");
}
// backward compatibility
ScopeModel scopeModel = ScopeModelUtil.getOrDefaultApplicationModel(config.getScopeModel());
PropertiesConfiguration configuration = scopeModel.modelEnvironment().getPropertiesConfiguration();
String wait = configuration.getProperty(SHUTDOWN_WAIT_KEY);
if (wait != null && wait.trim().length() > 0) {
System.setProperty(SHUTDOWN_WAIT_KEY, wait.trim());
} else {
wait = configuration.getProperty(SHUTDOWN_WAIT_SECONDS_KEY);
if (wait != null && wait.trim().length() > 0) {
System.setProperty(SHUTDOWN_WAIT_SECONDS_KEY, wait.trim());
}
}
checkName(NAME, config.getName());
checkMultiName(OWNER, config.getOwner());
checkName(ORGANIZATION, config.getOrganization());
checkName(ARCHITECTURE, config.getArchitecture());
checkName(ENVIRONMENT, config.getEnvironment());
checkParameterName(config.getParameters());
checkQosDependency(config);
}
private static void checkQosDependency(ApplicationConfig config) {
if (!Boolean.FALSE.equals(config.getQosEnable())) {
try {
ClassUtils.forName("org.apache.dubbo.qos.protocol.QosProtocolWrapper");
} catch (ClassNotFoundException e) {
logger.info(
"QosProtocolWrapper not found, qos will not be enabled, please check if 'dubbo-qos' dependency was imported correctly.");
}
}
}
public static void validateModuleConfig(ModuleConfig config) {
if (config != null) {
checkName(NAME, config.getName());
checkName(OWNER, config.getOwner());
checkName(ORGANIZATION, config.getOrganization());
}
}
public static boolean isValidMetadataConfig(MetadataReportConfig metadataReportConfig) {
if (metadataReportConfig == null) {
return false;
}
if (Boolean.FALSE.equals(metadataReportConfig.getReportMetadata())
&& Boolean.FALSE.equals(metadataReportConfig.getReportDefinition())) {
return false;
}
return !isEmpty(metadataReportConfig.getAddress());
}
public static void validateMetadataConfig(MetadataReportConfig metadataReportConfig) {
if (!isValidMetadataConfig(metadataReportConfig)) {
return;
}
String address = metadataReportConfig.getAddress();
String protocol = metadataReportConfig.getProtocol();
if ((isEmpty(address) || !address.contains("://")) && isEmpty(protocol)) {
throw new IllegalArgumentException(
"Please specify valid protocol or address for metadata report " + address);
}
}
public static void validateMetricsConfig(MetricsConfig metricsConfig) {
if (metricsConfig == null) {
return;
}
}
public static void validateTracingConfig(TracingConfig tracingConfig) {
if (tracingConfig == null) {
return;
}
}
public static void validateSslConfig(SslConfig sslConfig) {
if (sslConfig == null) {
return;
}
}
public static void validateMonitorConfig(MonitorConfig config) {
if (config != null) {
if (!config.isValid()) {
logger.info("There's no valid monitor config found, if you want to open monitor statistics for Dubbo, "
+ "please make sure your monitor is configured properly.");
}
checkParameterName(config.getParameters());
}
}
public static void validateProtocolConfig(ProtocolConfig config) {
if (config != null) {
String name = config.getName();
checkName("name", name);
checkHost(HOST_KEY, config.getHost());
checkPathName("contextpath", config.getContextpath());
if (DUBBO_PROTOCOL.equals(name)) {
checkMultiExtension(config.getScopeModel(), Codec2.class, CODEC_KEY, config.getCodec());
checkMultiExtension(
config.getScopeModel(), Serialization.class, SERIALIZATION_KEY, config.getSerialization());
checkMultiExtension(
config.getScopeModel(),
Serialization.class,
PREFER_SERIALIZATION_KEY,
config.getPreferSerialization());
checkMultiExtension(config.getScopeModel(), Transporter.class, SERVER_KEY, config.getServer());
checkMultiExtension(config.getScopeModel(), Transporter.class, CLIENT_KEY, config.getClient());
}
checkMultiExtension(config.getScopeModel(), TelnetHandler.class, TELNET_KEY, config.getTelnet());
checkMultiExtension(config.getScopeModel(), StatusChecker.class, "status", config.getStatus());
checkExtension(config.getScopeModel(), Transporter.class, TRANSPORTER_KEY, config.getTransporter());
checkExtension(config.getScopeModel(), Exchanger.class, EXCHANGER_KEY, config.getExchanger());
checkExtension(config.getScopeModel(), Dispatcher.class, DISPATCHER_KEY, config.getDispatcher());
checkExtension(config.getScopeModel(), Dispatcher.class, "dispather", config.getDispatcher());
checkExtension(config.getScopeModel(), ThreadPool.class, THREADPOOL_KEY, config.getThreadpool());
}
}
public static void validateProviderConfig(ProviderConfig config) {
checkPathName(CONTEXTPATH_KEY, config.getContextpath());
checkExtension(config.getScopeModel(), ThreadPool.class, THREADPOOL_KEY, config.getThreadpool());
checkMultiExtension(config.getScopeModel(), TelnetHandler.class, TELNET_KEY, config.getTelnet());
checkMultiExtension(config.getScopeModel(), StatusChecker.class, STATUS_KEY, config.getStatus());
checkExtension(config.getScopeModel(), Transporter.class, TRANSPORTER_KEY, config.getTransporter());
checkExtension(config.getScopeModel(), Exchanger.class, EXCHANGER_KEY, config.getExchanger());
checkMultiExtension(config.getScopeModel(), Serialization.class, SERIALIZATION_KEY, config.getSerialization());
checkMultiExtension(
config.getScopeModel(), Serialization.class, PREFER_SERIALIZATION_KEY, config.getPreferSerialization());
}
public static void validateConsumerConfig(ConsumerConfig config) {
if (config == null) {
return;
}
}
public static void validateRegistryConfig(RegistryConfig config) {
checkName(PROTOCOL_KEY, config.getProtocol());
checkName(USERNAME_KEY, config.getUsername());
checkLength(PASSWORD_KEY, config.getPassword());
checkPathLength(FILE_KEY, config.getFile());
checkName(TRANSPORTER_KEY, config.getTransporter());
checkName(SERVER_KEY, config.getServer());
checkName(CLIENT_KEY, config.getClient());
checkParameterName(config.getParameters());
}
public static void validateMethodConfig(MethodConfig config) {
checkExtension(config.getScopeModel(), LoadBalance.class, LOADBALANCE_KEY, config.getLoadbalance());
checkParameterName(config.getParameters());
checkMethodName("name", config.getName());
String mock = config.getMock();
if (isNotEmpty(mock)) {
if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX + " ")) {
checkLength(MOCK_KEY, mock);
} else if (mock.startsWith(FAIL_PREFIX) || mock.startsWith(FORCE_PREFIX)) {
checkNameHasSymbol(MOCK_KEY, mock);
} else {
checkName(MOCK_KEY, mock);
}
}
}
private static String extractRegistryType(URL url) {
return UrlUtils.hasServiceDiscoveryRegistryTypeKey(url)
? SERVICE_REGISTRY_PROTOCOL
: getRegistryProtocolType(url);
}
private static String getRegistryProtocolType(URL url) {
String registryProtocol = url.getParameter(REGISTRY_PROTOCOL_TYPE);
return isNotEmpty(registryProtocol) ? registryProtocol : REGISTRY_PROTOCOL;
}
public static void checkExtension(ScopeModel scopeModel, Class<?> type, String property, String value) {
checkName(property, value);
if (isNotEmpty(value) && !scopeModel.getExtensionLoader(type).hasExtension(value)) {
throw new IllegalStateException("No such extension " + value + " for " + property + "/" + type.getName());
}
}
/**
* Check whether there is a <code>Extension</code> who's name (property) is <code>value</code> (special treatment is
* required)
*
* @param type The Extension type
* @param property The extension key
* @param value The Extension name
*/
public static void checkMultiExtension(ScopeModel scopeModel, Class<?> type, String property, String value) {
checkMultiExtension(scopeModel, Collections.singletonList(type), property, value);
}
public static void checkMultiExtension(ScopeModel scopeModel, List<Class<?>> types, String property, String value) {
checkMultiName(property, value);
if (isNotEmpty(value)) {
String[] values = value.split("\\s*[,]+\\s*");
for (String v : values) {
v = StringUtils.trim(v);
if (v.startsWith(REMOVE_VALUE_PREFIX)) {
continue;
}
if (DEFAULT_KEY.equals(v)) {
continue;
}
boolean match = false;
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/CompositeReferenceCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.List;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_WRONG_USE;
/**
* A impl of ReferenceCache for Application
*/
public class CompositeReferenceCache implements ReferenceCache {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(CompositeReferenceCache.class);
private final ApplicationModel applicationModel;
public CompositeReferenceCache(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public <T> T get(ReferenceConfigBase<T> referenceConfig, boolean check) {
Class<?> type = referenceConfig.getInterfaceClass();
String key = BaseServiceMetadata.buildServiceKey(
type.getName(), referenceConfig.getGroup(), referenceConfig.getVersion());
boolean singleton = referenceConfig.getSingleton() == null || referenceConfig.getSingleton();
T proxy = null;
if (singleton) {
proxy = get(key, (Class<T>) type);
} else {
logger.warn(
CONFIG_API_WRONG_USE,
"the api method is being used incorrectly",
"",
"Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. "
+ "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)");
}
if (proxy == null) {
proxy = referenceConfig.get(check);
}
return proxy;
}
@Override
public <T> T get(String key, Class<T> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
T proxy = moduleModel.getDeployer().getReferenceCache().get(key, type);
if (proxy != null) {
return proxy;
}
}
return null;
}
@Override
public <T> T get(String key) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
T proxy = moduleModel.getDeployer().getReferenceCache().get(key);
if (proxy != null) {
return proxy;
}
}
return null;
}
@Override
public <T> List<T> getAll(Class<T> type) {
List<T> proxies = new ArrayList<>();
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
proxies.addAll(moduleModel.getDeployer().getReferenceCache().getAll(type));
}
return proxies;
}
@Override
public <T> T get(Class<T> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
T proxy = moduleModel.getDeployer().getReferenceCache().get(type);
if (proxy != null) {
return proxy;
}
}
return null;
}
@Override
public void destroy(String key, Class<?> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().destroy(key, type);
}
}
@Override
public void check(String key, Class<?> type, long timeout) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().check(key, type, timeout);
}
}
@Override
public <T> void check(ReferenceConfigBase<T> referenceConfig, long timeout) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().check(referenceConfig, timeout);
}
}
@Override
public void destroy(Class<?> type) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().destroy(type);
}
}
@Override
public <T> void destroy(ReferenceConfigBase<T> referenceConfig) {
referenceConfig.getScopeModel().getDeployer().getReferenceCache().destroy(referenceConfig);
}
@Override
public void destroyAll() {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
moduleModel.getDeployer().getReferenceCache().destroyAll();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/SimpleReferenceCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.common.BaseServiceMetadata;
import org.apache.dubbo.common.config.ReferenceCache;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_API_WRONG_USE;
/**
* A simple util class for cache {@link ReferenceConfigBase}.
* <p>
* {@link ReferenceConfigBase} is a heavy Object, it's necessary to cache these object
* for the framework which create {@link ReferenceConfigBase} frequently.
* <p>
* You can implement and use your own {@link ReferenceConfigBase} cache if you need use complicate strategy.
*/
public class SimpleReferenceCache implements ReferenceCache {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(SimpleReferenceCache.class);
public static final String DEFAULT_NAME = "_DEFAULT_";
/**
* Create the key with the <b>Group</b>, <b>Interface</b> and <b>version</b> attribute of {@link ReferenceConfigBase}.
* <p>
* key example: <code>group1/org.apache.dubbo.foo.FooService:1.0.0</code>.
*/
public static final KeyGenerator DEFAULT_KEY_GENERATOR = referenceConfig -> {
String iName = referenceConfig.getInterface();
if (StringUtils.isBlank(iName)) {
Class<?> clazz = referenceConfig.getInterfaceClass();
iName = clazz.getName();
}
if (StringUtils.isBlank(iName)) {
throw new IllegalArgumentException("No interface info in ReferenceConfig" + referenceConfig);
}
return BaseServiceMetadata.buildServiceKey(iName, referenceConfig.getGroup(), referenceConfig.getVersion());
};
private static final AtomicInteger nameIndex = new AtomicInteger();
static final ConcurrentMap<String, SimpleReferenceCache> CACHE_HOLDER = new ConcurrentHashMap<>();
private final String name;
private final KeyGenerator generator;
private final ConcurrentMap<String, List<ReferenceConfigBase<?>>> referenceKeyMap = new ConcurrentHashMap<>();
private final ConcurrentMap<Class<?>, List<ReferenceConfigBase<?>>> referenceTypeMap = new ConcurrentHashMap<>();
private final Map<ReferenceConfigBase<?>, Object> references = new ConcurrentHashMap<>();
protected SimpleReferenceCache(String name, KeyGenerator generator) {
this.name = name;
this.generator = generator;
}
/**
* Get the cache use default name and {@link #DEFAULT_KEY_GENERATOR} to generate cache key.
* Create cache if not existed yet.
*/
public static SimpleReferenceCache getCache() {
return getCache(DEFAULT_NAME);
}
public static SimpleReferenceCache newCache() {
return getCache(DEFAULT_NAME + "#" + nameIndex.incrementAndGet());
}
/**
* Get the cache use specified name and {@link KeyGenerator}.
* Create cache if not existed yet.
*/
public static SimpleReferenceCache getCache(String name) {
return getCache(name, DEFAULT_KEY_GENERATOR);
}
/**
* Get the cache use specified {@link KeyGenerator}.
* Create cache if not existed yet.
*/
public static SimpleReferenceCache getCache(String name, KeyGenerator keyGenerator) {
return ConcurrentHashMapUtils.computeIfAbsent(
CACHE_HOLDER, name, k -> new SimpleReferenceCache(k, keyGenerator));
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(ReferenceConfigBase<T> rc, boolean check) {
String key = generator.generateKey(rc);
Class<?> type = rc.getInterfaceClass();
boolean singleton = rc.getSingleton() == null || rc.getSingleton();
T proxy = null;
// Check existing proxy of the same 'key' and 'type' first.
if (singleton) {
proxy = get(key, (Class<T>) type);
} else {
logger.warn(
CONFIG_API_WRONG_USE,
"",
"",
"Using non-singleton ReferenceConfig and ReferenceCache at the same time may cause memory leak. "
+ "Call ReferenceConfig#get() directly for non-singleton ReferenceConfig instead of using ReferenceCache#get(ReferenceConfig)");
}
if (proxy == null) {
List<ReferenceConfigBase<?>> referencesOfType = ConcurrentHashMapUtils.computeIfAbsent(
referenceTypeMap, type, _t -> Collections.synchronizedList(new ArrayList<>()));
referencesOfType.add(rc);
List<ReferenceConfigBase<?>> referenceConfigList = ConcurrentHashMapUtils.computeIfAbsent(
referenceKeyMap, key, _k -> Collections.synchronizedList(new ArrayList<>()));
referenceConfigList.add(rc);
proxy = rc.get(check);
}
return proxy;
}
/**
* Fetch cache with the specified key. The key is decided by KeyGenerator passed-in. If the default KeyGenerator is
* used, then the key is in the format of <code>group/interfaceClass:version</code>
*
* @param key cache key
* @param type object class
* @param <T> object type
* @return object from the cached ReferenceConfigBase
* @see KeyGenerator#generateKey(ReferenceConfigBase)
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(String key, Class<T> type) {
List<ReferenceConfigBase<?>> referenceConfigs = referenceKeyMap.get(key);
if (CollectionUtils.isNotEmpty(referenceConfigs)) {
return (T) referenceConfigs.get(0).get();
}
return null;
}
/**
* Check and return existing ReferenceConfig and its corresponding proxy instance.
*
* @param key ServiceKey
* @param <T> service interface type
* @return the existing proxy instance of the same service key
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(String key) {
List<ReferenceConfigBase<?>> referenceConfigBases = referenceKeyMap.get(key);
if (CollectionUtils.isNotEmpty(referenceConfigBases)) {
return (T) referenceConfigBases.get(0).get();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> type) {
List<ReferenceConfigBase<?>> referenceConfigBases = referenceTypeMap.get(type);
if (CollectionUtils.isEmpty(referenceConfigBases)) {
return Collections.EMPTY_LIST;
}
List proxiesOfType = new ArrayList(referenceConfigBases.size());
for (ReferenceConfigBase<?> rc : referenceConfigBases) {
proxiesOfType.add(rc.get());
}
return Collections.unmodifiableList(proxiesOfType);
}
/**
* Check and return existing ReferenceConfig and its corresponding proxy instance.
*
* @param type service interface class
* @param <T> service interface type
* @return the existing proxy instance of the same interface definition
*/
@Override
@SuppressWarnings("unchecked")
public <T> T get(Class<T> type) {
List<ReferenceConfigBase<?>> referenceConfigBases = referenceTypeMap.get(type);
if (CollectionUtils.isNotEmpty(referenceConfigBases)) {
return (T) referenceConfigBases.get(0).get();
}
return null;
}
@Override
public void check(String key, Class<?> type, long timeout) {
List<ReferenceConfigBase<?>> referencesOfKey = referenceKeyMap.get(key);
if (CollectionUtils.isEmpty(referencesOfKey)) {
return;
}
List<ReferenceConfigBase<?>> referencesOfType = referenceTypeMap.get(type);
if (CollectionUtils.isEmpty(referencesOfType)) {
return;
}
for (ReferenceConfigBase<?> rc : referencesOfKey) {
rc.checkOrDestroy(timeout);
}
}
@Override
public <T> void check(ReferenceConfigBase<T> referenceConfig, long timeout) {
String key = generator.generateKey(referenceConfig);
Class<?> type = referenceConfig.getInterfaceClass();
check(key, type, timeout);
}
@Override
public void destroy(String key, Class<?> type) {
List<ReferenceConfigBase<?>> referencesOfKey = referenceKeyMap.remove(key);
if (CollectionUtils.isEmpty(referencesOfKey)) {
return;
}
List<ReferenceConfigBase<?>> referencesOfType = referenceTypeMap.get(type);
if (CollectionUtils.isEmpty(referencesOfType)) {
return;
}
for (ReferenceConfigBase<?> rc : referencesOfKey) {
referencesOfType.remove(rc);
destroyReference(rc);
}
}
@Override
public void destroy(Class<?> type) {
List<ReferenceConfigBase<?>> referencesOfType = referenceTypeMap.remove(type);
for (ReferenceConfigBase<?> rc : referencesOfType) {
String key = generator.generateKey(rc);
referenceKeyMap.remove(key);
destroyReference(rc);
}
}
/**
* clear and destroy one {@link ReferenceConfigBase} in the cache.
*
* @param referenceConfig use for create key.
*/
@Override
public <T> void destroy(ReferenceConfigBase<T> referenceConfig) {
String key = generator.generateKey(referenceConfig);
Class<?> type = referenceConfig.getInterfaceClass();
destroy(key, type);
}
/**
* clear and destroy all {@link ReferenceConfigBase} in the cache.
*/
@Override
public void destroyAll() {
if (CollectionUtils.isEmptyMap(referenceKeyMap)) {
return;
}
referenceKeyMap.forEach((_k, referencesOfKey) -> {
for (ReferenceConfigBase<?> rc : referencesOfKey) {
destroyReference(rc);
}
});
referenceKeyMap.clear();
referenceTypeMap.clear();
}
private void destroyReference(ReferenceConfigBase<?> rc) {
Destroyable proxy = (Destroyable) rc.get();
if (proxy != null) {
proxy.$destroy();
}
rc.destroy();
}
public Map<String, List<ReferenceConfigBase<?>>> getReferenceMap() {
return referenceKeyMap;
}
public Map<Class<?>, List<ReferenceConfigBase<?>>> getReferenceTypeMap() {
return referenceTypeMap;
}
@Override
public String toString() {
return "ReferenceCache(name: " + name + ")";
}
public interface KeyGenerator {
String generateKey(ReferenceConfigBase<?> referenceConfig);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/utils/DefaultConfigValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.utils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.context.ConfigValidator;
public class DefaultConfigValidator implements ConfigValidator {
@Override
public void validate(AbstractConfig config) {
if (config instanceof ProtocolConfig) {
ConfigValidationUtils.validateProtocolConfig((ProtocolConfig) config);
} else if (config instanceof RegistryConfig) {
ConfigValidationUtils.validateRegistryConfig((RegistryConfig) config);
} else if (config instanceof MetadataReportConfig) {
ConfigValidationUtils.validateMetadataConfig((MetadataReportConfig) config);
} else if (config instanceof ProviderConfig) {
ConfigValidationUtils.validateProviderConfig((ProviderConfig) config);
} else if (config instanceof ConsumerConfig) {
ConfigValidationUtils.validateConsumerConfig((ConsumerConfig) config);
} else if (config instanceof ApplicationConfig) {
ConfigValidationUtils.validateApplicationConfig((ApplicationConfig) config);
} else if (config instanceof MonitorConfig) {
ConfigValidationUtils.validateMonitorConfig((MonitorConfig) config);
} else if (config instanceof ModuleConfig) {
ConfigValidationUtils.validateModuleConfig((ModuleConfig) config);
} else if (config instanceof MetricsConfig) {
ConfigValidationUtils.validateMetricsConfig((MetricsConfig) config);
} else if (config instanceof TracingConfig) {
ConfigValidationUtils.validateTracingConfig((TracingConfig) config);
} else if (config instanceof SslConfig) {
ConfigValidationUtils.validateSslConfig((SslConfig) config);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvoker.java | dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/invoker/DelegateProviderMetaDataInvoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.config.invoker;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
/**
* An invoker wrapper that wrap the invoker and all the metadata (ServiceConfig)
*/
public class DelegateProviderMetaDataInvoker<T> implements Invoker {
protected final Invoker<T> invoker;
private final ServiceConfig<?> metadata;
public DelegateProviderMetaDataInvoker(Invoker<T> invoker, ServiceConfig<?> metadata) {
this.invoker = invoker;
this.metadata = metadata;
}
@Override
public Class<T> getInterface() {
return invoker.getInterface();
}
@Override
public URL getUrl() {
return invoker.getUrl();
}
@Override
public boolean isAvailable() {
return invoker.isAvailable();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public void destroy() {
invoker.destroy();
}
public ServiceConfig<?> getMetadata() {
return metadata;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragmentByteArrayInputStream.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragmentByteArrayInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
import java.io.ByteArrayInputStream;
public class FinalFragmentByteArrayInputStream extends ByteArrayInputStream implements FinalFragment {
private final boolean finalFragment;
public FinalFragmentByteArrayInputStream(byte[] buf) {
this(buf, 0, buf.length);
}
public FinalFragmentByteArrayInputStream(byte[] buf, boolean finalFragment) {
this(buf, 0, buf.length, finalFragment);
}
public FinalFragmentByteArrayInputStream(byte[] buf, int offset, int length) {
this(buf, offset, length, false);
}
public FinalFragmentByteArrayInputStream(byte[] buf, int offset, int length, boolean finalFragment) {
super(buf, offset, length);
this.finalFragment = finalFragment;
}
@Override
public boolean isFinalFragment() {
return finalFragment;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/WebSocketServerTransportListenerFactory.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/WebSocketServerTransportListenerFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.rpc.model.FrameworkModel;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface WebSocketServerTransportListenerFactory {
WebSocketTransportListener newInstance(H2StreamChannel streamChannel, URL url, FrameworkModel frameworkModel);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragment.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragment.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
public interface FinalFragment {
boolean isFinalFragment();
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/WebSocketHeaderNames.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/WebSocketHeaderNames.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
public enum WebSocketHeaderNames {
WEBSOCKET_MESSAGE("websocket-message");
private final String name;
WebSocketHeaderNames(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragmentByteBufInputStream.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragmentByteBufInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
public class FinalFragmentByteBufInputStream extends ByteBufInputStream implements FinalFragment {
private final boolean finalFragment;
public FinalFragmentByteBufInputStream(ByteBuf buffer) {
this(buffer, buffer.readableBytes());
}
public FinalFragmentByteBufInputStream(ByteBuf buffer, int length) {
this(buffer, length, false);
}
public FinalFragmentByteBufInputStream(ByteBuf buffer, boolean releaseOnClose) {
this(buffer, buffer.readableBytes(), releaseOnClose);
}
public FinalFragmentByteBufInputStream(ByteBuf buffer, boolean releaseOnClose, boolean finalFragment) {
this(buffer, buffer.readableBytes(), releaseOnClose, finalFragment);
}
public FinalFragmentByteBufInputStream(ByteBuf buffer, int length, boolean releaseOnClose) {
this(buffer, length, releaseOnClose, false);
}
public FinalFragmentByteBufInputStream(ByteBuf buffer, int length, boolean releaseOnClose, boolean finalFragment) {
super(buffer, length, releaseOnClose);
this.finalFragment = finalFragment;
}
@Override
public boolean isFinalFragment() {
return finalFragment;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragmentStreamingDecoder.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/FinalFragmentStreamingDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
import org.apache.dubbo.remoting.http12.CompositeInputStream;
import org.apache.dubbo.remoting.http12.exception.DecodeException;
import org.apache.dubbo.remoting.http12.message.StreamingDecoder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FinalFragmentStreamingDecoder implements StreamingDecoder {
private boolean inDelivery;
private boolean pendingDelivery;
private boolean closed;
private boolean closing;
protected final CompositeInputStream accumulate = new CompositeInputStream();
protected FragmentListener listener;
@Override
public void request(int numMessages) {}
@Override
public void decode(InputStream inputStream) throws DecodeException {
if (closing || closed) {
// ignored
return;
}
accumulate.addInputStream(inputStream);
if (inputStream instanceof FinalFragment && ((FinalFragment) inputStream).isFinalFragment()) {
pendingDelivery = true;
deliver();
}
}
@Override
public void close() {
closing = true;
deliver();
}
@Override
public void onStreamClosed() {
if (closed) {
return;
}
closed = true;
try {
accumulate.close();
} catch (IOException e) {
throw new DecodeException(e);
}
}
@Override
public void setFragmentListener(FragmentListener listener) {
this.listener = listener;
}
private void deliver() {
if (inDelivery) {
return;
}
if (closed) {
return;
}
inDelivery = true;
try {
if (pendingDelivery) {
processBody();
pendingDelivery = false;
}
if (closing) {
if (!closed) {
closed = true;
accumulate.close();
listener.onClose();
}
}
} catch (IOException e) {
throw new DecodeException(e);
} finally {
inDelivery = false;
}
}
private void processBody() throws IOException {
byte[] rawMessage = readRawMessage(accumulate, accumulate.available());
InputStream inputStream = new ByteArrayInputStream(rawMessage);
invokeListener(inputStream);
}
protected void invokeListener(InputStream inputStream) {
this.listener.onFragmentMessage(inputStream);
}
protected byte[] readRawMessage(InputStream inputStream, int length) throws IOException {
byte[] data = new byte[length];
inputStream.read(data, 0, length);
return data;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/WebSocketTransportListener.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/WebSocketTransportListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket;
import org.apache.dubbo.remoting.http12.h2.Http2TransportListener;
public interface WebSocketTransportListener extends Http2TransportListener {}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/WebSocketProtocolSelectorHandler.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/WebSocketProtocolSelectorHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket.netty4;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.http12.command.HttpWriteQueue;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.command.Http2WriteQueueChannel;
import org.apache.dubbo.remoting.http12.netty4.HttpWriteQueueHandler;
import org.apache.dubbo.remoting.http12.netty4.h2.NettyHttp2FrameHandler;
import org.apache.dubbo.remoting.websocket.WebSocketServerTransportListenerFactory;
import org.apache.dubbo.remoting.websocket.WebSocketTransportListener;
import org.apache.dubbo.rpc.model.FrameworkModel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
public class WebSocketProtocolSelectorHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
private final URL url;
private final FrameworkModel frameworkModel;
private final TripleConfig tripleConfig;
private final WebSocketServerTransportListenerFactory defaultWebSocketServerTransportListenerFactory;
public WebSocketProtocolSelectorHandler(
URL url,
FrameworkModel frameworkModel,
TripleConfig tripleConfig,
WebSocketServerTransportListenerFactory defaultWebSocketServerTransportListenerFactory) {
this.url = url;
this.frameworkModel = frameworkModel;
this.tripleConfig = tripleConfig;
this.defaultWebSocketServerTransportListenerFactory = defaultWebSocketServerTransportListenerFactory;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
H2StreamChannel streamChannel = new NettyWebSocketChannel(ctx.channel(), tripleConfig);
HttpWriteQueueHandler writeQueueHandler = ctx.channel().pipeline().get(HttpWriteQueueHandler.class);
if (writeQueueHandler != null) {
HttpWriteQueue writeQueue = writeQueueHandler.getWriteQueue();
streamChannel = new Http2WriteQueueChannel(streamChannel, writeQueue);
}
WebSocketTransportListener webSocketTransportListener =
defaultWebSocketServerTransportListenerFactory.newInstance(streamChannel, url, frameworkModel);
ctx.channel().closeFuture().addListener(future -> webSocketTransportListener.close());
ctx.pipeline()
.addLast(new NettyHttp2FrameHandler(streamChannel, webSocketTransportListener))
.remove(this);
ctx.fireChannelRead(msg.retain());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/NettyWebSocketChannel.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/NettyWebSocketChannel.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket.netty4;
import org.apache.dubbo.config.nested.TripleConfig;
import org.apache.dubbo.remoting.http12.HttpMetadata;
import org.apache.dubbo.remoting.http12.HttpOutputMessage;
import org.apache.dubbo.remoting.http12.LimitedByteBufOutputStream;
import org.apache.dubbo.remoting.http12.h2.H2StreamChannel;
import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2OutputMessageFrame;
import org.apache.dubbo.remoting.http12.netty4.NettyHttpChannelFutureListener;
import java.net.SocketAddress;
import java.util.concurrent.CompletableFuture;
import io.netty.channel.Channel;
public class NettyWebSocketChannel implements H2StreamChannel {
private final Channel channel;
private final TripleConfig tripleConfig;
public NettyWebSocketChannel(Channel channel, TripleConfig tripleConfig) {
this.channel = channel;
this.tripleConfig = tripleConfig;
}
@Override
public CompletableFuture<Void> writeResetFrame(long errorCode) {
NettyHttpChannelFutureListener futureListener = new NettyHttpChannelFutureListener();
channel.close().addListener(futureListener);
return futureListener;
}
@Override
public Http2OutputMessage newOutputMessage(boolean endStream) {
return new Http2OutputMessageFrame(
new LimitedByteBufOutputStream(
channel.alloc().buffer(), tripleConfig.getMaxResponseBodySizeOrDefault()),
endStream);
}
@Override
public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) {
NettyHttpChannelFutureListener futureListener = new NettyHttpChannelFutureListener();
channel.write(httpMetadata).addListener(futureListener);
return futureListener;
}
@Override
public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) {
NettyHttpChannelFutureListener futureListener = new NettyHttpChannelFutureListener();
channel.write(httpOutputMessage).addListener(futureListener);
return futureListener;
}
@Override
public SocketAddress remoteAddress() {
return channel.remoteAddress();
}
@Override
public SocketAddress localAddress() {
return channel.localAddress();
}
@Override
public void flush() {
channel.flush();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/WebSocketFrameCodec.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/WebSocketFrameCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket.netty4;
import org.apache.dubbo.common.io.StreamUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.http12.HttpHeaderNames;
import org.apache.dubbo.remoting.http12.HttpHeaders;
import org.apache.dubbo.remoting.http12.HttpMethods;
import org.apache.dubbo.remoting.http12.HttpStatus;
import org.apache.dubbo.remoting.http12.h2.Http2Header;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessage;
import org.apache.dubbo.remoting.http12.h2.Http2InputMessageFrame;
import org.apache.dubbo.remoting.http12.h2.Http2MetadataFrame;
import org.apache.dubbo.remoting.http12.h2.Http2OutputMessage;
import org.apache.dubbo.remoting.http12.netty4.h1.NettyHttp1HttpHeaders;
import org.apache.dubbo.remoting.websocket.FinalFragmentByteBufInputStream;
import org.apache.dubbo.remoting.websocket.WebSocketHeaderNames;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketCloseStatus;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http2.DefaultHttp2ResetFrame;
public class WebSocketFrameCodec extends ChannelDuplexHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) {
Http2InputMessage http2InputMessage = onDataFrame((WebSocketFrame) msg);
super.channelRead(ctx, http2InputMessage);
} else if (msg instanceof CloseWebSocketFrame) {
Object closeMessage = onCloseFrame((CloseWebSocketFrame) msg);
super.channelRead(ctx, closeMessage);
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof Http2OutputMessage) {
WebSocketFrame webSocketFrame = encodeWebSocketFrame(ctx, (Http2OutputMessage) msg);
super.write(ctx, webSocketFrame, promise);
} else if (msg instanceof Http2Header) {
Http2Header http2Header = (Http2Header) msg;
if (http2Header.isEndStream()) {
CloseWebSocketFrame closeWebSocketFrame = encodeCloseWebSocketFrame(http2Header);
super.write(ctx, closeWebSocketFrame, promise);
}
} else {
super.write(ctx, msg, promise);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
Http2Header http2Header = onHandshakeComplete((WebSocketServerProtocolHandler.HandshakeComplete) evt);
super.channelRead(ctx, http2Header);
} else {
super.userEventTriggered(ctx, evt);
}
}
private Http2Header onHandshakeComplete(WebSocketServerProtocolHandler.HandshakeComplete evt) {
HttpHeaders httpHeaders = new NettyHttp1HttpHeaders(evt.requestHeaders());
httpHeaders.set(HttpHeaderNames.PATH.getName(), evt.requestUri());
httpHeaders.set(HttpHeaderNames.METHOD.getName(), HttpMethods.POST.name());
return new Http2MetadataFrame(httpHeaders);
}
private Http2InputMessageFrame onDataFrame(WebSocketFrame webSocketFrame) {
ByteBuf data = webSocketFrame.content();
return new Http2InputMessageFrame(
new FinalFragmentByteBufInputStream(data, true, webSocketFrame.isFinalFragment()), false);
}
private Object onCloseFrame(CloseWebSocketFrame closeWebSocketFrame) {
if (closeWebSocketFrame.statusCode() != WebSocketCloseStatus.NORMAL_CLOSURE.code()) {
return new DefaultHttp2ResetFrame(closeWebSocketFrame.statusCode());
}
return new Http2InputMessageFrame(StreamUtils.EMPTY, true);
}
private CloseWebSocketFrame encodeCloseWebSocketFrame(Http2Header http2Header) {
HttpHeaders headers = http2Header.headers();
List<String> statusHeaders = headers.remove(HttpHeaderNames.STATUS.getName());
WebSocketCloseStatus status = WebSocketCloseStatus.NORMAL_CLOSURE;
if (CollectionUtils.isNotEmpty(statusHeaders)
&& !HttpStatus.OK.getStatusString().equals(statusHeaders.get(0))) {
List<String> messageHeaders = headers.remove(WebSocketHeaderNames.WEBSOCKET_MESSAGE.getName());
status = new WebSocketCloseStatus(
WebSocketCloseStatus.INTERNAL_SERVER_ERROR.code(),
CollectionUtils.isNotEmpty(messageHeaders)
? messageHeaders.get(0)
: WebSocketCloseStatus.INTERNAL_SERVER_ERROR.reasonText());
}
return new CloseWebSocketFrame(status);
}
private WebSocketFrame encodeWebSocketFrame(ChannelHandlerContext ctx, Http2OutputMessage outputMessage)
throws IOException {
OutputStream body = outputMessage.getBody();
if (body == null) {
return new BinaryWebSocketFrame();
}
if (body instanceof ByteBufOutputStream) {
ByteBuf buffer = ((ByteBufOutputStream) body).buffer();
return new BinaryWebSocketFrame(buffer);
}
throw new IllegalArgumentException("Http2OutputMessage body must be ByteBufOutputStream");
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/WebSocketServerUpgradeCodec.java | dubbo-remoting/dubbo-remoting-websocket/src/main/java/org/apache/dubbo/remoting/websocket/netty4/WebSocketServerUpgradeCodec.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.websocket.netty4;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpServerUpgradeHandler;
public class WebSocketServerUpgradeCodec implements HttpServerUpgradeHandler.UpgradeCodec {
private final List<Class<? extends ChannelHandler>> shouldRemoveChannelHandlers;
private final ChannelHandler[] channelHandlers;
public WebSocketServerUpgradeCodec(
List<Class<? extends ChannelHandler>> shouldRemoveChannelHandlers, ChannelHandler... channelHandlers) {
this.shouldRemoveChannelHandlers = shouldRemoveChannelHandlers;
this.channelHandlers = channelHandlers;
}
@Override
public Collection<CharSequence> requiredUpgradeHeaders() {
return Collections.emptyList();
}
@Override
public boolean prepareUpgradeResponse(
ChannelHandlerContext ctx, FullHttpRequest upgradeRequest, HttpHeaders upgradeHeaders) {
if (shouldRemoveChannelHandlers != null) {
for (Class<? extends ChannelHandler> shouldRemoveChannelHandler : shouldRemoveChannelHandlers) {
ctx.pipeline().remove(shouldRemoveChannelHandler);
}
}
if (channelHandlers != null) {
for (ChannelHandler channelHandler : channelHandlers) {
ctx.pipeline().addLast(channelHandler);
}
}
return false;
}
@Override
public void upgradeTo(ChannelHandlerContext ctx, FullHttpRequest upgradeRequest) {}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient.CuratorWatcherImpl;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.collect.Lists;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.WatcherRemoveCuratorFramework;
import org.apache.curator.framework.api.CreateBuilder;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.api.DeleteBuilder;
import org.apache.curator.framework.api.ExistsBuilder;
import org.apache.curator.framework.api.GetChildrenBuilder;
import org.apache.curator.framework.api.GetDataBuilder;
import org.apache.curator.framework.api.Pathable;
import org.apache.curator.framework.api.SetDataBuilder;
import org.apache.curator.framework.api.WatchPathable;
import org.apache.curator.framework.listen.StandardListenerManager;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import org.mockito.stubbing.Answer;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstructionWithAnswer;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class Curator5ZookeeperClientTest {
private static Curator5ZookeeperClient curatorClient;
private static int zookeeperServerMockPort1;
private static String zookeeperConnectionAddress1;
private static MockedStatic<CuratorFrameworkFactory> curatorFrameworkFactoryMockedStatic;
CuratorFrameworkFactory.Builder spyBuilder = CuratorFrameworkFactory.builder();
private CuratorFramework mockCuratorFramework;
private CreateBuilder mockCreateBuilder;
private ExistsBuilder mockExistsBuilder;
private GetChildrenBuilder mockGetChildrenBuilder;
private DeleteBuilder mockDeleteBuilder;
private GetDataBuilder mockGetDataBuilder;
private SetDataBuilder mockSetDataBuilder;
private CuratorZookeeperClient mockCuratorZookeeperClient;
private WatcherRemoveCuratorFramework mockWatcherRemoveCuratorFramework;
private Answer<String> createAnswer;
@BeforeAll
public static void setUp() throws Exception {
zookeeperServerMockPort1 = 2181;
zookeeperConnectionAddress1 = "zookeeper://localhost:" + zookeeperServerMockPort1;
// mock begin
// create mock bean begin
CuratorFrameworkFactory.Builder realBuilder = CuratorFrameworkFactory.builder();
CuratorFrameworkFactory.Builder spyBuilder = spy(realBuilder);
curatorFrameworkFactoryMockedStatic = mockStatic(CuratorFrameworkFactory.class);
curatorFrameworkFactoryMockedStatic
.when(CuratorFrameworkFactory::builder)
.thenReturn(spyBuilder);
}
@BeforeEach
public void init() throws Exception {
mockCreateBuilder = mock(CreateBuilder.class);
mockExistsBuilder = mock(ExistsBuilder.class);
mockDeleteBuilder = mock(DeleteBuilder.class);
mockCuratorFramework = mock(CuratorFramework.class);
mockGetChildrenBuilder = mock(GetChildrenBuilder.class);
mockGetDataBuilder = mock(GetDataBuilder.class);
mockCuratorZookeeperClient = mock(CuratorZookeeperClient.class);
mockWatcherRemoveCuratorFramework = mock(WatcherRemoveCuratorFramework.class);
mockSetDataBuilder = mock(SetDataBuilder.class);
doReturn(mockCuratorFramework).when(spyBuilder).build();
when(mockCuratorFramework.blockUntilConnected(anyInt(), any())).thenReturn(true);
when(mockCuratorFramework.getConnectionStateListenable()).thenReturn(StandardListenerManager.standard());
when(mockCuratorFramework.create()).thenReturn(mockCreateBuilder);
when(mockCuratorFramework.checkExists()).thenReturn(mockExistsBuilder);
when(mockCuratorFramework.getChildren()).thenReturn(mockGetChildrenBuilder);
when(mockCuratorFramework.getZookeeperClient()).thenReturn(mockCuratorZookeeperClient);
when(mockCuratorFramework.newWatcherRemoveCuratorFramework()).thenReturn(mockWatcherRemoveCuratorFramework);
when(mockCuratorZookeeperClient.isConnected()).thenReturn(true);
when(mockCuratorFramework.delete()).thenReturn(mockDeleteBuilder);
when(mockCreateBuilder.withMode(any())).thenReturn(mockCreateBuilder);
when(mockDeleteBuilder.deletingChildrenIfNeeded()).thenReturn(mockDeleteBuilder);
when(mockDeleteBuilder.forPath(any())).then((Answer<Void>) invocationOnMock -> null);
when(mockCuratorFramework.getData()).thenReturn(mockGetDataBuilder);
when(mockCuratorFramework.setData()).thenReturn(mockSetDataBuilder);
when(mockSetDataBuilder.withVersion(anyInt())).thenReturn(mockSetDataBuilder);
List<String> paths = new ArrayList<>();
createAnswer = invocationOnMock -> {
String param = invocationOnMock.getArgument(0);
if (paths.contains(param)) {
throw new NodeExistsException("node existed: " + param);
}
paths.add(invocationOnMock.getArgument(0));
return invocationOnMock.getArgument(0);
};
when(mockCreateBuilder.forPath(anyString())).thenAnswer(createAnswer);
when(mockCreateBuilder.forPath(anyString(), any())).thenAnswer(createAnswer);
when(mockExistsBuilder.forPath(anyString())).thenAnswer(i -> {
if (paths.contains(i.getArgument(0))) {
return new Stat();
}
return null;
});
when(mockDeleteBuilder.forPath(anyString())).thenAnswer(i -> {
if (paths.contains(i.getArgument(0))) {
paths.remove(i.getArgument(0));
}
return null;
});
curatorClient = new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService"));
}
@Test
void testCheckExists() {
String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers";
curatorClient.create(path, false, true);
assertThat(curatorClient.checkExists(path), is(true));
assertThat(curatorClient.checkExists(path + "/noneexits"), is(false));
}
@Test
void testChildrenPath() throws Exception {
when(mockGetChildrenBuilder.forPath(any())).thenReturn(Lists.newArrayList("provider1", "provider2"));
String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers";
curatorClient.create(path, false, true);
curatorClient.create(path + "/provider1", false, true);
curatorClient.create(path + "/provider2", false, true);
List<String> children = curatorClient.getChildren(path);
assertThat(children.size(), is(2));
}
@Test
@Timeout(value = 2)
public void testChildrenListener() throws Exception {
String path = "/dubbo/org.apache.dubbo.demo.DemoListenerService/providers";
curatorClient.create(path, false, true);
final CountDownLatch countDownLatch = new CountDownLatch(1);
when(mockGetChildrenBuilder.usingWatcher(any(CuratorWatcher.class))).thenReturn(mockGetChildrenBuilder);
when(mockGetChildrenBuilder.forPath(any())).thenReturn(Lists.newArrayList("providers"));
CuratorWatcherImpl watcher = new CuratorWatcherImpl() {
@Override
public void process(WatchedEvent watchedEvent) {
countDownLatch.countDown();
}
};
curatorClient.addTargetChildListener(path, watcher);
watcher.process(new WatchedEvent(Event.EventType.NodeDeleted, KeeperState.Closed, "providers"));
curatorClient.createPersistent(path + "/provider1", true);
countDownLatch.await();
}
@Test
void testWithInvalidServer() throws InterruptedException {
when(mockCuratorFramework.blockUntilConnected(anyInt(), any())).thenReturn(false);
Assertions.assertThrows(IllegalStateException.class, () -> {
curatorClient = new Curator5ZookeeperClient(URL.valueOf("zookeeper://127.0.0.1:1/service?timeout=1000"));
curatorClient.create("/testPath", true, true);
});
}
@Test
void testWithInvalidServerWithoutCheck() throws InterruptedException {
when(mockCuratorFramework.blockUntilConnected(anyInt(), any())).thenReturn(false);
URL url = URL.valueOf("zookeeper://127.0.0.1:1/service").addParameter(CHECK_KEY, false);
Assertions.assertDoesNotThrow(() -> {
curatorClient = new Curator5ZookeeperClient(url);
curatorClient.create("/testPath", true, true);
});
}
@Test
void testRemoveChildrenListener() throws Exception {
ChildListener childListener = mock(ChildListener.class);
when(mockGetChildrenBuilder.usingWatcher(any(CuratorWatcher.class))).thenReturn(mockGetChildrenBuilder);
when(mockGetChildrenBuilder.forPath(any())).thenReturn(Lists.newArrayList("children"));
curatorClient.addChildListener("/children", childListener);
curatorClient.removeChildListener("/children", childListener);
}
@Test
void testCreateExistingPath() {
curatorClient.create("/pathOne", false, true);
curatorClient.create("/pathOne", false, true);
}
@Test
void testConnectedStatus() {
curatorClient.createEphemeral("/testPath", true);
boolean connected = curatorClient.isConnected();
assertThat(connected, is(true));
}
@Test
void testCreateContent4Persistent() throws Exception {
String path = "/curatorTest4CrContent/content.data";
String content = "createContentTest";
curatorClient.delete(path);
assertThat(curatorClient.checkExists(path), is(false));
assertNull(curatorClient.getContent(path));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> content.getBytes());
curatorClient.createOrUpdate(path, content, false);
assertThat(curatorClient.checkExists(path), is(true));
assertEquals(curatorClient.getContent(path), content);
}
@Test
void testCreateContent4Temp() throws Exception {
String path = "/curatorTest4CrContent/content.data";
String content = "createContentTest";
curatorClient.delete(path);
assertThat(curatorClient.checkExists(path), is(false));
assertNull(curatorClient.getContent(path));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> content.getBytes());
curatorClient.createOrUpdate(path, content, true);
assertThat(curatorClient.checkExists(path), is(true));
assertEquals(curatorClient.getContent(path), content);
}
@Test
void testCreatePersistentFailed() {
String path = "/dubbo/test/path";
curatorClient.delete(path);
curatorClient.create(path, false, true);
Assertions.assertTrue(curatorClient.checkExists(path));
curatorClient.createPersistent(path, true);
Assertions.assertTrue(curatorClient.checkExists(path));
curatorClient.createPersistent(path, true);
Assertions.assertTrue(curatorClient.checkExists(path));
Assertions.assertThrows(IllegalStateException.class, () -> {
curatorClient.createPersistent(path, false);
});
Assertions.assertTrue(curatorClient.checkExists(path));
}
@Test
void testCreateEphemeralFailed() {
String path = "/dubbo/test/path";
curatorClient.delete(path);
curatorClient.create(path, true, true);
Assertions.assertTrue(curatorClient.checkExists(path));
curatorClient.createEphemeral(path, true);
Assertions.assertTrue(curatorClient.checkExists(path));
curatorClient.createEphemeral(path, true);
Assertions.assertTrue(curatorClient.checkExists(path));
Assertions.assertThrows(IllegalStateException.class, () -> {
curatorClient.createEphemeral(path, false);
});
Assertions.assertTrue(curatorClient.checkExists(path));
}
@Test
void testAddTargetDataListener() throws Exception {
String listenerPath = "/dubbo/service.name/configuration";
String path = listenerPath + "/dat/data";
String value = "vav";
curatorClient.createOrUpdate(path + "/d.json", value, true);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> value.getBytes());
String valueFromCache = curatorClient.getContent(path + "/d.json");
Assertions.assertEquals(value, valueFromCache);
final AtomicInteger atomicInteger = new AtomicInteger(0);
NodeCache mockNodeCache = mock(NodeCache.class);
MockedConstruction<NodeCache> mockedConstruction =
mockConstructionWithAnswer(NodeCache.class, invocationOnMock -> invocationOnMock
.getMethod()
.invoke(mockNodeCache, invocationOnMock.getArguments()));
when(mockNodeCache.getListenable()).thenReturn(StandardListenerManager.standard());
Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener =
new Curator5ZookeeperClient.NodeCacheListenerImpl() {
@Override
public void nodeChanged() {
atomicInteger.incrementAndGet();
}
};
curatorClient.addTargetDataListener(path + "/d.json", nodeCacheListener);
valueFromCache = curatorClient.getContent(path + "/d.json");
Assertions.assertNotNull(valueFromCache);
int currentCount1 = atomicInteger.get();
when(mockSetDataBuilder.forPath(any(), any())).then(invocationOnMock -> {
nodeCacheListener.nodeChanged();
return null;
});
curatorClient.getClient().setData().forPath(path + "/d.json", "foo".getBytes());
await().until(() -> atomicInteger.get() > currentCount1);
int currentCount2 = atomicInteger.get();
curatorClient.getClient().setData().forPath(path + "/d.json", "bar".getBytes());
await().until(() -> atomicInteger.get() > currentCount2);
int currentCount3 = atomicInteger.get();
when(mockDeleteBuilder.forPath(any())).then(invocationOnMock -> {
nodeCacheListener.nodeChanged();
return null;
});
curatorClient.delete(path + "/d.json");
when(mockGetDataBuilder.forPath(any())).thenReturn(null);
valueFromCache = curatorClient.getContent(path + "/d.json");
Assertions.assertNull(valueFromCache);
await().until(() -> atomicInteger.get() > currentCount3);
mockedConstruction.close();
}
@Test
void testPersistentCas1() throws Exception {
// test create failed when others create success
String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService";
AtomicReference<Runnable> runnable = new AtomicReference<>();
Curator5ZookeeperClient curatorClient =
new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) {
@Override
protected void createPersistent(String path, String data, boolean faultTolerant) {
if (runnable.get() != null) {
runnable.get().run();
}
super.createPersistent(path, data, faultTolerant);
}
@Override
protected void update(String path, String data, int version) {
if (runnable.get() != null) {
runnable.get().run();
}
super.update(path, data, version);
}
};
curatorClient.delete(path);
runnable.set(() -> {
try {
mockCuratorFramework.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
when(mockCreateBuilder.forPath(any())).then(invocationOnMock -> {
String value;
try {
value = createAnswer.answer(invocationOnMock);
} catch (Exception e) {
throw e;
}
try {
runnable.get().run();
} catch (Exception ignored) {
}
return value;
});
Assertions.assertThrows(
IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, 0));
Assertions.assertEquals("version x", curatorClient.getContent(path));
mockCuratorFramework.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8));
when(mockGetDataBuilder.storingStatIn(any())).thenReturn(new WatchPathable<byte[]>() {
@Override
public byte[] forPath(String s) throws Exception {
return mockGetDataBuilder.forPath(s);
}
@Override
public Pathable<byte[]> watched() {
return null;
}
@Override
public Pathable<byte[]> usingWatcher(Watcher watcher) {
return null;
}
@Override
public Pathable<byte[]> usingWatcher(CuratorWatcher curatorWatcher) {
return null;
}
});
ConfigItem configItem = curatorClient.getConfigItem(path);
runnable.set(() -> {
try {
mockCuratorFramework.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
when(mockSetDataBuilder.forPath(any(), any())).thenThrow(new IllegalStateException());
int version1 = ((Stat) configItem.getTicket()).getVersion();
Assertions.assertThrows(
IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", false, version1));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
Assertions.assertEquals("version x", curatorClient.getContent(path));
runnable.set(null);
configItem = curatorClient.getConfigItem(path);
int version2 = ((Stat) configItem.getTicket()).getVersion();
doReturn(null).when(mockSetDataBuilder).forPath(any(), any());
curatorClient.createOrUpdate(path, "version 2", false, version2);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 2".getBytes());
Assertions.assertEquals("version 2", curatorClient.getContent(path));
curatorClient.close();
}
@Test
void testPersistentCas2() throws Exception {
// test update failed when others create success
String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService";
Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService"));
curatorClient.delete(path);
curatorClient.createOrUpdate(path, "version x", false);
Assertions.assertThrows(
IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", false, null));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
Assertions.assertEquals("version x", curatorClient.getContent(path));
curatorClient.close();
}
@Test
void testPersistentNonVersion() throws Exception {
String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService";
AtomicReference<Runnable> runnable = new AtomicReference<>();
Curator5ZookeeperClient curatorClient =
new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) {
@Override
protected void createPersistent(String path, String data, boolean faultTolerant) {
if (runnable.get() != null) {
runnable.get().run();
}
super.createPersistent(path, data, faultTolerant);
}
@Override
protected void update(String path, String data, int version) {
if (runnable.get() != null) {
runnable.get().run();
}
super.update(path, data, version);
}
};
curatorClient.delete(path);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
when(mockCreateBuilder.forPath(any())).then(invocationOnMock -> {
String value;
try {
value = createAnswer.answer(invocationOnMock);
} catch (Exception e) {
throw e;
}
try {
runnable.get().run();
} catch (Exception ignored) {
}
return value;
});
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 0".getBytes());
curatorClient.createOrUpdate(path, "version 0", false);
Assertions.assertEquals("version 0", curatorClient.getContent(path));
curatorClient.delete(path);
runnable.set(() -> {
try {
mockCuratorFramework.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 1".getBytes());
curatorClient.createOrUpdate(path, "version 1", false);
Assertions.assertEquals("version 1", curatorClient.getContent(path));
runnable.set(() -> {
try {
mockCuratorFramework.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
curatorClient.createOrUpdate(path, "version 2", false);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 2".getBytes());
Assertions.assertEquals("version 2", curatorClient.getContent(path));
runnable.set(null);
curatorClient.createOrUpdate(path, "version 3", false);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 3".getBytes());
Assertions.assertEquals("version 3", curatorClient.getContent(path));
curatorClient.close();
}
@Test
void testEphemeralCas1() throws Exception {
// test create failed when others create success
String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService";
AtomicReference<Runnable> runnable = new AtomicReference<>();
Curator5ZookeeperClient curatorClient =
new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) {
@Override
protected void createEphemeral(String path, String data, boolean faultTolerant) {
if (runnable.get() != null) {
runnable.get().run();
}
super.createPersistent(path, data, faultTolerant);
}
@Override
protected void update(String path, String data, int version) {
if (runnable.get() != null) {
runnable.get().run();
}
super.update(path, data, version);
}
};
curatorClient.delete(path);
when(mockCreateBuilder.forPath(any())).then(invocationOnMock -> {
String value;
try {
value = createAnswer.answer(invocationOnMock);
} catch (Exception e) {
throw e;
}
try {
runnable.get().run();
} catch (Exception ignored) {
}
return value;
});
runnable.set(() -> {
try {
mockCuratorFramework.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
Assertions.assertThrows(
IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, 0));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
Assertions.assertEquals("version x", curatorClient.getContent(path));
mockCuratorFramework.setData().forPath(path, "version 1".getBytes(StandardCharsets.UTF_8));
when(mockGetDataBuilder.storingStatIn(any())).thenReturn(new WatchPathable<byte[]>() {
@Override
public byte[] forPath(String s) throws Exception {
return mockGetDataBuilder.forPath(s);
}
@Override
public Pathable<byte[]> watched() {
return null;
}
@Override
public Pathable<byte[]> usingWatcher(Watcher watcher) {
return null;
}
@Override
public Pathable<byte[]> usingWatcher(CuratorWatcher curatorWatcher) {
return null;
}
});
ConfigItem configItem = curatorClient.getConfigItem(path);
runnable.set(() -> {
try {
mockCuratorFramework.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
int version1 = ((Stat) configItem.getTicket()).getVersion();
when(mockSetDataBuilder.forPath(any(), any())).thenThrow(new IllegalStateException());
Assertions.assertThrows(
IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 2", true, version1));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
Assertions.assertEquals("version x", curatorClient.getContent(path));
runnable.set(null);
configItem = curatorClient.getConfigItem(path);
int version2 = ((Stat) configItem.getTicket()).getVersion();
doReturn(null).when(mockSetDataBuilder).forPath(any(), any());
curatorClient.createOrUpdate(path, "version 2", true, version2);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 2".getBytes());
Assertions.assertEquals("version 2", curatorClient.getContent(path));
curatorClient.close();
}
@Test
void testEphemeralCas2() throws Exception {
// test update failed when others create success
String path = "/dubbo/mapping/org.apache.dubbo.demo.DemoService";
Curator5ZookeeperClient curatorClient = new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService"));
curatorClient.delete(path);
curatorClient.createOrUpdate(path, "version x", true);
Assertions.assertThrows(
IllegalStateException.class, () -> curatorClient.createOrUpdate(path, "version 1", true, null));
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version x".getBytes());
Assertions.assertEquals("version x", curatorClient.getContent(path));
curatorClient.close();
}
@Test
void testEphemeralNonVersion() throws Exception {
String path = "/dubbo/metadata/org.apache.dubbo.demo.DemoService";
AtomicReference<Runnable> runnable = new AtomicReference<>();
Curator5ZookeeperClient curatorClient =
new Curator5ZookeeperClient(
URL.valueOf(zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService")) {
@Override
protected void createPersistent(String path, String data, boolean faultTolerant) {
if (runnable.get() != null) {
runnable.get().run();
}
super.createPersistent(path, data, faultTolerant);
}
@Override
protected void update(String path, String data, int version) {
if (runnable.get() != null) {
runnable.get().run();
}
super.update(path, data, version);
}
};
curatorClient.delete(path);
curatorClient.createOrUpdate(path, "version 0", true);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 0".getBytes());
Assertions.assertEquals("version 0", curatorClient.getContent(path));
curatorClient.delete(path);
runnable.set(() -> {
try {
mockCuratorFramework.create().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw new RuntimeException(e);
}
});
curatorClient.createOrUpdate(path, "version 1", true);
when(mockGetDataBuilder.forPath(any())).then(invocationOnMock -> "version 1".getBytes());
Assertions.assertEquals("version 1", curatorClient.getContent(path));
runnable.set(() -> {
try {
mockCuratorFramework.setData().forPath(path, "version x".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | true |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientManagerTest.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClientManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import org.apache.dubbo.common.URL;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.listen.StandardListenerManager;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class Curator5ZookeeperClientManagerTest {
private ZookeeperClient zookeeperClient;
private static URL zookeeperUrl;
private static MockedStatic<CuratorFrameworkFactory> curatorFrameworkFactoryMockedStatic;
private static CuratorFramework mockCuratorFramework;
@BeforeAll
public static void beforeAll() {
String zookeeperConnectionAddress1 = "zookeeper://127.0.0.1:2181";
zookeeperUrl = URL.valueOf(zookeeperConnectionAddress1 + "/service");
CuratorFrameworkFactory.Builder realBuilder = CuratorFrameworkFactory.builder();
CuratorFrameworkFactory.Builder spyBuilder = spy(realBuilder);
curatorFrameworkFactoryMockedStatic = mockStatic(CuratorFrameworkFactory.class);
curatorFrameworkFactoryMockedStatic
.when(CuratorFrameworkFactory::builder)
.thenReturn(spyBuilder);
mockCuratorFramework = mock(CuratorFramework.class);
doReturn(mockCuratorFramework).when(spyBuilder).build();
}
@BeforeEach
public void setUp() throws InterruptedException {
when(mockCuratorFramework.blockUntilConnected(anyInt(), any())).thenReturn(true);
when(mockCuratorFramework.getConnectionStateListenable()).thenReturn(StandardListenerManager.standard());
zookeeperClient = new ZookeeperClientManager().connect(zookeeperUrl);
}
@Test
void testZookeeperClient() {
assertThat(zookeeperClient, not(nullValue()));
zookeeperClient.close();
}
@Test
void testRegistryCheckConnectDefault() throws InterruptedException {
when(mockCuratorFramework.blockUntilConnected(anyInt(), any())).thenReturn(false);
ZookeeperClientManager zookeeperClientManager = new ZookeeperClientManager();
Assertions.assertThrowsExactly(IllegalStateException.class, () -> {
zookeeperClientManager.connect(zookeeperUrl);
});
}
@Test
void testRegistryNotCheckConnect() throws InterruptedException {
when(mockCuratorFramework.blockUntilConnected(anyInt(), any())).thenReturn(false);
URL url = zookeeperUrl.addParameter(CHECK_KEY, false);
ZookeeperClientManager zookeeperClientManager = new ZookeeperClientManager();
Assertions.assertDoesNotThrow(() -> {
zookeeperClientManager.connect(url);
});
}
@AfterAll
public static void afterAll() {
curatorFrameworkFactoryMockedStatic.close();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/ZookeeperClientManagerTest.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/test/java/org/apache/dubbo/remoting/zookeeper/curator5/support/ZookeeperClientManagerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.zookeeper.curator5.Curator5ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.curator5.ZookeeperClientManager;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockConstructionWithAnswer;
import static org.mockito.Mockito.when;
/**
* ZookeeperManagerTest
*/
class ZookeeperClientManagerTest {
private ZookeeperClient zookeeperClient;
private ZookeeperClientManager zookeeperClientManager;
private static Curator5ZookeeperClient mockedCurator5ZookeeperClient;
private static MockedConstruction<Curator5ZookeeperClient> mockedCurator5ZookeeperClientConstruction;
private static int zookeeperServerPort1 = 2181;
private static int zookeeperServerPort2 = 2182;
private static String zookeeperConnectionAddress1 = "zookeeper://127.0.0.1:2181";
private static String zookeeperConnectionAddress2 = "zookeeper://127.0.0.1:2182";
@BeforeAll
public static void beforeAll() {
mockedCurator5ZookeeperClient = mock(Curator5ZookeeperClient.class);
mockedCurator5ZookeeperClientConstruction =
mockConstructionWithAnswer(Curator5ZookeeperClient.class, invocationOnMock -> invocationOnMock
.getMethod()
.invoke(mockedCurator5ZookeeperClient, invocationOnMock.getArguments()));
}
@BeforeEach
public void setUp() throws Exception {
zookeeperClient = new ZookeeperClientManager().connect(URL.valueOf(zookeeperConnectionAddress1 + "/service"));
zookeeperClientManager = new ZookeeperClientManager();
}
@Test
void testZookeeperClient() {
assertThat(zookeeperClient, not(nullValue()));
zookeeperClient.close();
}
@Test
void testGetURLBackupAddress() {
URL url = URL.valueOf(
zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:" + 9099
+ "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
List<String> stringList = zookeeperClientManager.getURLBackupAddress(url);
Assertions.assertEquals(stringList.size(), 2);
Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1);
Assertions.assertEquals(stringList.get(1), "127.0.0.1:9099");
}
@Test
void testGetURLBackupAddressNoBack() {
URL url = URL.valueOf(
zookeeperConnectionAddress1
+ "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
List<String> stringList = zookeeperClientManager.getURLBackupAddress(url);
Assertions.assertEquals(stringList.size(), 1);
Assertions.assertEquals(stringList.get(0), "127.0.0.1:" + zookeeperServerPort1);
}
@Test
void testFetchAndUpdateZookeeperClientCache() {
URL url = URL.valueOf(
zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:"
+ zookeeperServerPort1 + ",127.0.0.1:" + zookeeperServerPort2
+ "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
ZookeeperClient newZookeeperClient = zookeeperClientManager.connect(url);
// just for connected
newZookeeperClient.getContent("/dubbo/test");
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 2);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1),
newZookeeperClient);
URL url2 = URL.valueOf(
"zookeeper://127.0.0.1:" + zookeeperServerPort1
+ "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true");
checkFetchAndUpdateCacheNotNull(url2);
URL url3 = URL.valueOf(
"zookeeper://127.0.0.1:8778/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:"
+ zookeeperServerPort2
+ "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true");
checkFetchAndUpdateCacheNotNull(url3);
}
private void checkFetchAndUpdateCacheNotNull(URL url) {
List<String> addressList = zookeeperClientManager.getURLBackupAddress(url);
ZookeeperClient zookeeperClient = zookeeperClientManager.fetchAndUpdateZookeeperClientCache(addressList);
Assertions.assertNotNull(zookeeperClient);
}
@Test
void testRepeatConnect() {
URL url = URL.valueOf(
zookeeperConnectionAddress1
+ "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
URL url2 = URL.valueOf(
zookeeperConnectionAddress1
+ "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true");
ZookeeperClient newZookeeperClient = zookeeperClientManager.connect(url);
// just for connected
newZookeeperClient.getContent("/dubbo/test");
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 1);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1),
newZookeeperClient);
when(mockedCurator5ZookeeperClient.isConnected()).thenReturn(true);
Assertions.assertTrue(newZookeeperClient.isConnected());
ZookeeperClient newZookeeperClient2 = zookeeperClientManager.connect(url2);
// just for connected
newZookeeperClient2.getContent("/dubbo/test");
Assertions.assertEquals(newZookeeperClient, newZookeeperClient2);
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 1);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1),
newZookeeperClient);
}
@Test
void testNotRepeatConnect() {
URL url = URL.valueOf(
zookeeperConnectionAddress1
+ "/org.apache.dubbo.registry.RegistryService?application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
URL url2 = URL.valueOf(
zookeeperConnectionAddress2
+ "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true");
ZookeeperClient newZookeeperClient = zookeeperClientManager.connect(url);
// just for connected
newZookeeperClient.getContent("/dubbo/test");
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 1);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1),
newZookeeperClient);
ZookeeperClient newZookeeperClient2 = zookeeperClientManager.connect(url2);
// just for connected
newZookeeperClient2.getContent("/dubbo/test");
Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2);
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 2);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2),
newZookeeperClient2);
}
@Test
void testRepeatConnectForBackUpAdd() {
URL url = URL.valueOf(
zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:"
+ zookeeperServerPort1
+ "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
URL url2 = URL.valueOf(
zookeeperConnectionAddress1 + "/org.apache.dubbo.metadata.store.MetadataReport?backup=127.0.0.1:"
+ zookeeperServerPort2
+ "&address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true");
when(mockedCurator5ZookeeperClient.isConnected()).thenReturn(true);
ZookeeperClient newZookeeperClient = zookeeperClientManager.connect(url);
// just for connected
newZookeeperClient.getContent("/dubbo/test");
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 1);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1),
newZookeeperClient);
ZookeeperClient newZookeeperClient2 = zookeeperClientManager.connect(url2);
// just for connected
newZookeeperClient2.getContent("/dubbo/test");
Assertions.assertEquals(newZookeeperClient, newZookeeperClient2);
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 2);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2),
newZookeeperClient2);
}
@Test
void testRepeatConnectForNoMatchBackUpAdd() {
URL url = URL.valueOf(
zookeeperConnectionAddress1 + "/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:"
+ zookeeperServerPort1
+ "&application=metadatareport-local-xml-provider2&dubbo=2.0.2&interface=org.apache.dubbo.registry.RegistryService&pid=47418&specVersion=2.7.0-SNAPSHOT×tamp=1547102428828");
URL url2 = URL.valueOf(
zookeeperConnectionAddress2
+ "/org.apache.dubbo.metadata.store.MetadataReport?address=zookeeper://127.0.0.1:2181&application=metadatareport-local-xml-provider2&cycle-report=false&interface=org.apache.dubbo.metadata.store.MetadataReport&retry-period=4590&retry-times=23&sync-report=true");
ZookeeperClient newZookeeperClient = zookeeperClientManager.connect(url);
// just for connected
newZookeeperClient.getContent("/dubbo/test");
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 1);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort1),
newZookeeperClient);
ZookeeperClient newZookeeperClient2 = zookeeperClientManager.connect(url2);
// just for connected
newZookeeperClient2.getContent("/dubbo/test");
Assertions.assertNotEquals(newZookeeperClient, newZookeeperClient2);
Assertions.assertEquals(zookeeperClientManager.getZookeeperClientMap().size(), 2);
Assertions.assertEquals(
zookeeperClientManager.getZookeeperClientMap().get("127.0.0.1:" + zookeeperServerPort2),
newZookeeperClient2);
}
@Test
void testSameHostWithDifferentUser() {
URL url1 = URL.valueOf("zookeeper://us1:pw1@127.0.0.1:" + zookeeperServerPort1 + "/path1");
URL url2 = URL.valueOf("zookeeper://us2:pw2@127.0.0.1:" + zookeeperServerPort1 + "/path2");
ZookeeperClient client1 = zookeeperClientManager.connect(url1);
ZookeeperClient client2 = zookeeperClientManager.connect(url2);
assertThat(client1, not(client2));
}
@AfterAll
public static void afterAll() {
mockedCurator5ZookeeperClientConstruction.close();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ZookeeperClientManager.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ZookeeperClientManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RemotingConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_DESTROY_ZOOKEEPER;
public class ZookeeperClientManager {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ZookeeperClientManager.class);
private final Map<String, ZookeeperClient> zookeeperClientMap = new ConcurrentHashMap<>();
private static final Map<ApplicationModel, ZookeeperClientManager> managerMap = new ConcurrentHashMap<>();
/**
* Use getInstance instead of get Instance
* This method is made public solely for unit test purposes.
*/
public ZookeeperClientManager() {}
public static ZookeeperClientManager getInstance(ApplicationModel applicationModel) {
if (!managerMap.containsKey(applicationModel) || managerMap.get(applicationModel) == null) {
ZookeeperClientManager clientManager = new ZookeeperClientManager();
applicationModel.addDestroyListener(m -> {
// destroy zookeeper clients if any
try {
clientManager.destroy();
} catch (Exception e) {
logger.error(
TRANSPORT_FAILED_DESTROY_ZOOKEEPER,
"",
"",
"Error encountered while destroying ZookeeperTransporter: " + e.getMessage(),
e);
}
});
managerMap.put(applicationModel, clientManager);
}
return managerMap.get(applicationModel);
}
public ZookeeperClient connect(URL url) {
ZookeeperClient zookeeperClient;
// address format: {[username:password@]address}
List<String> addressList = getURLBackupAddress(url);
// The field define the zookeeper server , including protocol, host, port, username, password
if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null
&& zookeeperClient.isConnected()) {
logger.info("find valid zookeeper client from the cache for address: " + url);
return zookeeperClient;
}
// avoid creating too many connections, so add lock
synchronized (zookeeperClientMap) {
if ((zookeeperClient = fetchAndUpdateZookeeperClientCache(addressList)) != null
&& zookeeperClient.isConnected()) {
logger.info("find valid zookeeper client from the cache for address: " + url);
return zookeeperClient;
}
zookeeperClient = new Curator5ZookeeperClient(url);
logger.info("No valid zookeeper client found from cache, therefore create a new client for url. " + url);
writeToClientMap(addressList, zookeeperClient);
}
return zookeeperClient;
}
public ZookeeperClient fetchAndUpdateZookeeperClientCache(List<String> addressList) {
ZookeeperClient zookeeperClient = null;
for (String address : addressList) {
if ((zookeeperClient = zookeeperClientMap.get(address)) != null && zookeeperClient.isConnected()) {
break;
}
}
// mapping new backup address
if (zookeeperClient != null && zookeeperClient.isConnected()) {
writeToClientMap(addressList, zookeeperClient);
}
return zookeeperClient;
}
/**
* get all zookeeper urls (such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999)
*
* @param url such as zookeeper://127.0.0.1:2181?backup=127.0.0.1:8989,127.0.0.1:9999
* @return such as 127.0.0.1:2181,127.0.0.1:8989,127.0.0.1:9999
*/
public List<String> getURLBackupAddress(URL url) {
List<String> addressList = new ArrayList<>();
addressList.add(url.getAddress());
addressList.addAll(url.getParameter(RemotingConstants.BACKUP_KEY, Collections.emptyList()));
String authPrefix = null;
if (StringUtils.isNotEmpty(url.getUsername())) {
StringBuilder buf = new StringBuilder();
buf.append(url.getUsername());
if (StringUtils.isNotEmpty(url.getPassword())) {
buf.append(':');
buf.append(url.getPassword());
}
buf.append('@');
authPrefix = buf.toString();
}
if (StringUtils.isNotEmpty(authPrefix)) {
List<String> authedAddressList = new ArrayList<>(addressList.size());
for (String addr : addressList) {
authedAddressList.add(authPrefix + addr);
}
return authedAddressList;
}
return addressList;
}
/**
* write address-ZookeeperClient relationship to Map
*
* @param addressList
* @param zookeeperClient
*/
void writeToClientMap(List<String> addressList, ZookeeperClient zookeeperClient) {
for (String address : addressList) {
zookeeperClientMap.put(address, zookeeperClient);
}
}
/**
* redefine the url for zookeeper. just keep protocol, username, password, host, port, and individual parameter.
*
* @param url
* @return
*/
URL toClientURL(URL url) {
Map<String, String> parameterMap = new HashMap<>();
// for CuratorZookeeperClient
if (url.getParameter(TIMEOUT_KEY) != null) {
parameterMap.put(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY));
}
if (url.getParameter(RemotingConstants.BACKUP_KEY) != null) {
parameterMap.put(RemotingConstants.BACKUP_KEY, url.getParameter(RemotingConstants.BACKUP_KEY));
}
return new ServiceConfigURL(
url.getProtocol(),
url.getUsername(),
url.getPassword(),
url.getHost(),
url.getPort(),
ZookeeperClientManager.class.getName(),
parameterMap);
}
/**
* for unit test
*
* @return
*/
public Map<String, ZookeeperClient> getZookeeperClientMap() {
return zookeeperClientMap;
}
public void destroy() {
// only destroy zk clients here
for (ZookeeperClient client : zookeeperClientMap.values()) {
client.close();
}
zookeeperClientMap.clear();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/DataListener.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/DataListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
/**
* 2019-02-26
*/
public interface DataListener {
void dataChanged(String path, Object value, EventType eventType);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/EventType.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/EventType.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
/**
* 2019-02-26
*/
public enum EventType {
None(-1),
NodeCreated(1),
NodeDeleted(2),
NodeDataChanged(3),
NodeChildrenChanged(4),
CONNECTION_SUSPENDED(11),
CONNECTION_RECONNECTED(12),
CONNECTION_LOST(12),
INITIALIZED(10);
private final int intValue; // Integer representation of value
// for sending over wire
EventType(int intValue) {
this.intValue = intValue;
}
public int getIntValue() {
return intValue;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ChildListener.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ChildListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import java.util.List;
public interface ChildListener {
void childChanged(String path, List<String> children);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/StateListener.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/StateListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
public interface StateListener {
int SESSION_LOST = 0;
int CONNECTED = 1;
int RECONNECTED = 2;
int SUSPENDED = 3;
int NEW_SESSION_CREATED = 4;
void stateChanged(int connected);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/AbstractZookeeperClient.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/AbstractZookeeperClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
public abstract class AbstractZookeeperClient<TargetDataListener, TargetChildListener> implements ZookeeperClient {
protected static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractZookeeperClient.class);
// may hang up to wait name resolution up to 10s
protected int DEFAULT_CONNECTION_TIMEOUT_MS = 30 * 1000;
protected int DEFAULT_SESSION_TIMEOUT_MS = 60 * 1000;
protected boolean DEFAULT_ENSEMBLE_TRACKER = true;
private final URL url;
private final Set<StateListener> stateListeners = new CopyOnWriteArraySet<>();
private final ConcurrentMap<String, ConcurrentMap<ChildListener, TargetChildListener>> childListeners =
new ConcurrentHashMap<>();
private final ConcurrentMap<String, ConcurrentMap<DataListener, TargetDataListener>> listeners =
new ConcurrentHashMap<>();
private volatile boolean closed = false;
private final Set<String> persistentExistNodePath = new ConcurrentHashSet<>();
public AbstractZookeeperClient(URL url) {
this.url = url;
}
@Override
public URL getUrl() {
return url;
}
@Override
public void delete(String path) {
// never mind if ephemeral
persistentExistNodePath.remove(path);
deletePath(path);
}
@Override
public void create(String path, boolean ephemeral, boolean faultTolerant) {
if (!ephemeral) {
if (persistentExistNodePath.contains(path)) {
return;
}
if (checkExists(path)) {
persistentExistNodePath.add(path);
return;
}
}
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false, true);
}
if (ephemeral) {
createEphemeral(path, faultTolerant);
} else {
createPersistent(path, faultTolerant);
persistentExistNodePath.add(path);
}
}
@Override
public void addStateListener(StateListener listener) {
stateListeners.add(listener);
}
@Override
public void removeStateListener(StateListener listener) {
stateListeners.remove(listener);
}
public Set<StateListener> getSessionListeners() {
return stateListeners;
}
@Override
public List<String> addChildListener(String path, final ChildListener listener) {
ConcurrentMap<ChildListener, TargetChildListener> listeners =
ConcurrentHashMapUtils.computeIfAbsent(childListeners, path, k -> new ConcurrentHashMap<>());
TargetChildListener targetListener =
ConcurrentHashMapUtils.computeIfAbsent(listeners, listener, k -> createTargetChildListener(path, k));
return addTargetChildListener(path, targetListener);
}
@Override
public void addDataListener(String path, DataListener listener) {
this.addDataListener(path, listener, null);
}
@Override
public void addDataListener(String path, DataListener listener, Executor executor) {
ConcurrentMap<DataListener, TargetDataListener> dataListenerMap =
ConcurrentHashMapUtils.computeIfAbsent(listeners, path, k -> new ConcurrentHashMap<>());
TargetDataListener targetListener = ConcurrentHashMapUtils.computeIfAbsent(
dataListenerMap, listener, k -> createTargetDataListener(path, k));
addTargetDataListener(path, targetListener, executor);
}
@Override
public void removeDataListener(String path, DataListener listener) {
ConcurrentMap<DataListener, TargetDataListener> dataListenerMap = listeners.get(path);
if (dataListenerMap != null) {
TargetDataListener targetListener = dataListenerMap.remove(listener);
if (targetListener != null) {
removeTargetDataListener(path, targetListener);
}
}
}
@Override
public void removeChildListener(String path, ChildListener listener) {
ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
if (listeners != null) {
TargetChildListener targetListener = listeners.remove(listener);
if (targetListener != null) {
removeTargetChildListener(path, targetListener);
}
}
}
protected void stateChanged(int state) {
for (StateListener sessionListener : getSessionListeners()) {
sessionListener.stateChanged(state);
}
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
try {
doClose();
} catch (Exception e) {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", e.getMessage(), e);
}
}
@Override
public void createOrUpdate(String path, String content, boolean ephemeral) {
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false, true);
}
if (ephemeral) {
createOrUpdateEphemeral(path, content);
} else {
createOrUpdatePersistent(path, content);
}
}
@Override
public void createOrUpdate(String path, String content, boolean ephemeral, Integer version) {
int i = path.lastIndexOf('/');
if (i > 0) {
create(path.substring(0, i), false, true);
}
if (ephemeral) {
createOrUpdateEphemeral(path, content, version);
} else {
createOrUpdatePersistent(path, content, version);
}
}
@Override
public String getContent(String path) {
if (!checkExists(path)) {
return null;
}
return doGetContent(path);
}
@Override
public ConfigItem getConfigItem(String path) {
return doGetConfigItem(path);
}
protected void doClose() {
// Break circular reference of zk client
stateListeners.clear();
}
protected abstract void createPersistent(String path, boolean faultTolerant);
protected abstract void createEphemeral(String path, boolean faultTolerant);
protected abstract void createPersistent(String path, String data, boolean faultTolerant);
protected abstract void createEphemeral(String path, String data, boolean faultTolerant);
protected abstract void update(String path, String data, int version);
protected abstract void update(String path, String data);
protected abstract void createOrUpdatePersistent(String path, String data);
protected abstract void createOrUpdateEphemeral(String path, String data);
protected abstract void createOrUpdatePersistent(String path, String data, Integer version);
protected abstract void createOrUpdateEphemeral(String path, String data, Integer version);
@Override
public abstract boolean checkExists(String path);
protected abstract TargetChildListener createTargetChildListener(String path, ChildListener listener);
protected abstract List<String> addTargetChildListener(String path, TargetChildListener listener);
protected abstract TargetDataListener createTargetDataListener(String path, DataListener listener);
protected abstract void addTargetDataListener(String path, TargetDataListener listener);
protected abstract void addTargetDataListener(String path, TargetDataListener listener, Executor executor);
protected abstract void removeTargetDataListener(String path, TargetDataListener listener);
protected abstract void removeTargetChildListener(String path, TargetChildListener listener);
protected abstract String doGetContent(String path);
protected abstract ConfigItem doGetConfigItem(String path);
/**
* we invoke the zookeeper client to delete the node
*
* @param path the node path
*/
protected abstract void deletePath(String path);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.UrlUtils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ACLProvider;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import static org.apache.dubbo.common.constants.CommonConstants.SESSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ZOOKEEPER_ENSEMBLE_TRACKER_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
public class Curator5ZookeeperClient
extends AbstractZookeeperClient<
Curator5ZookeeperClient.NodeCacheListenerImpl, Curator5ZookeeperClient.CuratorWatcherImpl> {
protected static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(Curator5ZookeeperClient.class);
private static final Charset CHARSET = StandardCharsets.UTF_8;
private final CuratorFramework client;
private static Map<String, NodeCache> nodeCacheMap = new ConcurrentHashMap<>();
public Curator5ZookeeperClient(URL url) {
super(url);
try {
int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS);
int sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS);
boolean ensembleTracker = url.getParameter(ZOOKEEPER_ENSEMBLE_TRACKER_KEY, DEFAULT_ENSEMBLE_TRACKER);
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString(url.getBackupAddress())
.retryPolicy(new RetryNTimes(1, 1000))
.connectionTimeoutMs(timeout)
.ensembleTracker(ensembleTracker)
.sessionTimeoutMs(sessionExpireMs);
String userInformation = url.getUserInformation();
if (userInformation != null && userInformation.length() > 0) {
builder = builder.authorization("digest", userInformation.getBytes(StandardCharsets.UTF_8));
builder.aclProvider(new ACLProvider() {
@Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
@Override
public List<ACL> getAclForPath(String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
client = builder.build();
client.getConnectionStateListenable().addListener(new CuratorConnectionStateListener(url));
client.start();
boolean connected = client.blockUntilConnected(timeout, TimeUnit.MILLISECONDS);
boolean check = UrlUtils.isCheck(url);
if (check && !connected) {
// close CuratorFramework to stop re-connection.
client.close();
IllegalStateException illegalStateException =
new IllegalStateException("zookeeper not connected, the address is: " + url);
// 5-1 Failed to connect to configuration center.
logger.error(
CONFIG_FAILED_CONNECT_REGISTRY,
"Zookeeper server offline",
"",
"Failed to connect with zookeeper",
illegalStateException);
throw illegalStateException;
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void createPersistent(String path, boolean faultTolerant) {
try {
client.create().forPath(path);
} catch (NodeExistsException e) {
if (!faultTolerant) {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e);
throw new IllegalStateException(e.getMessage(), e);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public void createEphemeral(String path, boolean faultTolerant) {
try {
client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
} catch (NodeExistsException e) {
if (faultTolerant) {
logger.info("ZNode " + path
+ " already exists, since we will only try to recreate a node on a session expiration"
+ ", this duplication might be caused by a delete delay from the zk server, which means the old expired session"
+ " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, "
+ "we can just try to delete and create again.");
deletePath(path);
createEphemeral(path, true);
} else {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e);
throw new IllegalStateException(e.getMessage(), e);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createPersistent(String path, String data, boolean faultTolerant) {
byte[] dataBytes = data.getBytes(CHARSET);
try {
client.create().forPath(path, dataBytes);
} catch (NodeExistsException e) {
if (faultTolerant) {
logger.info("ZNode " + path + " already exists. Will be override with new data.");
try {
client.setData().forPath(path, dataBytes);
} catch (Exception e1) {
throw new IllegalStateException(e.getMessage(), e1);
}
} else {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e);
throw new IllegalStateException(e.getMessage(), e);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createEphemeral(String path, String data, boolean faultTolerant) {
byte[] dataBytes = data.getBytes(CHARSET);
try {
client.create().withMode(CreateMode.EPHEMERAL).forPath(path, dataBytes);
} catch (NodeExistsException e) {
if (faultTolerant) {
logger.info("ZNode " + path
+ " already exists, since we will only try to recreate a node on a session expiration"
+ ", this duplication might be caused by a delete delay from the zk server, which means the old expired session"
+ " may still holds this ZNode and the server just hasn't got time to do the deletion. In this case, "
+ "we can just try to delete and create again.");
deletePath(path);
createEphemeral(path, data, true);
} else {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "ZNode " + path + " already exists.", e);
throw new IllegalStateException(e.getMessage(), e);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void update(String path, String data, int version) {
byte[] dataBytes = data.getBytes(CHARSET);
try {
client.setData().withVersion(version).forPath(path, dataBytes);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void update(String path, String data) {
byte[] dataBytes = data.getBytes(CHARSET);
try {
client.setData().forPath(path, dataBytes);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createOrUpdatePersistent(String path, String data) {
try {
if (checkExists(path)) {
update(path, data);
} else {
createPersistent(path, data, true);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createOrUpdateEphemeral(String path, String data) {
try {
if (checkExists(path)) {
update(path, data);
} else {
createEphemeral(path, data, true);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createOrUpdatePersistent(String path, String data, Integer version) {
try {
if (checkExists(path) && version != null) {
update(path, data, version);
} else {
createPersistent(path, data, false);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void createOrUpdateEphemeral(String path, String data, Integer version) {
try {
if (checkExists(path) && version != null) {
update(path, data, version);
} else {
createEphemeral(path, data, false);
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected void deletePath(String path) {
try {
client.delete().deletingChildrenIfNeeded().forPath(path);
} catch (NoNodeException ignored) {
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public List<String> getChildren(String path) {
try {
return client.getChildren().forPath(path);
} catch (NoNodeException e) {
return null;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
public boolean checkExists(String path) {
try {
if (client.checkExists().forPath(path) != null) {
return true;
}
} catch (Exception ignored) {
}
return false;
}
@Override
public boolean isConnected() {
return client.getZookeeperClient().isConnected();
}
@Override
public String doGetContent(String path) {
try {
byte[] dataBytes = client.getData().forPath(path);
return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET);
} catch (NoNodeException e) {
// ignore NoNode Exception.
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
return null;
}
@Override
public ConfigItem doGetConfigItem(String path) {
String content;
Stat stat;
try {
stat = new Stat();
byte[] dataBytes = client.getData().storingStatIn(stat).forPath(path);
content = (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, CHARSET);
} catch (NoNodeException e) {
return new ConfigItem();
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
return new ConfigItem(content, stat);
}
@Override
public void doClose() {
super.doClose();
client.close();
}
@Override
public Curator5ZookeeperClient.CuratorWatcherImpl createTargetChildListener(String path, ChildListener listener) {
return new Curator5ZookeeperClient.CuratorWatcherImpl(client, listener, path);
}
@Override
public List<String> addTargetChildListener(String path, CuratorWatcherImpl listener) {
try {
return client.getChildren().usingWatcher(listener).forPath(path);
} catch (NoNodeException e) {
return null;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
@Override
protected Curator5ZookeeperClient.NodeCacheListenerImpl createTargetDataListener(
String path, DataListener listener) {
return new NodeCacheListenerImpl(client, listener, path);
}
@Override
protected void addTargetDataListener(String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) {
this.addTargetDataListener(path, nodeCacheListener, null);
}
@Override
protected void addTargetDataListener(
String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener, Executor executor) {
try {
NodeCache nodeCache = new NodeCache(client, path);
if (nodeCacheMap.putIfAbsent(path, nodeCache) != null) {
return;
}
if (executor == null) {
nodeCache.getListenable().addListener(nodeCacheListener);
} else {
nodeCache.getListenable().addListener(nodeCacheListener, executor);
}
nodeCache.start();
} catch (Exception e) {
throw new IllegalStateException("Add nodeCache listener for path:" + path, e);
}
}
@Override
protected void removeTargetDataListener(
String path, Curator5ZookeeperClient.NodeCacheListenerImpl nodeCacheListener) {
NodeCache nodeCache = nodeCacheMap.get(path);
if (nodeCache != null) {
nodeCache.getListenable().removeListener(nodeCacheListener);
}
nodeCacheListener.dataListener = null;
}
@Override
public void removeTargetChildListener(String path, CuratorWatcherImpl listener) {
listener.unwatch();
}
static class NodeCacheListenerImpl implements NodeCacheListener {
private CuratorFramework client;
private volatile DataListener dataListener;
private String path;
protected NodeCacheListenerImpl() {}
public NodeCacheListenerImpl(CuratorFramework client, DataListener dataListener, String path) {
this.client = client;
this.dataListener = dataListener;
this.path = path;
}
@Override
public void nodeChanged() throws Exception {
ChildData childData = nodeCacheMap.get(path).getCurrentData();
String content = null;
EventType eventType;
if (childData == null) {
eventType = EventType.NodeDeleted;
} else if (childData.getStat().getVersion() == 0) {
content = new String(childData.getData(), CHARSET);
eventType = EventType.NodeCreated;
} else {
content = new String(childData.getData(), CHARSET);
eventType = EventType.NodeDataChanged;
}
dataListener.dataChanged(path, content, eventType);
}
}
static class CuratorWatcherImpl implements CuratorWatcher {
private CuratorFramework client;
private volatile ChildListener childListener;
private String path;
public CuratorWatcherImpl(CuratorFramework client, ChildListener listener, String path) {
this.client = client;
this.childListener = listener;
this.path = path;
}
protected CuratorWatcherImpl() {}
public void unwatch() {
this.childListener = null;
}
@Override
public void process(WatchedEvent event) throws Exception {
// if client connect or disconnect to server, zookeeper will queue
// watched event(Watcher.Event.EventType.None, .., path = null).
if (event.getType() == Watcher.Event.EventType.None) {
return;
}
if (childListener != null) {
childListener.childChanged(
path, client.getChildren().usingWatcher(this).forPath(path));
}
}
}
private class CuratorConnectionStateListener implements ConnectionStateListener {
private final long UNKNOWN_SESSION_ID = -1L;
private long lastSessionId;
private int timeout;
private int sessionExpireMs;
public CuratorConnectionStateListener(URL url) {
this.timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_CONNECTION_TIMEOUT_MS);
this.sessionExpireMs = url.getParameter(SESSION_KEY, DEFAULT_SESSION_TIMEOUT_MS);
}
@Override
public void stateChanged(CuratorFramework client, ConnectionState state) {
long sessionId = UNKNOWN_SESSION_ID;
try {
sessionId = client.getZookeeperClient().getZooKeeper().getSessionId();
} catch (Exception e) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Curator client state changed, but failed to get the related zk session instance.");
}
if (state == ConnectionState.LOST) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Curator zookeeper session " + Long.toHexString(lastSessionId) + " expired.");
Curator5ZookeeperClient.this.stateChanged(StateListener.SESSION_LOST);
} else if (state == ConnectionState.SUSPENDED) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Curator zookeeper connection of session " + Long.toHexString(sessionId) + " timed out. "
+ "connection timeout value is " + timeout + ", session expire timeout value is "
+ sessionExpireMs);
Curator5ZookeeperClient.this.stateChanged(StateListener.SUSPENDED);
} else if (state == ConnectionState.CONNECTED) {
lastSessionId = sessionId;
logger.info("Curator zookeeper client instance initiated successfully, session id is "
+ Long.toHexString(sessionId));
Curator5ZookeeperClient.this.stateChanged(StateListener.CONNECTED);
} else if (state == ConnectionState.RECONNECTED) {
if (lastSessionId == sessionId && sessionId != UNKNOWN_SESSION_ID) {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"Curator zookeeper connection recovered from connection lose, " + "reuse the old session "
+ Long.toHexString(sessionId));
Curator5ZookeeperClient.this.stateChanged(StateListener.RECONNECTED);
} else {
logger.warn(
REGISTRY_ZOOKEEPER_EXCEPTION,
"",
"",
"New session created after old session lost, " + "old session "
+ Long.toHexString(lastSessionId) + ", new session " + Long.toHexString(sessionId));
lastSessionId = sessionId;
Curator5ZookeeperClient.this.stateChanged(StateListener.NEW_SESSION_CREATED);
}
}
}
}
/**
* just for unit test
*
* @return
*/
CuratorFramework getClient() {
return client;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ZookeeperClient.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/ZookeeperClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import java.util.List;
import java.util.concurrent.Executor;
/**
* Common abstraction of Zookeeper client.
*/
public interface ZookeeperClient {
/**
* Create ZNode in Zookeeper.
*
* @param path path to ZNode
* @param ephemeral specify create mode of ZNode creation. true - EPHEMERAL, false - PERSISTENT.
* @param faultTolerant specify fault tolerance of ZNode creation.
* true - ignore exception and recreate if is ephemeral, false - throw exception.
*/
void create(String path, boolean ephemeral, boolean faultTolerant);
/**
* Delete ZNode.
*
* @param path path to ZNode
*/
void delete(String path);
List<String> getChildren(String path);
List<String> addChildListener(String path, ChildListener listener);
/**
* Attach data listener to current Zookeeper client.
*
* @param path directory. All children of path will be listened.
* @param listener The data listener object.
*/
void addDataListener(String path, DataListener listener);
/**
* Attach data listener to current Zookeeper client. The listener will be executed using the given executor.
*
* @param path directory. All children of path will be listened.
* @param listener The data listener object.
* @param executor the executor that will execute the listener.
*/
void addDataListener(String path, DataListener listener, Executor executor);
/**
* Detach data listener.
*
* @param path directory. All listener of children of the path will be detached.
* @param listener The data listener object.
*/
void removeDataListener(String path, DataListener listener);
void removeChildListener(String path, ChildListener listener);
void addStateListener(StateListener listener);
void removeStateListener(StateListener listener);
/**
* Check the Zookeeper client whether connected to server or not.
*
* @return true if connected
*/
boolean isConnected();
/**
* Close connection to Zookeeper server (cluster).
*/
void close();
URL getUrl();
/**
* Create or update ZNode in Zookeeper with content specified.
*
* @param path path to ZNode
* @param content the content of ZNode
* @param ephemeral specify create mode of ZNode creation. true - EPHEMERAL, false - PERSISTENT.
*/
void createOrUpdate(String path, String content, boolean ephemeral);
/**
* CAS version to Create or update ZNode in Zookeeper with content specified.
*
* @param path path to ZNode
* @param content the content of ZNode
* @param ephemeral specify create mode of ZNode creation. true - EPHEMERAL, false - PERSISTENT.
* @param ticket origin content version, if current version is not the specified version, throw exception
*/
void createOrUpdate(String path, String content, boolean ephemeral, Integer ticket);
/**
* Obtain the content of a ZNode.
*
* @param path path to ZNode
* @return content of ZNode
*/
String getContent(String path);
ConfigItem getConfigItem(String path);
boolean checkExists(String path);
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/aot/Curator5ZookeeperReflectionTypeDescriberRegistrar.java | dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/aot/Curator5ZookeeperReflectionTypeDescriberRegistrar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.zookeeper.curator5.aot;
import org.apache.dubbo.aot.api.MemberCategory;
import org.apache.dubbo.aot.api.ReflectionTypeDescriberRegistrar;
import org.apache.dubbo.aot.api.TypeDescriber;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.zookeeper.ClientCnxnSocketNIO;
public class Curator5ZookeeperReflectionTypeDescriberRegistrar implements ReflectionTypeDescriberRegistrar {
@Override
public List<TypeDescriber> getTypeDescribers() {
List<TypeDescriber> typeDescribers = new ArrayList<>();
typeDescribers.add(buildTypeDescriberWithDeclaredConstructors(ClientCnxnSocketNIO.class));
typeDescribers.add(buildTypeDescriberWithDeclared("org.apache.curator.x.discovery.ServiceInstance"));
typeDescribers.add(buildTypeDescriberWithDeclared("org.apache.curator.x.discovery.details.OldServiceInstance"));
return typeDescribers;
}
private TypeDescriber buildTypeDescriberWithDeclared(String className) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_METHODS);
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
memberCategories.add(MemberCategory.DECLARED_FIELDS);
return new TypeDescriber(className, null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
private TypeDescriber buildTypeDescriberWithDeclaredConstructors(Class<?> c) {
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
return new TypeDescriber(
c.getName(), null, new HashSet<>(), new HashSet<>(), new HashSet<>(), memberCategories);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.exchange.support.header;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.ExchangeHandler;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.transport.dispatcher.FakeChannelHandlers;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class HeartbeatHandlerTest {
private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandlerTest.class);
private ExchangeServer server;
private ExchangeClient client;
@AfterEach
public void after() throws Exception {
if (client != null) {
client.close();
client = null;
}
if (server != null) {
server.close();
server = null;
}
FakeChannelHandlers.resetChannelHandlers();
// wait for timer to finish
Thread.sleep(2000);
}
@Test
void testServerHeartbeat() throws Exception {
FakeChannelHandlers.resetChannelHandlers();
URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56780))
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.HEARTBEAT_KEY, 1000);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
FakeChannelHandlers.setTestingChannelHandlers();
serverURL = serverURL.removeParameter(Constants.HEARTBEAT_KEY);
// Let the client not reply to the heartbeat, and turn off automatic reconnect to simulate the client dropped.
serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
serverURL = serverURL.addParameter(Constants.RECONNECT_KEY, false);
serverURL = serverURL.addParameter(Constants.CODEC_KEY, "telnet");
client = Exchangers.connect(serverURL);
disconnect.await();
Assertions.assertTrue(handler.disconnectCount > 0);
}
@Test
void testHeartbeat() throws Exception {
URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56785))
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.HEARTBEAT_KEY, 1000)
.addParameter(Constants.CODEC_KEY, "telnet");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
client = Exchangers.connect(serverURL);
connect.await();
Assertions.assertEquals(0, handler.disconnectCount);
Assertions.assertEquals(1, handler.connectCount);
}
@Test
void testClientHeartbeat() throws Exception {
FakeChannelHandlers.setTestingChannelHandlers();
URL serverURL = URL.valueOf("telnet://localhost:" + NetUtils.getAvailablePort(56790))
.addParameter(Constants.EXCHANGER_KEY, HeaderExchanger.NAME)
.addParameter(Constants.TRANSPORTER_KEY, "netty3")
.addParameter(Constants.CODEC_KEY, "telnet");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
CountDownLatch connect = new CountDownLatch(1);
CountDownLatch disconnect = new CountDownLatch(1);
TestHeartbeatHandler handler = new TestHeartbeatHandler(connect, disconnect);
server = Exchangers.bind(serverURL, handler);
FakeChannelHandlers.resetChannelHandlers();
serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000);
client = Exchangers.connect(serverURL);
connect.await();
Assertions.assertTrue(handler.connectCount > 0);
}
class TestHeartbeatHandler implements ExchangeHandler {
public int disconnectCount = 0;
public int connectCount = 0;
private CountDownLatch connectCountDownLatch;
private CountDownLatch disconnectCountDownLatch;
public TestHeartbeatHandler(CountDownLatch connectCountDownLatch, CountDownLatch disconnectCountDownLatch) {
this.connectCountDownLatch = connectCountDownLatch;
this.disconnectCountDownLatch = disconnectCountDownLatch;
}
public CompletableFuture<Object> reply(ExchangeChannel channel, Object request) throws RemotingException {
return CompletableFuture.completedFuture(request);
}
@Override
public void connected(Channel channel) throws RemotingException {
++connectCount;
connectCountDownLatch.countDown();
}
@Override
public void disconnected(Channel channel) throws RemotingException {
++disconnectCount;
disconnectCountDownLatch.countDown();
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {}
@Override
public void received(Channel channel, Object message) throws RemotingException {
logger.error(this.getClass().getSimpleName() + message.toString());
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
exception.printStackTrace();
}
public String telnet(Channel channel, String message) throws RemotingException {
return message;
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.dispatcher;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
public class FakeChannelHandlers extends ChannelHandlers {
public FakeChannelHandlers() {
super();
}
public static void setTestingChannelHandlers() {
ChannelHandlers.setTestingChannelHandlers(new FakeChannelHandlers());
}
public static void resetChannelHandlers() {
ChannelHandlers.setTestingChannelHandlers(new ChannelHandlers());
}
@Override
protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) {
return ExtensionLoader.getExtensionLoader(Dispatcher.class)
.getAdaptiveExtension()
.dispatch(handler, url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientsTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.remoting.Transporter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
class ClientsTest {
@Test
void testGetTransportEmpty() {
try {
ExtensionLoader.getExtensionLoader(Transporter.class).getExtension("");
fail();
} catch (IllegalArgumentException expected) {
assertThat(expected.getMessage(), containsString("Extension name == null"));
}
}
@Test
void testGetTransportNull() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
String name = null;
ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name);
});
}
@Test
void testGetTransport3() {
String name = "netty3";
assertEquals(
NettyTransporter.class,
ExtensionLoader.getExtensionLoader(Transporter.class)
.getExtension(name)
.getClass());
}
@Test
void testGetTransportWrong() {
Assertions.assertThrows(IllegalStateException.class, () -> {
String name = "nety";
assertNull(ExtensionLoader.getExtensionLoader(Transporter.class)
.getExtension(name)
.getClass());
});
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetServerHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* Date: 4/26/11
* Time: 4:29 PM
*/
public class TelnetServerHandler implements Replier<String> {
public Class<String> interest() {
return String.class;
}
public Object reply(ExchangeChannel channel, String msg) throws RemotingException {
// Generate and write a response.
String response;
if (msg.length() == 0) {
response = "Please type something.\r\n";
} else {
response = "Did you say '" + msg + "'?\r\n";
}
return response;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/World.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import java.io.Serializable;
/**
* Data
*/
public class World implements Serializable {
private static final long serialVersionUID = 8563900571013747774L;
private String name;
public World() {}
public World(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ThreadNameTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class ThreadNameTest {
private static final Logger logger = LoggerFactory.getLogger(ThreadNameTest.class);
private NettyServer server;
private NettyClient client;
private URL serverURL;
private URL clientURL;
private ThreadNameVerifyHandler serverHandler;
private ThreadNameVerifyHandler clientHandler;
private static String serverRegex = "DubboServerHandler\\-localhost:(\\d+)\\-thread\\-(\\d+)";
private static String clientRegex = "DubboClientHandler\\-thread\\-(\\d+)";
private final CountDownLatch serverLatch = new CountDownLatch(1);
private final CountDownLatch clientLatch = new CountDownLatch(1);
@BeforeEach
public void before() throws Exception {
int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000));
serverURL = URL.valueOf("telnet://localhost?side=provider&codec=telnet").setPort(port);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
clientURL = URL.valueOf("telnet://localhost?side=consumer&codec=telnet").setPort(port);
clientURL = clientURL.setScopeModel(applicationModel);
serverHandler = new ThreadNameVerifyHandler(serverRegex, false, serverLatch);
clientHandler = new ThreadNameVerifyHandler(clientRegex, true, clientLatch);
server = new NettyServer(serverURL, serverHandler);
client = new NettyClient(clientURL, clientHandler);
}
@AfterEach
public void after() throws Exception {
if (client != null) {
client.close();
client = null;
}
if (server != null) {
server.close();
server = null;
}
}
@Test
void testThreadName() throws Exception {
client.send("hello");
serverLatch.await(30, TimeUnit.SECONDS);
clientLatch.await(30, TimeUnit.SECONDS);
if (!serverHandler.isSuccess() || !clientHandler.isSuccess()) {
Assertions.fail();
}
}
class ThreadNameVerifyHandler implements ChannelHandler {
private String message;
private boolean success;
private boolean client;
private CountDownLatch latch;
ThreadNameVerifyHandler(String msg, boolean client, CountDownLatch latch) {
message = msg;
this.client = client;
this.latch = latch;
}
public boolean isSuccess() {
return success;
}
private void checkThreadName() {
if (!success) {
success = Thread.currentThread().getName().matches(message);
}
if (success) {
latch.countDown();
}
}
private void output(String method) {
logger.info("{} {}", Thread.currentThread().getName(), client ? "client " + method : "server " + method);
}
@Override
public void connected(Channel channel) throws RemotingException {
output("connected");
checkThreadName();
}
@Override
public void disconnected(Channel channel) throws RemotingException {
// client: DubboClientHandler thread, server: DubboServerHandler or DubboSharedHandler thread.
output("disconnected");
}
@Override
public void sent(Channel channel, Object message) throws RemotingException {
// main thread.
output("sent");
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
// server: DubboServerHandler or DubboSharedHandler thread.
output("received");
}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
// client: DubboClientHandler thread, server: ?
output("caught");
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/WorldHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* DataHandler
*/
public class WorldHandler implements Replier<World> {
public Class<World> interest() {
return World.class;
}
public Object reply(ExchangeChannel channel, World msg) throws RemotingException {
return new Hello("hello," + msg.getName());
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientToServerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.Replier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
class NettyClientToServerTest extends ClientToServerTest {
protected ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
return Exchangers.bind(url, receiver);
}
protected ExchangeChannel newClient(int port) throws RemotingException {
// add heartbeat cycle to avoid unstable ut.
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&timeout=3000&codec=exchange");
url = url.addParameter(Constants.HEARTBEAT_KEY, 600 * 1000);
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
return Exchangers.connect(url);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetClientHandler.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/TelnetClientHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.support.Replier;
/**
* Date: 4/28/11
* Time: 11:15 AM
*/
public class TelnetClientHandler implements Replier<String> {
public Class<String> interest() {
return String.class;
}
public Object reply(ExchangeChannel channel, String msg) throws RemotingException {
return msg;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/Hello.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import java.io.Serializable;
/**
* Result
*/
public class Hello implements Serializable {
private static final long serialVersionUID = 8563900571013747774L;
private String name;
public Hello() {}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyClientTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* Date: 5/3/11
* Time: 5:47 PM
*/
class NettyClientTest {
static RemotingServer server;
static int port = NetUtils.getAvailablePort();
@BeforeAll
public static void setUp() throws Exception {
FrameworkModel.destroyAll();
URL url = URL.valueOf("exchange://localhost:" + port + "?server=netty3&codec=exchange");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
server = Exchangers.bind(url, new TelnetServerHandler());
}
@AfterAll
public static void tearDown() {
try {
if (server != null) server.close();
} finally {
}
}
// public static void main(String[] args) throws RemotingException, InterruptedException {
// ExchangeChannel client =
// Exchangers.connect(URL.valueOf("exchange://10.20.153.10:20880?client=netty3&heartbeat=1000&codec=exchange"));
// Thread.sleep(60 * 1000 * 50);
// }
@Test
void testClientClose() throws Exception {
List<ExchangeChannel> clients = new ArrayList<ExchangeChannel>(100);
for (int i = 0; i < 100; i++) {
URL url = URL.valueOf("exchange://localhost:" + port + "?client=netty3&codec=exchange");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
ExchangeChannel client = Exchangers.connect(url);
Thread.sleep(5);
clients.add(client);
}
for (ExchangeChannel client : clients) {
client.close();
}
Thread.sleep(1000);
}
@Test
void testServerClose() throws Exception {
for (int i = 0; i < 100; i++) {
URL url = URL.valueOf(
"exchange://localhost:" + NetUtils.getAvailablePort(6000) + "?server=netty3&codec=exchange");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
RemotingServer aServer = Exchangers.bind(url, new TelnetServerHandler());
aServer.close();
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBufferTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class NettyBackedChannelBufferTest {
private static final int CAPACITY = 4096;
private ChannelBuffer buffer;
@BeforeEach
public void init() {
buffer = new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(CAPACITY));
}
@AfterEach
public void dispose() {
buffer = null;
}
@Test
void testBufferTransfer() {
byte[] tmp1 = {1, 2};
byte[] tmp2 = {3, 4};
ChannelBuffer source = new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(2));
source.writeBytes(tmp1);
buffer.writeBytes(tmp2);
assertEquals(2, buffer.readableBytes());
source.setBytes(0, tmp1, 0, 2);
buffer.setBytes(0, source, 0, 2);
assertEquals(2, buffer.readableBytes());
byte[] actual = new byte[2];
buffer.getBytes(0, actual);
assertEquals(1, actual[0]);
assertEquals(2, actual[1]);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientReconnectTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.DubboAppender;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.Client;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.RemotingServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
import static org.apache.dubbo.remoting.Constants.LEAST_RECONNECT_DURATION_KEY;
/**
* Client reconnect test
*/
class ClientReconnectTest {
@BeforeEach
public void clear() {
DubboAppender.clear();
}
@Test
void testReconnect() throws RemotingException, InterruptedException {
{
int port = NetUtils.getAvailablePort();
Client client = startClient(port, 200);
Assertions.assertFalse(client.isConnected());
RemotingServer server = startServer(port);
for (int i = 0; i < 1000 && !client.isConnected(); i++) {
Thread.sleep(10);
}
Assertions.assertTrue(client.isConnected());
client.close(2000);
server.close(2000);
}
{
int port = NetUtils.getAvailablePort();
Client client = startClient(port, 20000);
Assertions.assertFalse(client.isConnected());
RemotingServer server = startServer(port);
for (int i = 0; i < 5; i++) {
Thread.sleep(200);
}
Assertions.assertFalse(client.isConnected());
client.close(2000);
server.close(2000);
}
}
public Client startClient(int port, int heartbeat) throws RemotingException {
URL url = URL.valueOf(
"exchange://127.0.0.1:" + port + "/client.reconnect.test?check=false&codec=exchange&client=netty3&"
+ Constants.HEARTBEAT_KEY + "=" + heartbeat + "&" + LEAST_RECONNECT_DURATION_KEY + "=0");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
url = url.setScopeModel(applicationModel);
return Exchangers.connect(url);
}
public RemotingServer startServer(int port) throws RemotingException {
final String url = "exchange://127.0.0.1:" + port + "/client.reconnect.test?server=netty3";
return Exchangers.bind(url, new HandlerAdapter());
}
static class HandlerAdapter extends ExchangeHandlerAdapter {
public HandlerAdapter() {
super(FrameworkModel.defaultModel());
}
@Override
public void connected(Channel channel) throws RemotingException {}
@Override
public void disconnected(Channel channel) throws RemotingException {}
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/NettyStringTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.Exchangers;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_DEFAULT;
/**
* Date: 4/26/11
* Time: 4:13 PM
*/
class NettyStringTest {
static ExchangeServer server;
static ExchangeChannel client;
@BeforeAll
public static void setUp() throws Exception {
// int port = (int) (1000 * Math.random() + 10000);
// int port = 10001;
int port = NetUtils.getAvailablePort();
URL serverURL = URL.valueOf("telnet://0.0.0.0:" + port + "?server=netty3&codec=telnet");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
ApplicationConfig applicationConfig = new ApplicationConfig("provider-app");
applicationConfig.setExecutorManagementMode(EXECUTOR_MANAGEMENT_MODE_DEFAULT);
applicationModel.getApplicationConfigManager().setApplication(applicationConfig);
serverURL = serverURL.setScopeModel(applicationModel);
URL clientURL = URL.valueOf("telnet://127.0.0.1:" + port + "?client=netty3&codec=telnet");
clientURL = clientURL.setScopeModel(applicationModel);
server = Exchangers.bind(serverURL, new TelnetServerHandler());
client = Exchangers.connect(clientURL, new TelnetClientHandler());
}
@AfterAll
public static void tearDown() {
try {
if (server != null) server.close();
} finally {
if (client != null) client.close();
}
}
@Test
void testHandler() {
// Thread.sleep(20000);
/*client.request("world\r\n");
Future future = client.request("world", 10000);
String result = (String)future.get();
Assertions.assertEquals("Did you say 'world'?\r\n",result);*/
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java | dubbo-remoting/dubbo-remoting-netty/src/test/java/org/apache/dubbo/remoting/transport/netty/ClientToServerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.remoting.exchange.support.Replier;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* ClientToServer
*/
public abstract class ClientToServerTest {
protected static final String LOCALHOST = "127.0.0.1";
protected ExchangeServer server;
protected ExchangeChannel client;
protected WorldHandler handler = new WorldHandler();
protected abstract ExchangeServer newServer(int port, Replier<?> receiver) throws RemotingException;
protected abstract ExchangeChannel newClient(int port) throws RemotingException;
@BeforeEach
protected void setUp() throws Exception {
int port = NetUtils.getAvailablePort();
server = newServer(port, handler);
client = newClient(port);
}
@BeforeEach
protected void tearDown() {
try {
if (server != null) server.close();
} finally {
if (client != null) client.close();
}
}
@Test
void testFuture() throws Exception {
CompletableFuture<Object> future = client.request(new World("world"));
Hello result = (Hello) future.get();
Assertions.assertEquals("hello,world", result.getName());
}
// @Test
// public void testCallback() throws Exception {
// final Object waitter = new Object();
// client.invoke(new World("world"), new InvokeCallback<Hello>() {
// public void callback(Hello result) {
// Assertions.assertEquals("hello,world", result.getName());
// synchronized (waitter) {
// waitter.notifyAll();
// }
// }
// public void onException(Throwable exception) {
// }
// });
// synchronized (waitter) {
// waitter.wait();
// }
// }
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java | dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.remoting.buffer.ChannelBuffer;
import org.apache.dubbo.remoting.buffer.ChannelBufferFactory;
import org.apache.dubbo.remoting.buffer.ChannelBuffers;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public class NettyBackedChannelBuffer implements ChannelBuffer {
private final org.jboss.netty.buffer.ChannelBuffer buffer;
public NettyBackedChannelBuffer(org.jboss.netty.buffer.ChannelBuffer buffer) {
Assert.notNull(buffer, "buffer == null");
this.buffer = buffer;
}
public org.jboss.netty.buffer.ChannelBuffer nettyChannelBuffer() {
return buffer;
}
@Override
public int capacity() {
return buffer.capacity();
}
@Override
public ChannelBuffer copy(int index, int length) {
return new NettyBackedChannelBuffer(buffer.copy(index, length));
}
@Override
public ChannelBufferFactory factory() {
return NettyBackedChannelBufferFactory.getInstance();
}
@Override
public byte getByte(int index) {
return buffer.getByte(index);
}
@Override
public void getBytes(int index, byte[] dst, int dstIndex, int length) {
buffer.getBytes(index, dst, dstIndex, length);
}
@Override
public void getBytes(int index, ByteBuffer dst) {
buffer.getBytes(index, dst);
}
@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
// careful
byte[] data = new byte[length];
buffer.getBytes(index, data, 0, length);
dst.setBytes(dstIndex, data, 0, length);
}
@Override
public void getBytes(int index, OutputStream dst, int length) throws IOException {
buffer.getBytes(index, dst, length);
}
@Override
public boolean isDirect() {
return buffer.isDirect();
}
@Override
public void setByte(int index, int value) {
buffer.setByte(index, value);
}
@Override
public void setBytes(int index, byte[] src, int srcIndex, int length) {
buffer.setBytes(index, src, srcIndex, length);
}
@Override
public void setBytes(int index, ByteBuffer src) {
buffer.setBytes(index, src);
}
@Override
public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) {
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
// careful
byte[] data = new byte[length];
src.getBytes(srcIndex, data, 0, length);
setBytes(index, data, 0, length);
}
@Override
public int setBytes(int index, InputStream src, int length) throws IOException {
return buffer.setBytes(index, src, length);
}
@Override
public ByteBuffer toByteBuffer(int index, int length) {
return buffer.toByteBuffer(index, length);
}
@Override
public byte[] array() {
return buffer.array();
}
@Override
public boolean hasArray() {
return buffer.hasArray();
}
@Override
public int arrayOffset() {
return buffer.arrayOffset();
}
// AbstractChannelBuffer
@Override
public void clear() {
buffer.clear();
}
@Override
public ChannelBuffer copy() {
return new NettyBackedChannelBuffer(buffer.copy());
}
@Override
public void discardReadBytes() {
buffer.discardReadBytes();
}
@Override
public void ensureWritableBytes(int writableBytes) {
buffer.ensureWritableBytes(writableBytes);
}
@Override
public void getBytes(int index, byte[] dst) {
buffer.getBytes(index, dst);
}
@Override
public void getBytes(int index, ChannelBuffer dst) {
// careful
getBytes(index, dst, dst.writableBytes());
}
@Override
public void getBytes(int index, ChannelBuffer dst, int length) {
// careful
if (length > dst.writableBytes()) {
throw new IndexOutOfBoundsException();
}
getBytes(index, dst, dst.writerIndex(), length);
dst.writerIndex(dst.writerIndex() + length);
}
@Override
public void markReaderIndex() {
buffer.markReaderIndex();
}
@Override
public void markWriterIndex() {
buffer.markWriterIndex();
}
@Override
public boolean readable() {
return buffer.readable();
}
@Override
public int readableBytes() {
return buffer.readableBytes();
}
@Override
public byte readByte() {
return buffer.readByte();
}
@Override
public void readBytes(byte[] dst) {
buffer.readBytes(dst);
}
@Override
public void readBytes(byte[] dst, int dstIndex, int length) {
buffer.readBytes(dst, dstIndex, length);
}
@Override
public void readBytes(ByteBuffer dst) {
buffer.readBytes(dst);
}
@Override
public void readBytes(ChannelBuffer dst) {
// careful
readBytes(dst, dst.writableBytes());
}
@Override
public void readBytes(ChannelBuffer dst, int length) {
// careful
if (length > dst.writableBytes()) {
throw new IndexOutOfBoundsException();
}
readBytes(dst, dst.writerIndex(), length);
dst.writerIndex(dst.writerIndex() + length);
}
@Override
public void readBytes(ChannelBuffer dst, int dstIndex, int length) {
// careful
if (readableBytes() < length) {
throw new IndexOutOfBoundsException();
}
byte[] data = new byte[length];
buffer.readBytes(data, 0, length);
dst.setBytes(dstIndex, data, 0, length);
}
@Override
public ChannelBuffer readBytes(int length) {
return new NettyBackedChannelBuffer(buffer.readBytes(length));
}
@Override
public void resetReaderIndex() {
buffer.resetReaderIndex();
}
@Override
public void resetWriterIndex() {
buffer.resetWriterIndex();
}
@Override
public int readerIndex() {
return buffer.readerIndex();
}
@Override
public void readerIndex(int readerIndex) {
buffer.readerIndex(readerIndex);
}
@Override
public void readBytes(OutputStream dst, int length) throws IOException {
buffer.readBytes(dst, length);
}
@Override
public void setBytes(int index, byte[] src) {
buffer.setBytes(index, src);
}
@Override
public void setBytes(int index, ChannelBuffer src) {
// careful
setBytes(index, src, src.readableBytes());
}
@Override
public void setBytes(int index, ChannelBuffer src, int length) {
// careful
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
setBytes(index, src, src.readerIndex(), length);
src.readerIndex(src.readerIndex() + length);
}
@Override
public void setIndex(int readerIndex, int writerIndex) {
buffer.setIndex(readerIndex, writerIndex);
}
@Override
public void skipBytes(int length) {
buffer.skipBytes(length);
}
@Override
public ByteBuffer toByteBuffer() {
return buffer.toByteBuffer();
}
@Override
public boolean writable() {
return buffer.writable();
}
@Override
public int writableBytes() {
return buffer.writableBytes();
}
@Override
public void writeByte(int value) {
buffer.writeByte(value);
}
@Override
public void writeBytes(byte[] src) {
buffer.writeBytes(src);
}
@Override
public void writeBytes(byte[] src, int index, int length) {
buffer.writeBytes(src, index, length);
}
@Override
public void writeBytes(ByteBuffer src) {
buffer.writeBytes(src);
}
@Override
public void writeBytes(ChannelBuffer src) {
// careful
writeBytes(src, src.readableBytes());
}
@Override
public void writeBytes(ChannelBuffer src, int length) {
// careful
if (length > src.readableBytes()) {
throw new IndexOutOfBoundsException();
}
writeBytes(src, src.readerIndex(), length);
src.readerIndex(src.readerIndex() + length);
}
@Override
public void writeBytes(ChannelBuffer src, int srcIndex, int length) {
// careful
byte[] data = new byte[length];
src.getBytes(srcIndex, data, 0, length);
writeBytes(data, 0, length);
}
@Override
public int writeBytes(InputStream src, int length) throws IOException {
return buffer.writeBytes(src, length);
}
@Override
public int writerIndex() {
return buffer.writerIndex();
}
@Override
public void writerIndex(int writerIndex) {
buffer.writerIndex(writerIndex);
}
@Override
public int compareTo(ChannelBuffer o) {
return ChannelBuffers.compare(this, o);
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java | dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyCodecAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.Codec2;
import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer;
import java.io.IOException;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import static org.apache.dubbo.remoting.Constants.BUFFER_KEY;
import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE;
import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE;
import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE;
/**
* NettyCodecAdapter.
*/
final class NettyCodecAdapter {
private final ChannelHandler encoder = new InternalEncoder();
private final ChannelHandler decoder = new InternalDecoder();
private final Codec2 codec;
private final URL url;
private final int bufferSize;
private final org.apache.dubbo.remoting.ChannelHandler handler;
public NettyCodecAdapter(Codec2 codec, URL url, org.apache.dubbo.remoting.ChannelHandler handler) {
this.codec = codec;
this.url = url;
this.handler = handler;
int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE);
this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE;
}
public ChannelHandler getEncoder() {
return encoder;
}
public ChannelHandler getDecoder() {
return decoder;
}
@Sharable
private class InternalEncoder extends OneToOneEncoder {
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
org.apache.dubbo.remoting.buffer.ChannelBuffer buffer =
org.apache.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
try {
codec.encode(channel, buffer, msg);
} finally {
NettyChannel.removeChannelIfDisconnected(ch);
}
return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
}
private class InternalDecoder extends SimpleChannelUpstreamHandler {
private org.apache.dubbo.remoting.buffer.ChannelBuffer buffer =
org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
Object o = event.getMessage();
if (!(o instanceof ChannelBuffer)) {
ctx.sendUpstream(event);
return;
}
ChannelBuffer input = (ChannelBuffer) o;
int readable = input.readableBytes();
if (readable <= 0) {
return;
}
org.apache.dubbo.remoting.buffer.ChannelBuffer message;
if (buffer.readable()) {
if (buffer instanceof DynamicChannelBuffer) {
buffer.writeBytes(input.toByteBuffer());
message = buffer;
} else {
int size = buffer.readableBytes() + input.readableBytes();
message = org.apache.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(
size > bufferSize ? size : bufferSize);
message.writeBytes(buffer, buffer.readableBytes());
message.writeBytes(input.toByteBuffer());
}
} else {
message = org.apache.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer(input.toByteBuffer());
}
NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler);
Object msg;
int saveReaderIndex;
try {
// decode object.
do {
saveReaderIndex = message.readerIndex();
try {
msg = codec.decode(channel, message);
} catch (IOException e) {
buffer = org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
throw e;
}
if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) {
message.readerIndex(saveReaderIndex);
break;
} else {
if (saveReaderIndex == message.readerIndex()) {
buffer = org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
throw new IOException("Decode without read data.");
}
if (msg != null) {
Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress());
}
}
} while (message.readable());
} finally {
if (message.readable()) {
message.discardReadBytes();
buffer = message;
} else {
buffer = org.apache.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER;
}
NettyChannel.removeChannelIfDisconnected(ctx.getChannel());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
ctx.sendUpstream(e);
}
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
apache/dubbo | https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java | dubbo-remoting/dubbo-remoting-netty/src/main/java/org/apache/dubbo/remoting/transport/netty/NettyPortUnificationServer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport.netty;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.remoting.Channel;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.api.WireProtocol;
import org.apache.dubbo.remoting.api.pu.AbstractPortUnificationServer;
import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.BACKLOG_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.TRANSPORT_FAILED_CLOSE;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME;
import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_WORKER_POOL_NAME;
/**
* NettyServer
*/
public class NettyPortUnificationServer extends AbstractPortUnificationServer {
// <ip:port, channel>
private Map<String, Channel> dubboChannels;
private ServerBootstrap bootstrap;
private org.jboss.netty.channel.Channel channel;
public NettyPortUnificationServer(URL url, ChannelHandler handler) throws RemotingException {
super(url, ChannelHandlers.wrap(handler, url));
}
@Override
public void addSupportedProtocol(URL url, ChannelHandler handler) {
super.addSupportedProtocol(url, ChannelHandlers.wrap(handler, url));
}
@Override
public void close() {
if (channel != null) {
doClose();
}
}
public void bind() {
if (channel == null) {
doOpen();
}
}
@Override
protected void doOpen0() {
NettyHelper.setNettyLoggerFactory();
ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_BOSS_POOL_NAME, true));
ExecutorService worker =
Executors.newCachedThreadPool(new NamedThreadFactory(EVENT_LOOP_WORKER_POOL_NAME, true));
ChannelFactory channelFactory = new NioServerSocketChannelFactory(
boss, worker, getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
bootstrap = new ServerBootstrap(channelFactory);
final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
// set dubboChannels
dubboChannels = nettyHandler.getChannels();
// https://issues.jboss.org/browse/NETTY-365
// https://issues.jboss.org/browse/NETTY-379
// final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("backlog", getUrl().getPositiveParameter(BACKLOG_KEY, Constants.DEFAULT_BACKLOG));
bootstrap.setOption("reuseAddress", true);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() {
NettyCodecAdapter adapter =
new NettyCodecAdapter(getCodec(), getUrl(), NettyPortUnificationServer.this);
ChannelPipeline pipeline = Channels.pipeline();
/*int idleTimeout = getIdleTimeout();
if (idleTimeout > 10000) {
pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
}*/
pipeline.addLast("decoder", adapter.getDecoder());
pipeline.addLast("encoder", adapter.getEncoder());
pipeline.addLast("handler", nettyHandler);
return pipeline;
}
});
// bind
String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost());
int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort());
if (getUrl().getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) {
bindIp = ANYHOST_VALUE;
}
InetSocketAddress bindAddress = new InetSocketAddress(bindIp, bindPort);
channel = bootstrap.bind(bindAddress);
}
@Override
protected void doClose() {
try {
if (channel != null) {
// unbind.
channel.close();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
Collection<Channel> channels = getChannels();
if (CollectionUtils.isNotEmpty(channels)) {
for (Channel channel : channels) {
try {
channel.close();
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
for (WireProtocol protocol : getProtocols().values()) {
protocol.close();
}
try {
if (bootstrap != null) {
// release external resource.
bootstrap.releaseExternalResources();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
try {
if (dubboChannels != null) {
dubboChannels.clear();
}
} catch (Throwable e) {
logger.warn(TRANSPORT_FAILED_CLOSE, "", "", e.getMessage(), e);
}
}
@Override
protected int getChannelsSize() {
return dubboChannels.size();
}
@Override
public Collection<Channel> getChannels() {
Collection<Channel> chs = new ArrayList<>(this.dubboChannels.size());
chs.addAll(this.dubboChannels.values());
return chs;
}
@Override
public Channel getChannel(InetSocketAddress remoteAddress) {
return dubboChannels.get(NetUtils.toAddressString(remoteAddress));
}
public InetSocketAddress getLocalAddress() {
return (InetSocketAddress) channel.getLocalAddress();
}
@Override
public boolean isBound() {
return channel.isBound();
}
}
| java | Apache-2.0 | ac1621f9a0470054c0308c47f84c7668f6bc2868 | 2026-01-04T14:45:57.057261Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.