mirror of
https://gitee.com/mirrors/Spring-Cloud-Alibaba.git
synced 2021-06-26 13:25:11 +08:00
Merge pull request #1746 from mercyblitz/greenwich
[CodeBase] Sync the source code from 2.2.3.RELEASE to 2.1.3.RELEASE
This commit is contained in:
commit
071256d56a
2
pom.xml
2
pom.xml
@ -80,7 +80,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- Project revision -->
|
<!-- Project revision -->
|
||||||
<revision>2.1.2.RELEASE</revision>
|
<revision>2.1.3.RELEASE</revision>
|
||||||
|
|
||||||
<!-- Dependency Versions -->
|
<!-- Dependency Versions -->
|
||||||
<spring-cloud-commons.version>2.1.6.RELEASE</spring-cloud-commons.version>
|
<spring-cloud-commons.version>2.1.6.RELEASE</spring-cloud-commons.version>
|
||||||
|
@ -10,7 +10,7 @@ Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba.cloud</groupId>
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||||
<version>2.1.2.RELEASE</version>
|
<version>2.1.3.RELEASE</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
@ -8,7 +8,7 @@ If you’re a Maven Central user, add our BOM to your pom.xml <dependencyManagem
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba.cloud</groupId>
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||||
<version>2.1.2.RELEASE</version>
|
<version>2.1.3.RELEASE</version>
|
||||||
<type>pom</type>
|
<type>pom</type>
|
||||||
<scope>import</scope>
|
<scope>import</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
@ -94,4 +94,5 @@ public class ConsulDataSourceProperties extends AbstractDataSourceProperties {
|
|||||||
public void setWaitTimeoutInSecond(int waitTimeoutInSecond) {
|
public void setWaitTimeoutInSecond(int waitTimeoutInSecond) {
|
||||||
this.waitTimeoutInSecond = waitTimeoutInSecond;
|
this.waitTimeoutInSecond = waitTimeoutInSecond;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -47,9 +47,23 @@ public class DataSourcePropertiesConfiguration {
|
|||||||
|
|
||||||
private RedisDataSourceProperties redis;
|
private RedisDataSourceProperties redis;
|
||||||
|
|
||||||
|
private ConsulDataSourceProperties consul;
|
||||||
|
|
||||||
public DataSourcePropertiesConfiguration() {
|
public DataSourcePropertiesConfiguration() {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public DataSourcePropertiesConfiguration(ConsulDataSourceProperties consul) {
|
||||||
|
this.consul = consul;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ConsulDataSourceProperties getConsul() {
|
||||||
|
return consul;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setConsul(ConsulDataSourceProperties consul) {
|
||||||
|
this.consul = consul;
|
||||||
|
}
|
||||||
|
|
||||||
public DataSourcePropertiesConfiguration(FileDataSourceProperties file) {
|
public DataSourcePropertiesConfiguration(FileDataSourceProperties file) {
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
@ -32,6 +32,10 @@ public class NacosDataSourceProperties extends AbstractDataSourceProperties {
|
|||||||
|
|
||||||
private String serverAddr;
|
private String serverAddr;
|
||||||
|
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
private String password;
|
||||||
|
|
||||||
@NotEmpty
|
@NotEmpty
|
||||||
private String groupId = "DEFAULT_GROUP";
|
private String groupId = "DEFAULT_GROUP";
|
||||||
|
|
||||||
@ -67,6 +71,22 @@ public class NacosDataSourceProperties extends AbstractDataSourceProperties {
|
|||||||
this.serverAddr = serverAddr;
|
this.serverAddr = serverAddr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
public String getGroupId() {
|
public String getGroupId() {
|
||||||
return groupId;
|
return groupId;
|
||||||
}
|
}
|
||||||
|
@ -24,7 +24,7 @@ import com.alibaba.cloud.sentinel.datasource.factorybean.RedisDataSourceFactoryB
|
|||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Zookeeper Properties class Using by {@link DataSourcePropertiesConfiguration} and
|
* Redis Properties class Using by {@link DataSourcePropertiesConfiguration} and
|
||||||
* {@link RedisDataSourceFactoryBean}.
|
* {@link RedisDataSourceFactoryBean}.
|
||||||
*
|
*
|
||||||
* @author <a href="mailto:wangiegie@gmail.com">lengleng</a>
|
* @author <a href="mailto:wangiegie@gmail.com">lengleng</a>
|
||||||
@ -93,7 +93,7 @@ public class RedisDataSourceProperties extends AbstractDataSourceProperties {
|
|||||||
"RedisDataSource channel can not be empty");
|
"RedisDataSource channel can not be empty");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!StringUtils.isEmpty(masterId) && StringUtils.isEmpty(masterId)) {
|
if (StringUtils.isEmpty(masterId)) {
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"RedisDataSource sentinel model,masterId can not be empty");
|
"RedisDataSource sentinel model,masterId can not be empty");
|
||||||
}
|
}
|
||||||
|
@ -88,4 +88,5 @@ public class ConsulDataSourceFactoryBean implements FactoryBean<ConsulDataSource
|
|||||||
public void setConverter(Converter converter) {
|
public void setConverter(Converter converter) {
|
||||||
this.converter = converter;
|
this.converter = converter;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -35,6 +35,10 @@ public class NacosDataSourceFactoryBean implements FactoryBean<NacosDataSource>
|
|||||||
|
|
||||||
private String serverAddr;
|
private String serverAddr;
|
||||||
|
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
private String password;
|
||||||
|
|
||||||
private String groupId;
|
private String groupId;
|
||||||
|
|
||||||
private String dataId;
|
private String dataId;
|
||||||
@ -63,6 +67,12 @@ public class NacosDataSourceFactoryBean implements FactoryBean<NacosDataSource>
|
|||||||
if (!StringUtils.isEmpty(this.namespace)) {
|
if (!StringUtils.isEmpty(this.namespace)) {
|
||||||
properties.setProperty(PropertyKeyConst.NAMESPACE, this.namespace);
|
properties.setProperty(PropertyKeyConst.NAMESPACE, this.namespace);
|
||||||
}
|
}
|
||||||
|
if (!StringUtils.isEmpty(this.username)) {
|
||||||
|
properties.setProperty(PropertyKeyConst.USERNAME, this.username);
|
||||||
|
}
|
||||||
|
if (!StringUtils.isEmpty(this.password)) {
|
||||||
|
properties.setProperty(PropertyKeyConst.PASSWORD, this.password);
|
||||||
|
}
|
||||||
return new NacosDataSource(properties, groupId, dataId, converter);
|
return new NacosDataSource(properties, groupId, dataId, converter);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,6 +89,22 @@ public class NacosDataSourceFactoryBean implements FactoryBean<NacosDataSource>
|
|||||||
this.serverAddr = serverAddr;
|
this.serverAddr = serverAddr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
public String getGroupId() {
|
public String getGroupId() {
|
||||||
return groupId;
|
return groupId;
|
||||||
}
|
}
|
||||||
|
@ -90,7 +90,8 @@ public class SentinelSCGAutoConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void initAppType() {
|
private void initAppType() {
|
||||||
System.setProperty(SentinelConfig.APP_TYPE, ConfigConstants.APP_TYPE_SCG_GATEWAY);
|
System.setProperty(SentinelConfig.APP_TYPE_PROP_KEY,
|
||||||
|
ConfigConstants.APP_TYPE_SCG_GATEWAY);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void initFallback() {
|
private void initFallback() {
|
||||||
|
@ -64,7 +64,7 @@ public class SentinelZuulAutoConfiguration {
|
|||||||
private void init() {
|
private void init() {
|
||||||
requestOriginParserOptional
|
requestOriginParserOptional
|
||||||
.ifPresent(ZuulGatewayCallbackManager::setOriginParser);
|
.ifPresent(ZuulGatewayCallbackManager::setOriginParser);
|
||||||
System.setProperty(SentinelConfig.APP_TYPE,
|
System.setProperty(SentinelConfig.APP_TYPE_PROP_KEY,
|
||||||
String.valueOf(ConfigConstants.APP_TYPE_ZUUL_GATEWAY));
|
String.valueOf(ConfigConstants.APP_TYPE_ZUUL_GATEWAY));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,7 +22,6 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
@ -485,8 +484,7 @@ public class NacosConfigProperties {
|
|||||||
List<Config> result = new ArrayList<>();
|
List<Config> result = new ArrayList<>();
|
||||||
configList.stream()
|
configList.stream()
|
||||||
.collect(Collectors.groupingBy(cfg -> (cfg.getGroup() + cfg.getDataId()),
|
.collect(Collectors.groupingBy(cfg -> (cfg.getGroup() + cfg.getDataId()),
|
||||||
() -> new ConcurrentHashMap<>(new LinkedHashMap<>()),
|
LinkedHashMap::new, Collectors.toList()))
|
||||||
Collectors.toList()))
|
|
||||||
.forEach((key, list) -> {
|
.forEach((key, list) -> {
|
||||||
list.stream()
|
list.stream()
|
||||||
.reduce((a, b) -> new Config(a.getDataId(), a.getGroup(),
|
.reduce((a, b) -> new Config(a.getDataId(), a.getGroup(),
|
||||||
|
@ -55,7 +55,9 @@ public class NacosDataPropertiesParser extends AbstractNacosDataParser {
|
|||||||
log.warn("the config data is invalid {}", dataLine);
|
log.warn("the config data is invalid {}", dataLine);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
result.put(dataLine.substring(0, index), dataLine.substring(index + 1));
|
String key = dataLine.substring(0, index);
|
||||||
|
String value = dataLine.substring(index + 1);
|
||||||
|
result.put(key.trim(), value.trim());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
|
@ -19,7 +19,6 @@ package com.alibaba.cloud.nacos;
|
|||||||
import java.net.Inet4Address;
|
import java.net.Inet4Address;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.NetworkInterface;
|
import java.net.NetworkInterface;
|
||||||
import java.net.SocketException;
|
|
||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@ -30,9 +29,7 @@ import java.util.regex.Pattern;
|
|||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import javax.annotation.PostConstruct;
|
||||||
|
|
||||||
import com.alibaba.nacos.api.NacosFactory;
|
import com.alibaba.cloud.nacos.event.NacosDiscoveryInfoChangedEvent;
|
||||||
import com.alibaba.nacos.api.naming.NamingMaintainFactory;
|
|
||||||
import com.alibaba.nacos.api.naming.NamingMaintainService;
|
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
|
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
|
||||||
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
|
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
|
||||||
@ -44,6 +41,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
import org.springframework.cloud.commons.util.InetUtils;
|
import org.springframework.cloud.commons.util.InetUtils;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
import org.springframework.core.env.ConfigurableEnvironment;
|
import org.springframework.core.env.ConfigurableEnvironment;
|
||||||
import org.springframework.core.env.Environment;
|
import org.springframework.core.env.Environment;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@ -64,8 +62,8 @@ import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME;
|
|||||||
* @author xiaojing
|
* @author xiaojing
|
||||||
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
||||||
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
|
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
|
||||||
|
* @author <a href="mailto:78552423@qq.com">eshun</a>
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ConfigurationProperties("spring.cloud.nacos.discovery")
|
@ConfigurationProperties("spring.cloud.nacos.discovery")
|
||||||
public class NacosDiscoveryProperties {
|
public class NacosDiscoveryProperties {
|
||||||
|
|
||||||
@ -199,18 +197,30 @@ public class NacosDiscoveryProperties {
|
|||||||
*/
|
*/
|
||||||
private Integer ipDeleteTimeout;
|
private Integer ipDeleteTimeout;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If instance is enabled to accept request. The default value is true.
|
||||||
|
*/
|
||||||
|
private boolean instanceEnabled = true;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If instance is ephemeral.The default value is true.
|
||||||
|
*/
|
||||||
|
private boolean ephemeral = true;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private InetUtils inetUtils;
|
private InetUtils inetUtils;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private Environment environment;
|
private Environment environment;
|
||||||
|
|
||||||
private static NamingService namingService;
|
@Autowired
|
||||||
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
private static NamingMaintainService namingMaintainService;
|
@Autowired
|
||||||
|
private ApplicationEventPublisher applicationEventPublisher;
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void init() throws SocketException {
|
public void init() throws Exception {
|
||||||
|
|
||||||
metadata.put(PreservedMetadataKeys.REGISTER_SOURCE, "SPRING_CLOUD");
|
metadata.put(PreservedMetadataKeys.REGISTER_SOURCE, "SPRING_CLOUD");
|
||||||
if (secure) {
|
if (secure) {
|
||||||
@ -257,6 +267,19 @@ public class NacosDiscoveryProperties {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.overrideFromEnv(environment);
|
this.overrideFromEnv(environment);
|
||||||
|
if (nacosServiceManager.isNacosDiscoveryInfoChanged(this)) {
|
||||||
|
applicationEventPublisher
|
||||||
|
.publishEvent(new NacosDiscoveryInfoChangedEvent(this));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* recommend to use {@link NacosServiceManager#getNamingService(Properties)}.
|
||||||
|
* @return NamingService
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public NamingService namingServiceInstance() {
|
||||||
|
return nacosServiceManager.getNamingService(this.getNacosProperties());
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getEndpoint() {
|
public String getEndpoint() {
|
||||||
@ -447,6 +470,58 @@ public class NacosDiscoveryProperties {
|
|||||||
this.password = password;
|
this.password = password;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isInstanceEnabled() {
|
||||||
|
return instanceEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setInstanceEnabled(boolean instanceEnabled) {
|
||||||
|
this.instanceEnabled = instanceEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEphemeral() {
|
||||||
|
return ephemeral;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEphemeral(boolean ephemeral) {
|
||||||
|
this.ephemeral = ephemeral;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
NacosDiscoveryProperties that = (NacosDiscoveryProperties) o;
|
||||||
|
return Objects.equals(serverAddr, that.serverAddr)
|
||||||
|
&& Objects.equals(username, that.username)
|
||||||
|
&& Objects.equals(password, that.password)
|
||||||
|
&& Objects.equals(endpoint, that.endpoint)
|
||||||
|
&& Objects.equals(namespace, that.namespace)
|
||||||
|
&& Objects.equals(logName, that.logName)
|
||||||
|
&& Objects.equals(service, that.service)
|
||||||
|
&& Objects.equals(clusterName, that.clusterName)
|
||||||
|
&& Objects.equals(group, that.group) && Objects.equals(ip, that.ip)
|
||||||
|
&& Objects.equals(port, that.port)
|
||||||
|
&& Objects.equals(networkInterface, that.networkInterface)
|
||||||
|
&& Objects.equals(accessKey, that.accessKey)
|
||||||
|
&& Objects.equals(secretKey, that.secretKey)
|
||||||
|
&& Objects.equals(heartBeatInterval, that.heartBeatInterval)
|
||||||
|
&& Objects.equals(heartBeatTimeout, that.heartBeatTimeout)
|
||||||
|
&& Objects.equals(ipDeleteTimeout, that.ipDeleteTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(serverAddr, username, password, endpoint, namespace,
|
||||||
|
watchDelay, logName, service, weight, clusterName, group,
|
||||||
|
namingLoadCacheAtStart, registerEnabled, ip, networkInterface, port,
|
||||||
|
secure, accessKey, secretKey, heartBeatInterval, heartBeatTimeout,
|
||||||
|
ipDeleteTimeout, instanceEnabled, ephemeral);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\''
|
return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\''
|
||||||
@ -510,41 +585,7 @@ public class NacosDiscoveryProperties {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public NamingService namingServiceInstance() {
|
public Properties getNacosProperties() {
|
||||||
|
|
||||||
if (null != namingService) {
|
|
||||||
return namingService;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
namingService = NacosFactory.createNamingService(getNacosProperties());
|
|
||||||
}
|
|
||||||
catch (Exception e) {
|
|
||||||
log.error("create naming service error!properties={},e=,", this, e);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return namingService;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Deprecated
|
|
||||||
public NamingMaintainService namingMaintainServiceInstance() {
|
|
||||||
|
|
||||||
if (null != namingMaintainService) {
|
|
||||||
return namingMaintainService;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
namingMaintainService = NamingMaintainFactory
|
|
||||||
.createMaintainService(getNacosProperties());
|
|
||||||
}
|
|
||||||
catch (Exception e) {
|
|
||||||
log.error("create naming service error!properties={},e=,", this, e);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return namingMaintainService;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Properties getNacosProperties() {
|
|
||||||
Properties properties = new Properties();
|
Properties properties = new Properties();
|
||||||
properties.put(SERVER_ADDR, serverAddr);
|
properties.put(SERVER_ADDR, serverAddr);
|
||||||
properties.put(USERNAME, Objects.toString(username, ""));
|
properties.put(USERNAME, Objects.toString(username, ""));
|
||||||
|
@ -0,0 +1,36 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2018 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed 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
|
||||||
|
*
|
||||||
|
* https://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 com.alibaba.cloud.nacos;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author yuhuangbin
|
||||||
|
*/
|
||||||
|
@Configuration
|
||||||
|
@ConditionalOnDiscoveryEnabled
|
||||||
|
@ConditionalOnNacosDiscoveryEnabled
|
||||||
|
public class NacosServiceAutoConfiguration {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public NacosServiceManager nacosServiceManager() {
|
||||||
|
return new NacosServiceManager();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,134 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2018 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed 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
|
||||||
|
*
|
||||||
|
* https://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 com.alibaba.cloud.nacos;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import com.alibaba.cloud.nacos.registry.NacosRegistration;
|
||||||
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
|
import com.alibaba.nacos.api.naming.NamingMaintainService;
|
||||||
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import org.springframework.cloud.client.discovery.event.InstancePreRegisteredEvent;
|
||||||
|
import org.springframework.cloud.client.serviceregistry.Registration;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
|
||||||
|
import static com.alibaba.nacos.api.NacosFactory.createMaintainService;
|
||||||
|
import static com.alibaba.nacos.api.NacosFactory.createNamingService;
|
||||||
|
import static org.springframework.beans.BeanUtils.copyProperties;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author yuhuangbin
|
||||||
|
*/
|
||||||
|
public class NacosServiceManager {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(NacosServiceManager.class);
|
||||||
|
|
||||||
|
private NacosDiscoveryProperties nacosDiscoveryPropertiesCache;
|
||||||
|
|
||||||
|
private NamingService namingService;
|
||||||
|
|
||||||
|
private NamingMaintainService namingMaintainService;
|
||||||
|
|
||||||
|
public NamingService getNamingService(Properties properties) {
|
||||||
|
if (Objects.isNull(this.namingService)) {
|
||||||
|
buildNamingService(properties);
|
||||||
|
}
|
||||||
|
return namingService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public NamingMaintainService getNamingMaintainService(Properties properties) {
|
||||||
|
if (Objects.isNull(namingMaintainService)) {
|
||||||
|
buildNamingMaintainService(properties);
|
||||||
|
}
|
||||||
|
return namingMaintainService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isNacosDiscoveryInfoChanged(
|
||||||
|
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
|
if (Objects.isNull(nacosDiscoveryPropertiesCache)
|
||||||
|
|| this.nacosDiscoveryPropertiesCache.equals(nacosDiscoveryProperties)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
copyProperties(nacosDiscoveryProperties, nacosDiscoveryPropertiesCache);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NamingMaintainService buildNamingMaintainService(Properties properties) {
|
||||||
|
if (Objects.isNull(namingMaintainService)) {
|
||||||
|
synchronized (NacosServiceManager.class) {
|
||||||
|
if (Objects.isNull(namingMaintainService)) {
|
||||||
|
namingMaintainService = createNamingMaintainService(properties);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return namingMaintainService;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NamingService buildNamingService(Properties properties) {
|
||||||
|
if (Objects.isNull(namingService)) {
|
||||||
|
synchronized (NacosServiceManager.class) {
|
||||||
|
if (Objects.isNull(namingService)) {
|
||||||
|
namingService = createNewNamingService(properties);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return namingService;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NamingService createNewNamingService(Properties properties) {
|
||||||
|
try {
|
||||||
|
return createNamingService(properties);
|
||||||
|
}
|
||||||
|
catch (NacosException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private NamingMaintainService createNamingMaintainService(Properties properties) {
|
||||||
|
try {
|
||||||
|
return createMaintainService(properties);
|
||||||
|
}
|
||||||
|
catch (NacosException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void nacosServiceShutDown() throws NacosException {
|
||||||
|
this.namingService.shutDown();
|
||||||
|
namingService = null;
|
||||||
|
namingMaintainService = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@EventListener
|
||||||
|
public void onInstancePreRegisteredEvent(
|
||||||
|
InstancePreRegisteredEvent instancePreRegisteredEvent) {
|
||||||
|
Registration registration = instancePreRegisteredEvent.getRegistration();
|
||||||
|
if (Objects.isNull(nacosDiscoveryPropertiesCache)
|
||||||
|
&& registration instanceof NacosRegistration) {
|
||||||
|
NacosDiscoveryProperties nacosDiscoveryProperties = ((NacosRegistration) registration)
|
||||||
|
.getNacosDiscoveryProperties();
|
||||||
|
|
||||||
|
nacosDiscoveryPropertiesCache = new NacosDiscoveryProperties();
|
||||||
|
copyProperties(nacosDiscoveryProperties, nacosDiscoveryPropertiesCache);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -18,6 +18,7 @@ package com.alibaba.cloud.nacos.discovery;
|
|||||||
|
|
||||||
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
|
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
|
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
|
||||||
@ -41,8 +42,9 @@ public class NacosDiscoveryAutoConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public NacosServiceDiscovery nacosServiceDiscovery(
|
public NacosServiceDiscovery nacosServiceDiscovery(
|
||||||
NacosDiscoveryProperties discoveryProperties) {
|
NacosDiscoveryProperties discoveryProperties,
|
||||||
return new NacosServiceDiscovery(discoveryProperties);
|
NacosServiceManager nacosServiceManager) {
|
||||||
|
return new NacosServiceDiscovery(discoveryProperties, nacosServiceManager);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -18,6 +18,7 @@ package com.alibaba.cloud.nacos.discovery;
|
|||||||
|
|
||||||
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
|
|
||||||
import org.springframework.beans.factory.ObjectProvider;
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
@ -55,9 +56,11 @@ public class NacosDiscoveryClientConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.watch.enabled", matchIfMissing = true)
|
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.watch.enabled", matchIfMissing = true)
|
||||||
public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties,
|
public NacosWatch nacosWatch(NacosServiceManager nacosServiceManager,
|
||||||
ObjectProvider<TaskScheduler> taskScheduler) {
|
NacosDiscoveryProperties nacosDiscoveryProperties,
|
||||||
return new NacosWatch(nacosDiscoveryProperties, taskScheduler);
|
ObjectProvider<TaskScheduler> taskExecutorObjectProvider) {
|
||||||
|
return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties,
|
||||||
|
taskExecutorObjectProvider);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,9 @@ import java.util.Map;
|
|||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
import com.alibaba.cloud.nacos.NacosServiceInstance;
|
import com.alibaba.cloud.nacos.NacosServiceInstance;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.nacos.api.exception.NacosException;
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||||
import com.alibaba.nacos.api.naming.pojo.ListView;
|
import com.alibaba.nacos.api.naming.pojo.ListView;
|
||||||
|
|
||||||
@ -36,8 +38,12 @@ public class NacosServiceDiscovery {
|
|||||||
|
|
||||||
private NacosDiscoveryProperties discoveryProperties;
|
private NacosDiscoveryProperties discoveryProperties;
|
||||||
|
|
||||||
public NacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties) {
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
|
public NacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties,
|
||||||
|
NacosServiceManager nacosServiceManager) {
|
||||||
this.discoveryProperties = discoveryProperties;
|
this.discoveryProperties = discoveryProperties;
|
||||||
|
this.nacosServiceManager = nacosServiceManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -48,8 +54,8 @@ public class NacosServiceDiscovery {
|
|||||||
*/
|
*/
|
||||||
public List<ServiceInstance> getInstances(String serviceId) throws NacosException {
|
public List<ServiceInstance> getInstances(String serviceId) throws NacosException {
|
||||||
String group = discoveryProperties.getGroup();
|
String group = discoveryProperties.getGroup();
|
||||||
List<Instance> instances = discoveryProperties.namingServiceInstance()
|
List<Instance> instances = namingService().selectInstances(serviceId, group,
|
||||||
.selectInstances(serviceId, group, true);
|
true);
|
||||||
return hostToServiceInstanceList(instances, serviceId);
|
return hostToServiceInstanceList(instances, serviceId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -60,8 +66,8 @@ public class NacosServiceDiscovery {
|
|||||||
*/
|
*/
|
||||||
public List<String> getServices() throws NacosException {
|
public List<String> getServices() throws NacosException {
|
||||||
String group = discoveryProperties.getGroup();
|
String group = discoveryProperties.getGroup();
|
||||||
ListView<String> services = discoveryProperties.namingServiceInstance()
|
ListView<String> services = namingService().getServicesOfServer(1,
|
||||||
.getServicesOfServer(1, Integer.MAX_VALUE, group);
|
Integer.MAX_VALUE, group);
|
||||||
return services.getData();
|
return services.getData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -92,7 +98,10 @@ public class NacosServiceDiscovery {
|
|||||||
metadata.put("nacos.weight", instance.getWeight() + "");
|
metadata.put("nacos.weight", instance.getWeight() + "");
|
||||||
metadata.put("nacos.healthy", instance.isHealthy() + "");
|
metadata.put("nacos.healthy", instance.isHealthy() + "");
|
||||||
metadata.put("nacos.cluster", instance.getClusterName() + "");
|
metadata.put("nacos.cluster", instance.getClusterName() + "");
|
||||||
metadata.putAll(instance.getMetadata());
|
if (instance.getMetadata() != null) {
|
||||||
|
metadata.putAll(instance.getMetadata());
|
||||||
|
}
|
||||||
|
metadata.put("nacos.ephemeral", String.valueOf(instance.isEphemeral()));
|
||||||
nacosServiceInstance.setMetadata(metadata);
|
nacosServiceInstance.setMetadata(metadata);
|
||||||
|
|
||||||
if (metadata.containsKey("secure")) {
|
if (metadata.containsKey("secure")) {
|
||||||
@ -102,4 +111,9 @@ public class NacosServiceDiscovery {
|
|||||||
return nacosServiceInstance;
|
return nacosServiceInstance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private NamingService namingService() {
|
||||||
|
return nacosServiceManager
|
||||||
|
.getNamingService(discoveryProperties.getNacosProperties());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -16,11 +16,23 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.nacos.discovery;
|
package com.alibaba.cloud.nacos.discovery;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.ScheduledFuture;
|
import java.util.concurrent.ScheduledFuture;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
|
import com.alibaba.nacos.api.naming.listener.Event;
|
||||||
|
import com.alibaba.nacos.api.naming.listener.EventListener;
|
||||||
|
import com.alibaba.nacos.api.naming.listener.NamingEvent;
|
||||||
|
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -34,47 +46,39 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @author xiaojing
|
* @author xiaojing
|
||||||
|
* @author yuhuangbin
|
||||||
*/
|
*/
|
||||||
public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle {
|
public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(NacosWatch.class);
|
private static final Logger log = LoggerFactory.getLogger(NacosWatch.class);
|
||||||
|
|
||||||
private final NacosDiscoveryProperties properties;
|
private Map<String, EventListener> listenerMap = new ConcurrentHashMap<>(16);
|
||||||
|
|
||||||
private final TaskScheduler taskScheduler;
|
|
||||||
|
|
||||||
private final AtomicLong nacosWatchIndex = new AtomicLong(0);
|
|
||||||
|
|
||||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
private final AtomicLong nacosWatchIndex = new AtomicLong(0);
|
||||||
|
|
||||||
private ApplicationEventPublisher publisher;
|
private ApplicationEventPublisher publisher;
|
||||||
|
|
||||||
private ScheduledFuture<?> watchFuture;
|
private ScheduledFuture<?> watchFuture;
|
||||||
|
|
||||||
public NacosWatch(NacosDiscoveryProperties properties) {
|
private NacosServiceManager nacosServiceManager;
|
||||||
this(properties, getTaskScheduler());
|
|
||||||
}
|
|
||||||
|
|
||||||
public NacosWatch(NacosDiscoveryProperties properties, TaskScheduler taskScheduler) {
|
private final NacosDiscoveryProperties properties;
|
||||||
this.properties = properties;
|
|
||||||
this.taskScheduler = taskScheduler;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
private final TaskScheduler taskScheduler;
|
||||||
* The constructor with {@link NacosDiscoveryProperties} bean and the optional.
|
|
||||||
* {@link TaskScheduler} bean
|
public NacosWatch(NacosServiceManager nacosServiceManager,
|
||||||
* @param properties {@link NacosDiscoveryProperties} bean
|
NacosDiscoveryProperties properties,
|
||||||
* @param taskScheduler the optional {@link TaskScheduler} bean
|
|
||||||
* @since 2.2.0
|
|
||||||
*/
|
|
||||||
public NacosWatch(NacosDiscoveryProperties properties,
|
|
||||||
ObjectProvider<TaskScheduler> taskScheduler) {
|
ObjectProvider<TaskScheduler> taskScheduler) {
|
||||||
this(properties, taskScheduler.getIfAvailable(NacosWatch::getTaskScheduler));
|
this.nacosServiceManager = nacosServiceManager;
|
||||||
|
this.properties = properties;
|
||||||
|
this.taskScheduler = taskScheduler.getIfAvailable(NacosWatch::getTaskScheduler);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ThreadPoolTaskScheduler getTaskScheduler() {
|
private static ThreadPoolTaskScheduler getTaskScheduler() {
|
||||||
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
|
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
|
||||||
taskScheduler.setBeanName("Nacso-Watch-Task-Scheduler");
|
taskScheduler.setBeanName("Nacos-Watch-Task-Scheduler");
|
||||||
taskScheduler.initialize();
|
taskScheduler.initialize();
|
||||||
return taskScheduler;
|
return taskScheduler;
|
||||||
}
|
}
|
||||||
@ -98,19 +102,75 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl
|
|||||||
@Override
|
@Override
|
||||||
public void start() {
|
public void start() {
|
||||||
if (this.running.compareAndSet(false, true)) {
|
if (this.running.compareAndSet(false, true)) {
|
||||||
|
EventListener eventListener = listenerMap.computeIfAbsent(buildKey(),
|
||||||
|
event -> new EventListener() {
|
||||||
|
@Override
|
||||||
|
public void onEvent(Event event) {
|
||||||
|
if (event instanceof NamingEvent) {
|
||||||
|
List<Instance> instances = ((NamingEvent) event)
|
||||||
|
.getInstances();
|
||||||
|
Optional<Instance> instanceOptional = selectCurrentInstance(
|
||||||
|
instances);
|
||||||
|
instanceOptional.ifPresent(currentInstance -> {
|
||||||
|
resetIfNeeded(currentInstance);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
NamingService namingService = nacosServiceManager
|
||||||
|
.getNamingService(properties.getNacosProperties());
|
||||||
|
try {
|
||||||
|
namingService.subscribe(properties.getService(), properties.getGroup(),
|
||||||
|
Arrays.asList(properties.getClusterName()), eventListener);
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
log.error("namingService subscribe failed, properties:{}", properties, e);
|
||||||
|
}
|
||||||
|
|
||||||
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(
|
this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(
|
||||||
this::nacosServicesWatch, this.properties.getWatchDelay());
|
this::nacosServicesWatch, this.properties.getWatchDelay());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private String buildKey() {
|
||||||
|
return String.join(":", properties.getService(), properties.getGroup());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void resetIfNeeded(Instance instance) {
|
||||||
|
if (!properties.getMetadata().equals(instance.getMetadata())) {
|
||||||
|
properties.setMetadata(instance.getMetadata());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Optional<Instance> selectCurrentInstance(List<Instance> instances) {
|
||||||
|
return instances.stream()
|
||||||
|
.filter(instance -> properties.getIp().equals(instance.getIp())
|
||||||
|
&& properties.getPort() == instance.getPort())
|
||||||
|
.findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
if (this.running.compareAndSet(true, false) && this.watchFuture != null) {
|
if (this.running.compareAndSet(true, false)) {
|
||||||
// shutdown current user-thread,
|
if (this.watchFuture != null) {
|
||||||
// then the other daemon-threads will terminate automatic.
|
// shutdown current user-thread,
|
||||||
((ThreadPoolTaskScheduler) this.taskScheduler).shutdown();
|
// then the other daemon-threads will terminate automatic.
|
||||||
|
((ThreadPoolTaskScheduler) this.taskScheduler).shutdown();
|
||||||
|
this.watchFuture.cancel(true);
|
||||||
|
}
|
||||||
|
|
||||||
this.watchFuture.cancel(true);
|
EventListener eventListener = listenerMap.get(buildKey());
|
||||||
|
try {
|
||||||
|
NamingService namingService = nacosServiceManager
|
||||||
|
.getNamingService(properties.getNacosProperties());
|
||||||
|
namingService.unsubscribe(properties.getService(), properties.getGroup(),
|
||||||
|
Arrays.asList(properties.getClusterName()), eventListener);
|
||||||
|
}
|
||||||
|
catch (NacosException e) {
|
||||||
|
log.error("namingService unsubscribe failed, properties:{}", properties,
|
||||||
|
e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -26,7 +26,6 @@ import org.springframework.boot.actuate.health.HealthIndicator;
|
|||||||
* The {@link HealthIndicator} for Nacos Discovery.
|
* The {@link HealthIndicator} for Nacos Discovery.
|
||||||
*
|
*
|
||||||
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
||||||
* @since 2.2.0
|
|
||||||
* @see HealthIndicator
|
* @see HealthIndicator
|
||||||
*/
|
*/
|
||||||
public class NacosDiscoveryHealthIndicator extends AbstractHealthIndicator {
|
public class NacosDiscoveryHealthIndicator extends AbstractHealthIndicator {
|
||||||
|
@ -22,6 +22,7 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
|
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@ -41,9 +42,13 @@ public class NacosDiscoveryEndpoint {
|
|||||||
private static final Logger log = LoggerFactory
|
private static final Logger log = LoggerFactory
|
||||||
.getLogger(NacosDiscoveryEndpoint.class);
|
.getLogger(NacosDiscoveryEndpoint.class);
|
||||||
|
|
||||||
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||||
|
|
||||||
public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
public NacosDiscoveryEndpoint(NacosServiceManager nacosServiceManager,
|
||||||
|
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
|
this.nacosServiceManager = nacosServiceManager;
|
||||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,7 +60,8 @@ public class NacosDiscoveryEndpoint {
|
|||||||
Map<String, Object> result = new HashMap<>();
|
Map<String, Object> result = new HashMap<>();
|
||||||
result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);
|
result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);
|
||||||
|
|
||||||
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
|
NamingService namingService = nacosServiceManager
|
||||||
|
.getNamingService(nacosDiscoveryProperties.getNacosProperties());
|
||||||
List<ServiceInfo> subscribe = Collections.emptyList();
|
List<ServiceInfo> subscribe = Collections.emptyList();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
@ -16,8 +16,11 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.nacos.endpoint;
|
package com.alibaba.cloud.nacos.endpoint;
|
||||||
|
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.cloud.nacos.discovery.actuate.health.NacosDiscoveryHealthIndicator;
|
import com.alibaba.cloud.nacos.discovery.actuate.health.NacosDiscoveryHealthIndicator;
|
||||||
|
|
||||||
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
|
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
|
||||||
@ -44,16 +47,19 @@ public class NacosDiscoveryEndpointAutoConfiguration {
|
|||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
@ConditionalOnEnabledEndpoint
|
@ConditionalOnEnabledEndpoint
|
||||||
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint(
|
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint(
|
||||||
|
NacosServiceManager nacosServiceManager,
|
||||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
return new NacosDiscoveryEndpoint(nacosDiscoveryProperties);
|
return new NacosDiscoveryEndpoint(nacosServiceManager, nacosDiscoveryProperties);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnEnabledHealthIndicator("nacos-discovery")
|
@ConditionalOnEnabledHealthIndicator("nacos-discovery")
|
||||||
public HealthIndicator nacosDiscoveryHealthIndicator(
|
public HealthIndicator nacosDiscoveryHealthIndicator(
|
||||||
|
NacosServiceManager nacosServiceManager,
|
||||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
|
Properties nacosProperties = nacosDiscoveryProperties.getNacosProperties();
|
||||||
return new NacosDiscoveryHealthIndicator(
|
return new NacosDiscoveryHealthIndicator(
|
||||||
nacosDiscoveryProperties.namingServiceInstance());
|
nacosServiceManager.getNamingService(nacosProperties));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,38 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2018 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed 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
|
||||||
|
*
|
||||||
|
* https://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 com.alibaba.cloud.nacos.event;
|
||||||
|
|
||||||
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
|
||||||
|
import org.springframework.context.ApplicationEvent;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author yuhuangbin
|
||||||
|
*/
|
||||||
|
public class NacosDiscoveryInfoChangedEvent extends ApplicationEvent {
|
||||||
|
|
||||||
|
public NacosDiscoveryInfoChangedEvent(
|
||||||
|
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
|
super(nacosDiscoveryProperties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public NacosDiscoveryProperties getSource() {
|
||||||
|
return (NacosDiscoveryProperties) super.getSource();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -16,6 +16,7 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.nacos.registry;
|
package com.alibaba.cloud.nacos.registry;
|
||||||
|
|
||||||
|
import com.alibaba.cloud.nacos.event.NacosDiscoveryInfoChangedEvent;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -23,6 +24,7 @@ import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegis
|
|||||||
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
|
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
|
||||||
import org.springframework.cloud.client.serviceregistry.Registration;
|
import org.springframework.cloud.client.serviceregistry.Registration;
|
||||||
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
@ -102,4 +104,14 @@ public class NacosAutoServiceRegistration
|
|||||||
return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
|
return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@EventListener
|
||||||
|
public void onNacosDiscoveryInfoChangedEvent(NacosDiscoveryInfoChangedEvent event) {
|
||||||
|
restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void restart() {
|
||||||
|
this.stop();
|
||||||
|
this.start();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -17,12 +17,12 @@
|
|||||||
package com.alibaba.cloud.nacos.registry;
|
package com.alibaba.cloud.nacos.registry;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import javax.annotation.PostConstruct;
|
import javax.annotation.PostConstruct;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
|
||||||
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
|
import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
|
||||||
|
|
||||||
import org.springframework.cloud.client.DefaultServiceInstance;
|
import org.springframework.cloud.client.DefaultServiceInstance;
|
||||||
@ -58,12 +58,16 @@ public class NacosRegistration implements Registration, ServiceInstance {
|
|||||||
*/
|
*/
|
||||||
public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path";
|
public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path";
|
||||||
|
|
||||||
|
private List<NacosRegistrationCustomizer> registrationCustomizers;
|
||||||
|
|
||||||
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||||
|
|
||||||
private ApplicationContext context;
|
private ApplicationContext context;
|
||||||
|
|
||||||
public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties,
|
public NacosRegistration(List<NacosRegistrationCustomizer> registrationCustomizers,
|
||||||
|
NacosDiscoveryProperties nacosDiscoveryProperties,
|
||||||
ApplicationContext context) {
|
ApplicationContext context) {
|
||||||
|
this.registrationCustomizers = registrationCustomizers;
|
||||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
@ -105,6 +109,17 @@ public class NacosRegistration implements Registration, ServiceInstance {
|
|||||||
metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT,
|
metadata.put(PreservedMetadataKeys.IP_DELETE_TIMEOUT,
|
||||||
nacosDiscoveryProperties.getIpDeleteTimeout().toString());
|
nacosDiscoveryProperties.getIpDeleteTimeout().toString());
|
||||||
}
|
}
|
||||||
|
customize(registrationCustomizers, this);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void customize(
|
||||||
|
List<NacosRegistrationCustomizer> registrationCustomizers,
|
||||||
|
NacosRegistration registration) {
|
||||||
|
if (registrationCustomizers != null) {
|
||||||
|
for (NacosRegistrationCustomizer customizer : registrationCustomizers) {
|
||||||
|
customizer.customize(registration);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -157,10 +172,6 @@ public class NacosRegistration implements Registration, ServiceInstance {
|
|||||||
return nacosDiscoveryProperties;
|
return nacosDiscoveryProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
public NamingService getNacosNamingService() {
|
|
||||||
return nacosDiscoveryProperties.namingServiceInstance();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "NacosRegistration{" + "nacosDiscoveryProperties="
|
return "NacosRegistration{" + "nacosDiscoveryProperties="
|
||||||
|
@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2018 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed 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
|
||||||
|
*
|
||||||
|
* https://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 com.alibaba.cloud.nacos.registry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author L.cm
|
||||||
|
*/
|
||||||
|
public interface NacosRegistrationCustomizer {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* customize NacosRegistration.
|
||||||
|
* @param registration NacosRegistration
|
||||||
|
*/
|
||||||
|
void customize(NacosRegistration registration);
|
||||||
|
|
||||||
|
}
|
@ -17,13 +17,17 @@
|
|||||||
package com.alibaba.cloud.nacos.registry;
|
package com.alibaba.cloud.nacos.registry;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.cloud.client.serviceregistry.Registration;
|
import org.springframework.cloud.client.serviceregistry.Registration;
|
||||||
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
@ -33,6 +37,7 @@ import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
|
|||||||
/**
|
/**
|
||||||
* @author xiaojing
|
* @author xiaojing
|
||||||
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
|
||||||
|
* @author <a href="mailto:78552423@qq.com">eshun</a>
|
||||||
*/
|
*/
|
||||||
public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
||||||
|
|
||||||
@ -40,11 +45,11 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
|
|
||||||
private final NacosDiscoveryProperties nacosDiscoveryProperties;
|
private final NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||||
|
|
||||||
private final NamingService namingService;
|
@Autowired
|
||||||
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||||
this.namingService = nacosDiscoveryProperties.namingServiceInstance();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -55,6 +60,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
NamingService namingService = namingService();
|
||||||
String serviceId = registration.getServiceId();
|
String serviceId = registration.getServiceId();
|
||||||
String group = nacosDiscoveryProperties.getGroup();
|
String group = nacosDiscoveryProperties.getGroup();
|
||||||
|
|
||||||
@ -84,7 +90,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
|
NamingService namingService = namingService();
|
||||||
String serviceId = registration.getServiceId();
|
String serviceId = registration.getServiceId();
|
||||||
String group = nacosDiscoveryProperties.getGroup();
|
String group = nacosDiscoveryProperties.getGroup();
|
||||||
|
|
||||||
@ -102,7 +108,12 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() {
|
public void close() {
|
||||||
|
try {
|
||||||
|
nacosServiceManager.nacosServiceShutDown();
|
||||||
|
}
|
||||||
|
catch (NacosException e) {
|
||||||
|
log.error("Nacos namingService shutDown failed", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -125,7 +136,8 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
nacosDiscoveryProperties.namingMaintainServiceInstance()
|
Properties nacosProperties = nacosDiscoveryProperties.getNacosProperties();
|
||||||
|
nacosServiceManager.getNamingMaintainService(nacosProperties)
|
||||||
.updateInstance(serviceId, instance);
|
.updateInstance(serviceId, instance);
|
||||||
}
|
}
|
||||||
catch (Exception e) {
|
catch (Exception e) {
|
||||||
@ -139,8 +151,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
|
|
||||||
String serviceName = registration.getServiceId();
|
String serviceName = registration.getServiceId();
|
||||||
try {
|
try {
|
||||||
List<Instance> instances = nacosDiscoveryProperties.namingServiceInstance()
|
List<Instance> instances = namingService().getAllInstances(serviceName);
|
||||||
.getAllInstances(serviceName);
|
|
||||||
for (Instance instance : instances) {
|
for (Instance instance : instances) {
|
||||||
if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp())
|
if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp())
|
||||||
&& instance.getPort() == nacosDiscoveryProperties.getPort()) {
|
&& instance.getPort() == nacosDiscoveryProperties.getPort()) {
|
||||||
@ -160,9 +171,15 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
|||||||
instance.setPort(registration.getPort());
|
instance.setPort(registration.getPort());
|
||||||
instance.setWeight(nacosDiscoveryProperties.getWeight());
|
instance.setWeight(nacosDiscoveryProperties.getWeight());
|
||||||
instance.setClusterName(nacosDiscoveryProperties.getClusterName());
|
instance.setClusterName(nacosDiscoveryProperties.getClusterName());
|
||||||
|
instance.setEnabled(nacosDiscoveryProperties.isInstanceEnabled());
|
||||||
instance.setMetadata(registration.getMetadata());
|
instance.setMetadata(registration.getMetadata());
|
||||||
|
instance.setEphemeral(nacosDiscoveryProperties.isEphemeral());
|
||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private NamingService namingService() {
|
||||||
|
return nacosServiceManager
|
||||||
|
.getNamingService(nacosDiscoveryProperties.getNacosProperties());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -16,10 +16,13 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.nacos.registry;
|
package com.alibaba.cloud.nacos.registry;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration;
|
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
@ -53,9 +56,11 @@ public class NacosServiceRegistryAutoConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
|
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
|
||||||
public NacosRegistration nacosRegistration(
|
public NacosRegistration nacosRegistration(
|
||||||
|
ObjectProvider<List<NacosRegistrationCustomizer>> registrationCustomizers,
|
||||||
NacosDiscoveryProperties nacosDiscoveryProperties,
|
NacosDiscoveryProperties nacosDiscoveryProperties,
|
||||||
ApplicationContext context) {
|
ApplicationContext context) {
|
||||||
return new NacosRegistration(nacosDiscoveryProperties, context);
|
return new NacosRegistration(registrationCustomizers.getIfAvailable(),
|
||||||
|
nacosDiscoveryProperties, context);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
@ -21,6 +21,7 @@ import java.util.Objects;
|
|||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||||
import com.netflix.client.config.IClientConfig;
|
import com.netflix.client.config.IClientConfig;
|
||||||
@ -47,16 +48,20 @@ public class NacosRule extends AbstractLoadBalancerRule {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Server choose(Object key) {
|
public Server choose(Object key) {
|
||||||
try {
|
try {
|
||||||
String clusterName = this.nacosDiscoveryProperties.getClusterName();
|
String clusterName = this.nacosDiscoveryProperties.getClusterName();
|
||||||
|
String group = this.nacosDiscoveryProperties.getGroup();
|
||||||
DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
|
DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
|
||||||
String name = loadBalancer.getName();
|
String name = loadBalancer.getName();
|
||||||
|
|
||||||
NamingService namingService = nacosDiscoveryProperties
|
NamingService namingService = nacosServiceManager
|
||||||
.namingServiceInstance();
|
.getNamingService(nacosDiscoveryProperties.getNacosProperties());
|
||||||
List<Instance> instances = namingService.selectInstances(name, true);
|
List<Instance> instances = namingService.selectInstances(name, group, true);
|
||||||
if (CollectionUtils.isEmpty(instances)) {
|
if (CollectionUtils.isEmpty(instances)) {
|
||||||
LOGGER.warn("no instance in service {}", name);
|
LOGGER.warn("no instance in service {}", name);
|
||||||
return null;
|
return null;
|
||||||
|
@ -1,60 +1,72 @@
|
|||||||
{"properties": [
|
{"properties": [
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.server-addr",
|
"name": "spring.cloud.nacos.server-addr",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.String",
|
||||||
"defaultValue": "localhost:8848",
|
"defaultValue": "localhost:8848",
|
||||||
"description": "nacos server address."
|
"description": "nacos server address."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.server-addr",
|
"name": "spring.cloud.nacos.discovery.server-addr",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.String",
|
||||||
"defaultValue": "${spring.cloud.nacos.server-addr}",
|
"defaultValue": "${spring.cloud.nacos.server-addr}",
|
||||||
"description": "nacos discovery server address."
|
"description": "nacos discovery server address."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.service",
|
"name": "spring.cloud.nacos.discovery.service",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.String",
|
||||||
"defaultValue": "${spring.application.name}",
|
"defaultValue": "${spring.application.name}",
|
||||||
"description": "the service name to register, default value is ${spring.application.name}."
|
"description": "the service name to register, default value is ${spring.application.name}."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.enabled",
|
"name": "spring.cloud.nacos.discovery.enabled",
|
||||||
"type": "java.lang.Boolean",
|
"type": "java.lang.Boolean",
|
||||||
"defaultValue": true,
|
"defaultValue": true,
|
||||||
"description": "enable nacos discovery or not."
|
"description": "enable nacos discovery or not."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.namingLoadCacheAtStart",
|
"name": "spring.cloud.nacos.discovery.instance-enabled",
|
||||||
"type": "java.lang.Boolean",
|
"type": "java.lang.Boolean",
|
||||||
"defaultValue": "false",
|
"defaultValue": true,
|
||||||
"description": "naming load from local cache at application start ."
|
"description": "If instance is enabled to accept request. The default value is true."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.watch.enabled",
|
"name": "spring.cloud.nacos.discovery.ephemeral",
|
||||||
"type": "java.lang.Boolean",
|
"type": "java.lang.Boolean",
|
||||||
"defaultValue": "true",
|
"defaultValue": true,
|
||||||
"description": "enable nacos discovery watch or not ."
|
"description": "If instance is ephemeral.The default value is true."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.username",
|
"name": "spring.cloud.nacos.discovery.namingLoadCacheAtStart",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.Boolean",
|
||||||
"defaultValue": "${spring.cloud.nacos.username}",
|
"defaultValue": "false",
|
||||||
"description": "nacos discovery service's username to authenticate."
|
"description": "naming load from local cache at application start ."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.discovery.password",
|
"name": "spring.cloud.nacos.discovery.watch.enabled",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.Boolean",
|
||||||
"defaultValue": "${spring.cloud.nacos.password}",
|
"defaultValue": "true",
|
||||||
"description": "nacos discovery service's password to authenticate."
|
"description": "enable nacos discovery watch or not ."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.nacos.username",
|
"name": "spring.cloud.nacos.discovery.username",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.String",
|
||||||
"description": "nacos userName to authenticate."
|
"defaultValue": "${spring.cloud.nacos.username}",
|
||||||
},
|
"description": "nacos discovery service's username to authenticate."
|
||||||
{
|
},
|
||||||
"name": "spring.cloud.nacos.password",
|
{
|
||||||
"type": "java.lang.String",
|
"name": "spring.cloud.nacos.discovery.password",
|
||||||
"description": "nacos password to authenticate."
|
"type": "java.lang.String",
|
||||||
}
|
"defaultValue": "${spring.cloud.nacos.password}",
|
||||||
|
"description": "nacos discovery service's password to authenticate."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "spring.cloud.nacos.username",
|
||||||
|
"type": "java.lang.String",
|
||||||
|
"description": "nacos userName to authenticate."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "spring.cloud.nacos.password",
|
||||||
|
"type": "java.lang.String",
|
||||||
|
"description": "nacos password to authenticate."
|
||||||
|
}
|
||||||
]}
|
]}
|
||||||
|
@ -4,6 +4,7 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
|||||||
com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\
|
com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\
|
||||||
com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration,\
|
com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration,\
|
||||||
com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration,\
|
com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration,\
|
||||||
|
com.alibaba.cloud.nacos.NacosServiceAutoConfiguration,\
|
||||||
com.alibaba.cloud.nacos.discovery.configclient.NacosConfigServerAutoConfiguration
|
com.alibaba.cloud.nacos.discovery.configclient.NacosConfigServerAutoConfiguration
|
||||||
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
|
org.springframework.cloud.bootstrap.BootstrapConfiguration=\
|
||||||
com.alibaba.cloud.nacos.discovery.configclient.NacosDiscoveryClientConfigServiceBootstrapConfiguration
|
com.alibaba.cloud.nacos.discovery.configclient.NacosDiscoveryClientConfigServiceBootstrapConfiguration
|
||||||
|
@ -22,6 +22,7 @@ import java.util.LinkedList;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.nacos.api.exception.NacosException;
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||||
@ -60,16 +61,19 @@ public class NacosServiceDiscoveryTest {
|
|||||||
|
|
||||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||||
NacosDiscoveryProperties.class);
|
NacosDiscoveryProperties.class);
|
||||||
|
NacosServiceManager nacosServiceManager = mock(NacosServiceManager.class);
|
||||||
|
|
||||||
NamingService namingService = mock(NamingService.class);
|
NamingService namingService = mock(NamingService.class);
|
||||||
|
|
||||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
when(nacosServiceManager
|
||||||
|
.getNamingService(nacosDiscoveryProperties.getNacosProperties()))
|
||||||
|
.thenReturn(namingService);
|
||||||
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
||||||
when(namingService.selectInstances(eq(serviceName), eq("DEFAULT"), eq(true)))
|
when(namingService.selectInstances(eq(serviceName), eq("DEFAULT"), eq(true)))
|
||||||
.thenReturn(instances);
|
.thenReturn(instances);
|
||||||
|
|
||||||
NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery(
|
NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery(
|
||||||
nacosDiscoveryProperties);
|
nacosDiscoveryProperties, nacosServiceManager);
|
||||||
|
|
||||||
List<ServiceInstance> serviceInstances = serviceDiscovery
|
List<ServiceInstance> serviceInstances = serviceDiscovery
|
||||||
.getInstances(serviceName);
|
.getInstances(serviceName);
|
||||||
@ -99,16 +103,19 @@ public class NacosServiceDiscoveryTest {
|
|||||||
|
|
||||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||||
NacosDiscoveryProperties.class);
|
NacosDiscoveryProperties.class);
|
||||||
|
NacosServiceManager nacosServiceManager = mock(NacosServiceManager.class);
|
||||||
|
|
||||||
NamingService namingService = mock(NamingService.class);
|
NamingService namingService = mock(NamingService.class);
|
||||||
|
|
||||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
when(nacosServiceManager
|
||||||
|
.getNamingService(nacosDiscoveryProperties.getNacosProperties()))
|
||||||
|
.thenReturn(namingService);
|
||||||
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
||||||
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),
|
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),
|
||||||
eq("DEFAULT"))).thenReturn(nacosServices);
|
eq("DEFAULT"))).thenReturn(nacosServices);
|
||||||
|
|
||||||
NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery(
|
NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery(
|
||||||
nacosDiscoveryProperties);
|
nacosDiscoveryProperties, nacosServiceManager);
|
||||||
|
|
||||||
List<String> services = serviceDiscovery.getServices();
|
List<String> services = serviceDiscovery.getServices();
|
||||||
|
|
||||||
|
@ -328,4 +328,9 @@ public class MockNamingService implements NamingService {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void shutDown() throws NacosException {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -22,6 +22,7 @@ import java.util.Map;
|
|||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration;
|
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration;
|
||||||
import com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpoint;
|
import com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpoint;
|
||||||
import com.alibaba.nacos.api.NacosFactory;
|
import com.alibaba.nacos.api.NacosFactory;
|
||||||
@ -85,6 +86,9 @@ public class NacosAutoServiceRegistrationTests {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private NacosDiscoveryProperties properties;
|
private NacosDiscoveryProperties properties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private InetUtils inetUtils;
|
private InetUtils inetUtils;
|
||||||
|
|
||||||
@ -206,7 +210,7 @@ public class NacosAutoServiceRegistrationTests {
|
|||||||
|
|
||||||
private void checkoutEndpoint() throws Exception {
|
private void checkoutEndpoint() throws Exception {
|
||||||
NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint(
|
NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint(
|
||||||
properties);
|
nacosServiceManager, properties);
|
||||||
Map<String, Object> map = nacosDiscoveryEndpoint.nacosDiscovery();
|
Map<String, Object> map = nacosDiscoveryEndpoint.nacosDiscovery();
|
||||||
|
|
||||||
assertThat(properties).isEqualTo(map.get("NacosDiscoveryProperties"));
|
assertThat(properties).isEqualTo(map.get("NacosDiscoveryProperties"));
|
||||||
|
@ -46,6 +46,7 @@ public class SeataHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy
|
|||||||
|
|
||||||
private final Logger logger = LoggerFactory
|
private final Logger logger = LoggerFactory
|
||||||
.getLogger(SeataHystrixConcurrencyStrategy.class);
|
.getLogger(SeataHystrixConcurrencyStrategy.class);
|
||||||
|
|
||||||
private HystrixConcurrencyStrategy delegate;
|
private HystrixConcurrencyStrategy delegate;
|
||||||
|
|
||||||
public SeataHystrixConcurrencyStrategy() {
|
public SeataHystrixConcurrencyStrategy() {
|
||||||
@ -78,8 +79,8 @@ public class SeataHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
|
private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
|
||||||
HystrixMetricsPublisher metricsPublisher,
|
HystrixMetricsPublisher metricsPublisher,
|
||||||
HystrixPropertiesStrategy propertiesStrategy) {
|
HystrixPropertiesStrategy propertiesStrategy) {
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("Current Hystrix plugins configuration is ["
|
logger.debug("Current Hystrix plugins configuration is ["
|
||||||
+ "concurrencyStrategy [" + this.delegate + "]," + "eventNotifier ["
|
+ "concurrencyStrategy [" + this.delegate + "]," + "eventNotifier ["
|
||||||
@ -91,17 +92,17 @@ public class SeataHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
|
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
|
||||||
HystrixProperty<Integer> corePoolSize,
|
HystrixProperty<Integer> corePoolSize,
|
||||||
HystrixProperty<Integer> maximumPoolSize,
|
HystrixProperty<Integer> maximumPoolSize,
|
||||||
HystrixProperty<Integer> keepAliveTime, TimeUnit unit,
|
HystrixProperty<Integer> keepAliveTime, TimeUnit unit,
|
||||||
BlockingQueue<Runnable> workQueue) {
|
BlockingQueue<Runnable> workQueue) {
|
||||||
return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize,
|
return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize,
|
||||||
keepAliveTime, unit, workQueue);
|
keepAliveTime, unit, workQueue);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
|
public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
|
||||||
HystrixThreadPoolProperties threadPoolProperties) {
|
HystrixThreadPoolProperties threadPoolProperties) {
|
||||||
return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
|
return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,11 +19,11 @@ package com.alibaba.cloud.seata.web;
|
|||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
|
||||||
|
import io.seata.common.util.StringUtils;
|
||||||
import io.seata.core.context.RootContext;
|
import io.seata.core.context.RootContext;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import org.springframework.util.StringUtils;
|
|
||||||
import org.springframework.web.servlet.HandlerInterceptor;
|
import org.springframework.web.servlet.HandlerInterceptor;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -50,7 +50,7 @@ public class SeataHandlerInterceptor implements HandlerInterceptor {
|
|||||||
log.debug("xid in RootContext {} xid in RpcContext {}", xid, rpcXid);
|
log.debug("xid in RootContext {} xid in RpcContext {}", xid, rpcXid);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (xid == null && rpcXid != null) {
|
if (StringUtils.isBlank(xid) && rpcXid != null) {
|
||||||
RootContext.bind(rpcXid);
|
RootContext.bind(rpcXid);
|
||||||
if (log.isDebugEnabled()) {
|
if (log.isDebugEnabled()) {
|
||||||
log.debug("bind {} to RootContext", rpcXid);
|
log.debug("bind {} to RootContext", rpcXid);
|
||||||
@ -62,22 +62,23 @@ public class SeataHandlerInterceptor implements HandlerInterceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
|
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
|
||||||
Object handler, Exception e) {
|
Object handler, Exception e) {
|
||||||
|
if (StringUtils.isNotBlank(RootContext.getXID())) {
|
||||||
|
String rpcXid = request.getHeader(RootContext.KEY_XID);
|
||||||
|
|
||||||
String rpcXid = request.getHeader(RootContext.KEY_XID);
|
if (StringUtils.isEmpty(rpcXid)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (StringUtils.isEmpty(rpcXid)) {
|
String unbindXid = RootContext.unbind();
|
||||||
return;
|
if (log.isDebugEnabled()) {
|
||||||
}
|
log.debug("unbind {} from RootContext", unbindXid);
|
||||||
|
}
|
||||||
String unbindXid = RootContext.unbind();
|
if (!rpcXid.equalsIgnoreCase(unbindXid)) {
|
||||||
if (log.isDebugEnabled()) {
|
log.warn("xid in change during RPC from {} to {}", rpcXid, unbindXid);
|
||||||
log.debug("unbind {} from RootContext", unbindXid);
|
if (unbindXid != null) {
|
||||||
}
|
RootContext.bind(unbindXid);
|
||||||
if (!rpcXid.equalsIgnoreCase(unbindXid)) {
|
log.warn("bind {} back to RootContext", unbindXid);
|
||||||
log.warn("xid in change during RPC from {} to {}", rpcXid, unbindXid);
|
}
|
||||||
if (unbindXid != null) {
|
|
||||||
RootContext.bind(unbindXid);
|
|
||||||
log.warn("bind {} back to RootContext", unbindXid);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -148,6 +148,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||||
<artifactId>jackson-dataformat-xml</artifactId>
|
<artifactId>jackson-dataformat-xml</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -102,6 +102,20 @@ public class SentinelProperties {
|
|||||||
*/
|
*/
|
||||||
private Boolean httpMethodSpecify = false;
|
private Boolean httpMethodSpecify = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Specify whether unify web context(i.e. use the default context name), and is true
|
||||||
|
* by default.
|
||||||
|
*/
|
||||||
|
private Boolean webContextUnify = true;
|
||||||
|
|
||||||
|
public Boolean getWebContextUnify() {
|
||||||
|
return webContextUnify;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setWebContextUnify(Boolean webContextUnify) {
|
||||||
|
this.webContextUnify = webContextUnify;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean isEager() {
|
public boolean isEager() {
|
||||||
return eager;
|
return eager;
|
||||||
}
|
}
|
||||||
|
@ -94,6 +94,7 @@ public class SentinelWebAutoConfiguration implements WebMvcConfigurer {
|
|||||||
public SentinelWebMvcConfig sentinelWebMvcConfig() {
|
public SentinelWebMvcConfig sentinelWebMvcConfig() {
|
||||||
SentinelWebMvcConfig sentinelWebMvcConfig = new SentinelWebMvcConfig();
|
SentinelWebMvcConfig sentinelWebMvcConfig = new SentinelWebMvcConfig();
|
||||||
sentinelWebMvcConfig.setHttpMethodSpecify(properties.getHttpMethodSpecify());
|
sentinelWebMvcConfig.setHttpMethodSpecify(properties.getHttpMethodSpecify());
|
||||||
|
sentinelWebMvcConfig.setWebContextUnify(properties.getWebContextUnify());
|
||||||
|
|
||||||
if (blockExceptionHandlerOptional.isPresent()) {
|
if (blockExceptionHandlerOptional.isPresent()) {
|
||||||
blockExceptionHandlerOptional
|
blockExceptionHandlerOptional
|
||||||
|
@ -31,7 +31,6 @@ import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
|||||||
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
|
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
|
||||||
import com.alibaba.csp.sentinel.slots.system.SystemRule;
|
import com.alibaba.csp.sentinel.slots.system.SystemRule;
|
||||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||||
import com.alibaba.csp.sentinel.util.AppNameUtil;
|
|
||||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||||
@ -79,9 +78,9 @@ public class SentinelAutoConfiguration {
|
|||||||
System.setProperty(LogBase.LOG_NAME_USE_PID,
|
System.setProperty(LogBase.LOG_NAME_USE_PID,
|
||||||
String.valueOf(properties.getLog().isSwitchPid()));
|
String.valueOf(properties.getLog().isSwitchPid()));
|
||||||
}
|
}
|
||||||
if (StringUtils.isEmpty(System.getProperty(AppNameUtil.APP_NAME))
|
if (StringUtils.isEmpty(System.getProperty(SentinelConfig.APP_NAME_PROP_KEY))
|
||||||
&& StringUtils.hasText(projectName)) {
|
&& StringUtils.hasText(projectName)) {
|
||||||
System.setProperty(AppNameUtil.APP_NAME, projectName);
|
System.setProperty(SentinelConfig.APP_NAME_PROP_KEY, projectName);
|
||||||
}
|
}
|
||||||
if (StringUtils.isEmpty(System.getProperty(TransportConfig.SERVER_PORT))
|
if (StringUtils.isEmpty(System.getProperty(TransportConfig.SERVER_PORT))
|
||||||
&& StringUtils.hasText(properties.getTransport().getPort())) {
|
&& StringUtils.hasText(properties.getTransport().getPort())) {
|
||||||
|
@ -61,7 +61,7 @@ public class SentinelEndpoint {
|
|||||||
result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
|
result.put("metricsFileSize", SentinelConfig.singleMetricFileSize());
|
||||||
result.put("metricsFileCharset", SentinelConfig.charset());
|
result.put("metricsFileCharset", SentinelConfig.charset());
|
||||||
result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
|
result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount());
|
||||||
result.put("consoleServer", TransportConfig.getConsoleServer());
|
result.put("consoleServer", TransportConfig.getConsoleServerList());
|
||||||
result.put("clientIp", TransportConfig.getHeartbeatClientIp());
|
result.put("clientIp", TransportConfig.getHeartbeatClientIp());
|
||||||
result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
|
result.put("heartbeatIntervalMs", TransportConfig.getHeartbeatIntervalMs());
|
||||||
result.put("clientPort", TransportConfig.getPort());
|
result.put("clientPort", TransportConfig.getPort());
|
||||||
|
@ -17,6 +17,7 @@
|
|||||||
package com.alibaba.cloud.sentinel.endpoint;
|
package com.alibaba.cloud.sentinel.endpoint;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import com.alibaba.cloud.sentinel.SentinelProperties;
|
import com.alibaba.cloud.sentinel.SentinelProperties;
|
||||||
@ -24,13 +25,14 @@ import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
|
|||||||
import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider;
|
import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider;
|
||||||
import com.alibaba.csp.sentinel.transport.HeartbeatSender;
|
import com.alibaba.csp.sentinel.transport.HeartbeatSender;
|
||||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||||
|
import com.alibaba.csp.sentinel.util.function.Tuple2;
|
||||||
|
|
||||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||||
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
|
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
|
||||||
import org.springframework.boot.actuate.health.Health;
|
import org.springframework.boot.actuate.health.Health;
|
||||||
import org.springframework.boot.actuate.health.HealthIndicator;
|
import org.springframework.boot.actuate.health.HealthIndicator;
|
||||||
import org.springframework.boot.actuate.health.Status;
|
import org.springframework.boot.actuate.health.Status;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A {@link HealthIndicator} for Sentinel, which checks the status of Sentinel Dashboard
|
* A {@link HealthIndicator} for Sentinel, which checks the status of Sentinel Dashboard
|
||||||
@ -61,7 +63,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
|
|||||||
private SentinelProperties sentinelProperties;
|
private SentinelProperties sentinelProperties;
|
||||||
|
|
||||||
public SentinelHealthIndicator(DefaultListableBeanFactory beanFactory,
|
public SentinelHealthIndicator(DefaultListableBeanFactory beanFactory,
|
||||||
SentinelProperties sentinelProperties) {
|
SentinelProperties sentinelProperties) {
|
||||||
this.beanFactory = beanFactory;
|
this.beanFactory = beanFactory;
|
||||||
this.sentinelProperties = sentinelProperties;
|
this.sentinelProperties = sentinelProperties;
|
||||||
}
|
}
|
||||||
@ -74,7 +76,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
|
|||||||
// detail
|
// detail
|
||||||
if (!sentinelProperties.isEnabled()) {
|
if (!sentinelProperties.isEnabled()) {
|
||||||
detailMap.put("enabled", false);
|
detailMap.put("enabled", false);
|
||||||
withDetails(builder.up(), detailMap);
|
builder.up().withDetails(detailMap);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -82,8 +84,9 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
|
|||||||
|
|
||||||
// Check health of Dashboard
|
// Check health of Dashboard
|
||||||
boolean dashboardUp = true;
|
boolean dashboardUp = true;
|
||||||
String consoleServer = TransportConfig.getConsoleServer();
|
List<Tuple2<String, Integer>> consoleServerList = TransportConfig
|
||||||
if (StringUtils.isEmpty(consoleServer)) {
|
.getConsoleServerList();
|
||||||
|
if (CollectionUtils.isEmpty(consoleServerList)) {
|
||||||
// If Dashboard isn't configured, it's OK and mark the status of Dashboard
|
// If Dashboard isn't configured, it's OK and mark the status of Dashboard
|
||||||
// with UNKNOWN.
|
// with UNKNOWN.
|
||||||
detailMap.put("dashboard",
|
detailMap.put("dashboard",
|
||||||
@ -101,8 +104,10 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
|
|||||||
else {
|
else {
|
||||||
// If failed to send heartbeat message, means that the Dashboard is DOWN
|
// If failed to send heartbeat message, means that the Dashboard is DOWN
|
||||||
dashboardUp = false;
|
dashboardUp = false;
|
||||||
detailMap.put("dashboard", new Status(Status.DOWN.getCode(),
|
detailMap.put("dashboard",
|
||||||
consoleServer + " can't be connected"));
|
new Status(Status.UNKNOWN.getCode(), String.format(
|
||||||
|
"the dashboard servers [%s] one of them can't be connected",
|
||||||
|
consoleServerList)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,22 +138,17 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator {
|
|||||||
// DOWN
|
// DOWN
|
||||||
dataSourceUp = false;
|
dataSourceUp = false;
|
||||||
dataSourceDetailMap.put(dataSourceBeanName,
|
dataSourceDetailMap.put(dataSourceBeanName,
|
||||||
new Status(Status.DOWN.getCode(), e.getMessage()));
|
new Status(Status.UNKNOWN.getCode(), e.getMessage()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If Dashboard and DataSource are both OK, the health status is UP
|
// If Dashboard and DataSource are both OK, the health status is UP
|
||||||
if (dashboardUp && dataSourceUp) {
|
if (dashboardUp && dataSourceUp) {
|
||||||
withDetails(builder.up(), detailMap);
|
builder.up().withDetails(detailMap);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
withDetails(builder.down(), detailMap);
|
builder.unknown().withDetails(detailMap);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void withDetails(Health.Builder builder, Map<String, Object> detailMap) {
|
|
||||||
for (String key : detailMap.keySet()) {
|
|
||||||
builder.withDetail(key, detailMap.get(key));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,12 @@
|
|||||||
"description": "earlier initialize heart-beat when the spring container starts when the transport dependency is on classpath, the configuration is effective."
|
"description": "earlier initialize heart-beat when the spring container starts when the transport dependency is on classpath, the configuration is effective."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "spring.cloud.sentinel.transport.port",
|
"name": "spring.cloud.sentinel.web-context-unify",
|
||||||
|
"type": "java.lang.Boolean",
|
||||||
|
"defaultValue": true,
|
||||||
|
"description": "Specify whether unify web context(i.e. use the default context name), and is true by default."
|
||||||
|
},
|
||||||
|
{ "name": "spring.cloud.sentinel.transport.port",
|
||||||
"type": "java.lang.String",
|
"type": "java.lang.String",
|
||||||
"defaultValue": "8719",
|
"defaultValue": "8719",
|
||||||
"description": "sentinel api port."
|
"description": "sentinel api port."
|
||||||
|
@ -28,11 +28,10 @@ import com.alibaba.csp.sentinel.config.SentinelConfig;
|
|||||||
import com.alibaba.csp.sentinel.log.LogBase;
|
import com.alibaba.csp.sentinel.log.LogBase;
|
||||||
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
||||||
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
|
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
|
||||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
|
|
||||||
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
|
|
||||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
||||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
||||||
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
|
||||||
|
import com.alibaba.csp.sentinel.util.function.Tuple2;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
@ -74,7 +73,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
|||||||
"spring.cloud.sentinel.flow.coldFactor=3",
|
"spring.cloud.sentinel.flow.coldFactor=3",
|
||||||
"spring.cloud.sentinel.eager=true",
|
"spring.cloud.sentinel.eager=true",
|
||||||
"spring.cloud.sentinel.log.switchPid=true",
|
"spring.cloud.sentinel.log.switchPid=true",
|
||||||
"spring.cloud.sentinel.transport.dashboard=http://localhost:8080",
|
"spring.cloud.sentinel.transport.dashboard=http://localhost:8080,http://localhost:8081",
|
||||||
"spring.cloud.sentinel.transport.port=9999",
|
"spring.cloud.sentinel.transport.port=9999",
|
||||||
"spring.cloud.sentinel.transport.clientIp=1.1.1.1",
|
"spring.cloud.sentinel.transport.clientIp=1.1.1.1",
|
||||||
"spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, webEnvironment = RANDOM_PORT)
|
"spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, webEnvironment = RANDOM_PORT)
|
||||||
@ -115,13 +114,6 @@ public class SentinelAutoConfigurationTests {
|
|||||||
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
|
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
|
||||||
rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
|
rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
|
||||||
FlowRuleManager.loadRules(Arrays.asList(rule));
|
FlowRuleManager.loadRules(Arrays.asList(rule));
|
||||||
|
|
||||||
DegradeRule degradeRule = new DegradeRule();
|
|
||||||
degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
|
|
||||||
degradeRule.setResource("GET:" + degradeUrl);
|
|
||||||
degradeRule.setCount(0);
|
|
||||||
degradeRule.setTimeWindow(60);
|
|
||||||
DegradeRuleManager.loadRules(Arrays.asList(degradeRule));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -142,7 +134,9 @@ public class SentinelAutoConfigurationTests {
|
|||||||
Map<String, Object> map = sentinelEndpoint.invoke();
|
Map<String, Object> map = sentinelEndpoint.invoke();
|
||||||
|
|
||||||
assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE);
|
assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE);
|
||||||
assertThat(map.get("consoleServer")).isEqualTo("http://localhost:8080");
|
assertThat(map.get("consoleServer").toString()).isEqualTo(
|
||||||
|
Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081))
|
||||||
|
.toString());
|
||||||
assertThat(map.get("clientPort")).isEqualTo("9999");
|
assertThat(map.get("clientPort")).isEqualTo("9999");
|
||||||
assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L);
|
assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L);
|
||||||
assertThat(map.get("clientIp")).isEqualTo("1.1.1.1");
|
assertThat(map.get("clientIp")).isEqualTo("1.1.1.1");
|
||||||
@ -174,7 +168,7 @@ public class SentinelAutoConfigurationTests {
|
|||||||
private void checkSentinelTransport() {
|
private void checkSentinelTransport() {
|
||||||
assertThat(sentinelProperties.getTransport().getPort()).isEqualTo("9999");
|
assertThat(sentinelProperties.getTransport().getPort()).isEqualTo("9999");
|
||||||
assertThat(sentinelProperties.getTransport().getDashboard())
|
assertThat(sentinelProperties.getTransport().getDashboard())
|
||||||
.isEqualTo("http://localhost:8080");
|
.isEqualTo("http://localhost:8080,http://localhost:8081");
|
||||||
assertThat(sentinelProperties.getTransport().getClientIp()).isEqualTo("1.1.1.1");
|
assertThat(sentinelProperties.getTransport().getClientIp()).isEqualTo("1.1.1.1");
|
||||||
assertThat(sentinelProperties.getTransport().getHeartbeatIntervalMs())
|
assertThat(sentinelProperties.getTransport().getHeartbeatIntervalMs())
|
||||||
.isEqualTo("20000");
|
.isEqualTo("20000");
|
||||||
@ -191,7 +185,9 @@ public class SentinelAutoConfigurationTests {
|
|||||||
@Test
|
@Test
|
||||||
public void testSentinelSystemProperties() {
|
public void testSentinelSystemProperties() {
|
||||||
assertThat(LogBase.isLogNameUsePid()).isEqualTo(true);
|
assertThat(LogBase.isLogNameUsePid()).isEqualTo(true);
|
||||||
assertThat(TransportConfig.getConsoleServer()).isEqualTo("http://localhost:8080");
|
assertThat(TransportConfig.getConsoleServerList().toString()).isEqualTo(
|
||||||
|
Arrays.asList(Tuple2.of("localhost", 8080), Tuple2.of("localhost", 8081))
|
||||||
|
.toString());
|
||||||
assertThat(TransportConfig.getPort()).isEqualTo("9999");
|
assertThat(TransportConfig.getPort()).isEqualTo("9999");
|
||||||
assertThat(TransportConfig.getHeartbeatIntervalMs().longValue())
|
assertThat(TransportConfig.getHeartbeatIntervalMs().longValue())
|
||||||
.isEqualTo(20000L);
|
.isEqualTo(20000L);
|
||||||
@ -203,7 +199,7 @@ public class SentinelAutoConfigurationTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testFlowRestTemplate() {
|
public void testRestTemplateBlockHandler() {
|
||||||
|
|
||||||
assertThat(restTemplate.getInterceptors().size()).isEqualTo(2);
|
assertThat(restTemplate.getInterceptors().size()).isEqualTo(2);
|
||||||
assertThat(restTemplateWithBlockClass.getInterceptors().size()).isEqualTo(1);
|
assertThat(restTemplateWithBlockClass.getInterceptors().size()).isEqualTo(1);
|
||||||
@ -231,15 +227,6 @@ public class SentinelAutoConfigurationTests {
|
|||||||
}).isInstanceOf(RestClientException.class);
|
}).isInstanceOf(RestClientException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testFallbackRestTemplate() {
|
|
||||||
ResponseEntity responseEntity = restTemplateWithFallbackClass
|
|
||||||
.getForEntity(degradeUrl, String.class);
|
|
||||||
|
|
||||||
assertThat(responseEntity.getBody()).isEqualTo("Oops fallback");
|
|
||||||
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
static class SentinelTestConfiguration {
|
static class SentinelTestConfiguration {
|
||||||
|
|
||||||
|
@ -109,9 +109,9 @@ public class SentinelHealthIndicatorTests {
|
|||||||
|
|
||||||
Health health = sentinelHealthIndicator.health();
|
Health health = sentinelHealthIndicator.health();
|
||||||
|
|
||||||
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
|
assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN);
|
||||||
assertThat(health.getDetails().get("dashboard")).isEqualTo(
|
assertThat(health.getDetails().get("dashboard")).isEqualTo(new Status(
|
||||||
new Status(Status.DOWN.getCode(), "localhost:8080 can't be connected"));
|
Status.UNKNOWN.getCode(), "localhost:8080 can't be connected"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -163,13 +163,13 @@ public class SentinelHealthIndicatorTests {
|
|||||||
|
|
||||||
Health health = sentinelHealthIndicator.health();
|
Health health = sentinelHealthIndicator.health();
|
||||||
|
|
||||||
assertThat(health.getStatus()).isEqualTo(Status.DOWN);
|
assertThat(health.getStatus()).isEqualTo(Status.UNKNOWN);
|
||||||
Map<String, Status> dataSourceDetailMap = (Map<String, Status>) health
|
Map<String, Status> dataSourceDetailMap = (Map<String, Status>) health
|
||||||
.getDetails().get("dataSource");
|
.getDetails().get("dataSource");
|
||||||
assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource"))
|
assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource"))
|
||||||
.isEqualTo(Status.UP);
|
.isEqualTo(Status.UP);
|
||||||
assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource"))
|
assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource"))
|
||||||
.isEqualTo(new Status(Status.DOWN.getCode(), "fileDataSource2 error"));
|
.isEqualTo(new Status(Status.UNKNOWN.getCode(), "fileDataSource2 error"));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,6 @@ package com.alibaba.cloud.sidecar;
|
|||||||
|
|
||||||
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
|
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.env.ConfigurableEnvironment;
|
import org.springframework.core.env.ConfigurableEnvironment;
|
||||||
@ -28,7 +27,6 @@ import org.springframework.web.client.RestTemplate;
|
|||||||
* @author www.itmuch.com
|
* @author www.itmuch.com
|
||||||
*/
|
*/
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableConfigurationProperties(SidecarProperties.class)
|
|
||||||
public class SidecarAutoConfiguration {
|
public class SidecarAutoConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
@ -16,6 +16,9 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.sidecar;
|
package com.alibaba.cloud.sidecar;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@ -28,11 +31,14 @@ import org.springframework.core.env.ConfigurableEnvironment;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @author www.itmuch.com
|
* @author www.itmuch.com
|
||||||
|
* @author yuhuangbin
|
||||||
*/
|
*/
|
||||||
public class SidecarHealthChecker {
|
public class SidecarHealthChecker {
|
||||||
|
|
||||||
private static final Logger log = LoggerFactory.getLogger(SidecarHealthChecker.class);
|
private static final Logger log = LoggerFactory.getLogger(SidecarHealthChecker.class);
|
||||||
|
|
||||||
|
private final Map<String, SidecarInstanceCache> sidecarInstanceCacheMap = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
private final SidecarDiscoveryClient sidecarDiscoveryClient;
|
private final SidecarDiscoveryClient sidecarDiscoveryClient;
|
||||||
|
|
||||||
private final HealthIndicator healthIndicator;
|
private final HealthIndicator healthIndicator;
|
||||||
@ -52,26 +58,59 @@ public class SidecarHealthChecker {
|
|||||||
|
|
||||||
public void check() {
|
public void check() {
|
||||||
Schedulers.single().schedulePeriodically(() -> {
|
Schedulers.single().schedulePeriodically(() -> {
|
||||||
|
String applicationName = environment.getProperty("spring.application.name");
|
||||||
String ip = sidecarProperties.getIp();
|
String ip = sidecarProperties.getIp();
|
||||||
Integer port = sidecarProperties.getPort();
|
Integer port = sidecarProperties.getPort();
|
||||||
|
|
||||||
Status status = healthIndicator.health().getStatus();
|
Status status = healthIndicator.health().getStatus();
|
||||||
String applicationName = environment.getProperty("spring.application.name");
|
|
||||||
|
|
||||||
|
instanceCache(applicationName, ip, port, status);
|
||||||
if (status.equals(Status.UP)) {
|
if (status.equals(Status.UP)) {
|
||||||
this.sidecarDiscoveryClient.registerInstance(applicationName, ip, port);
|
if (needRegister(applicationName, ip, port, status)) {
|
||||||
log.debug(
|
this.sidecarDiscoveryClient.registerInstance(applicationName, ip,
|
||||||
"Health check success. register this instance. applicationName = {}, ip = {}, port = {}, status = {}",
|
port);
|
||||||
applicationName, ip, port, status);
|
log.info(
|
||||||
|
"Polyglot service changed and Health check success. register the new instance. applicationName = {}, ip = {}, port = {}, status = {}",
|
||||||
|
applicationName, ip, port, status);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
log.warn(
|
log.warn(
|
||||||
"Health check failed. unregister this instance. applicationName = {}, ip = {}, port = {}, status = {}",
|
"Health check failed. unregister this instance. applicationName = {}, ip = {}, port = {}, status = {}",
|
||||||
applicationName, ip, port, status);
|
applicationName, ip, port, status);
|
||||||
this.sidecarDiscoveryClient.deregisterInstance(applicationName, ip, port);
|
this.sidecarDiscoveryClient.deregisterInstance(applicationName, ip, port);
|
||||||
|
sidecarInstanceCacheMap.put(applicationName,
|
||||||
|
buildCache(ip, port, status));
|
||||||
}
|
}
|
||||||
|
|
||||||
}, 0, sidecarProperties.getHealthCheckInterval(), TimeUnit.MILLISECONDS);
|
}, 0, sidecarProperties.getHealthCheckInterval(), TimeUnit.MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void instanceCache(String applicationName, String ip, Integer port,
|
||||||
|
Status status) {
|
||||||
|
sidecarInstanceCacheMap.putIfAbsent(applicationName,
|
||||||
|
buildCache(ip, port, status));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean needRegister(String applicationName, String ip, Integer port,
|
||||||
|
Status status) {
|
||||||
|
SidecarInstanceCache cacheRecord = sidecarInstanceCacheMap.get(applicationName);
|
||||||
|
SidecarInstanceCache cache = buildCache(ip, port, status);
|
||||||
|
|
||||||
|
if (!Objects.equals(cache, cacheRecord)) {
|
||||||
|
// modify the cache info
|
||||||
|
sidecarInstanceCacheMap.put(applicationName, cache);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SidecarInstanceCache buildCache(String ip, Integer port, Status status) {
|
||||||
|
SidecarInstanceCache cache = new SidecarInstanceCache();
|
||||||
|
cache.setIp(ip);
|
||||||
|
cache.setPort(port);
|
||||||
|
cache.setStatus(status);
|
||||||
|
return cache;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,76 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2013-2018 the original author or authors.
|
||||||
|
*
|
||||||
|
* Licensed 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
|
||||||
|
*
|
||||||
|
* https://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 com.alibaba.cloud.sidecar;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import org.springframework.boot.actuate.health.Status;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author yuhuangbin
|
||||||
|
*/
|
||||||
|
public class SidecarInstanceCache {
|
||||||
|
|
||||||
|
private String ip;
|
||||||
|
|
||||||
|
private Integer port;
|
||||||
|
|
||||||
|
private Status status;
|
||||||
|
|
||||||
|
public String getIp() {
|
||||||
|
return ip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIp(String ip) {
|
||||||
|
this.ip = ip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getPort() {
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPort(Integer port) {
|
||||||
|
this.port = port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Status getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(Status status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
SidecarInstanceCache that = (SidecarInstanceCache) o;
|
||||||
|
return Objects.equals(ip, that.ip) && Objects.equals(port, that.port)
|
||||||
|
&& Objects.equals(status, that.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(ip, port, status);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -17,6 +17,7 @@
|
|||||||
package com.alibaba.cloud.sidecar.nacos;
|
package com.alibaba.cloud.sidecar.nacos;
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration;
|
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration;
|
||||||
import com.alibaba.cloud.sidecar.SidecarAutoConfiguration;
|
import com.alibaba.cloud.sidecar.SidecarAutoConfiguration;
|
||||||
import com.alibaba.cloud.sidecar.SidecarDiscoveryClient;
|
import com.alibaba.cloud.sidecar.SidecarDiscoveryClient;
|
||||||
@ -25,6 +26,7 @@ import com.alibaba.cloud.sidecar.SidecarProperties;
|
|||||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
@ -35,6 +37,7 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
@AutoConfigureBefore({ NacosDiscoveryAutoConfiguration.class,
|
@AutoConfigureBefore({ NacosDiscoveryAutoConfiguration.class,
|
||||||
SidecarAutoConfiguration.class })
|
SidecarAutoConfiguration.class })
|
||||||
@ConditionalOnClass(NacosDiscoveryProperties.class)
|
@ConditionalOnClass(NacosDiscoveryProperties.class)
|
||||||
|
@EnableConfigurationProperties(SidecarProperties.class)
|
||||||
public class SidecarNacosAutoConfiguration {
|
public class SidecarNacosAutoConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@ -47,8 +50,10 @@ public class SidecarNacosAutoConfiguration {
|
|||||||
@Bean
|
@Bean
|
||||||
@ConditionalOnMissingBean
|
@ConditionalOnMissingBean
|
||||||
public SidecarDiscoveryClient sidecarDiscoveryClient(
|
public SidecarDiscoveryClient sidecarDiscoveryClient(
|
||||||
|
NacosServiceManager nacosServiceManager,
|
||||||
SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties) {
|
SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties) {
|
||||||
return new SidecarNacosDiscoveryClient(sidecarNacosDiscoveryProperties);
|
return new SidecarNacosDiscoveryClient(nacosServiceManager,
|
||||||
|
sidecarNacosDiscoveryProperties);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -16,8 +16,10 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.sidecar.nacos;
|
package com.alibaba.cloud.sidecar.nacos;
|
||||||
|
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.cloud.sidecar.SidecarDiscoveryClient;
|
import com.alibaba.cloud.sidecar.SidecarDiscoveryClient;
|
||||||
import com.alibaba.nacos.api.exception.NacosException;
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
@ -29,9 +31,11 @@ public class SidecarNacosDiscoveryClient implements SidecarDiscoveryClient {
|
|||||||
private static final Logger log = LoggerFactory
|
private static final Logger log = LoggerFactory
|
||||||
.getLogger(SidecarNacosDiscoveryClient.class);
|
.getLogger(SidecarNacosDiscoveryClient.class);
|
||||||
|
|
||||||
|
private NacosServiceManager nacosServiceManager;
|
||||||
|
|
||||||
private final SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties;
|
private final SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties;
|
||||||
|
|
||||||
public SidecarNacosDiscoveryClient(
|
public SidecarNacosDiscoveryClient(NacosServiceManager nacosServiceManager,
|
||||||
SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties) {
|
SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties) {
|
||||||
this.sidecarNacosDiscoveryProperties = sidecarNacosDiscoveryProperties;
|
this.sidecarNacosDiscoveryProperties = sidecarNacosDiscoveryProperties;
|
||||||
}
|
}
|
||||||
@ -39,8 +43,8 @@ public class SidecarNacosDiscoveryClient implements SidecarDiscoveryClient {
|
|||||||
@Override
|
@Override
|
||||||
public void registerInstance(String applicationName, String ip, Integer port) {
|
public void registerInstance(String applicationName, String ip, Integer port) {
|
||||||
try {
|
try {
|
||||||
this.sidecarNacosDiscoveryProperties.namingServiceInstance()
|
this.namingService().registerInstance(applicationName,
|
||||||
.registerInstance(applicationName, ip, port);
|
sidecarNacosDiscoveryProperties.getGroup(), ip, port);
|
||||||
}
|
}
|
||||||
catch (NacosException e) {
|
catch (NacosException e) {
|
||||||
log.warn("nacos exception happens", e);
|
log.warn("nacos exception happens", e);
|
||||||
@ -50,12 +54,17 @@ public class SidecarNacosDiscoveryClient implements SidecarDiscoveryClient {
|
|||||||
@Override
|
@Override
|
||||||
public void deregisterInstance(String applicationName, String ip, Integer port) {
|
public void deregisterInstance(String applicationName, String ip, Integer port) {
|
||||||
try {
|
try {
|
||||||
this.sidecarNacosDiscoveryProperties.namingServiceInstance()
|
this.namingService().deregisterInstance(applicationName,
|
||||||
.deregisterInstance(applicationName, ip, port);
|
sidecarNacosDiscoveryProperties.getGroup(), ip, port);
|
||||||
}
|
}
|
||||||
catch (NacosException e) {
|
catch (NacosException e) {
|
||||||
log.warn("nacos exception happens", e);
|
log.warn("nacos exception happens", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private NamingService namingService() {
|
||||||
|
return nacosServiceManager
|
||||||
|
.getNamingService(sidecarNacosDiscoveryProperties.getNacosProperties());
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -16,29 +16,29 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.sidecar.nacos;
|
package com.alibaba.cloud.sidecar.nacos;
|
||||||
|
|
||||||
import java.net.SocketException;
|
|
||||||
|
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
import com.alibaba.cloud.sidecar.SidecarProperties;
|
import com.alibaba.cloud.sidecar.SidecarProperties;
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author itmuch.com
|
* @author itmuch.com
|
||||||
|
* @author yuhuangbin
|
||||||
*/
|
*/
|
||||||
public class SidecarNacosDiscoveryProperties extends NacosDiscoveryProperties {
|
public class SidecarNacosDiscoveryProperties extends NacosDiscoveryProperties {
|
||||||
|
|
||||||
private final SidecarProperties sidecarProperties;
|
SidecarProperties sidecarProperties;
|
||||||
|
|
||||||
public SidecarNacosDiscoveryProperties(SidecarProperties sidecarProperties) {
|
public SidecarNacosDiscoveryProperties(SidecarProperties sidecarProperties) {
|
||||||
this.sidecarProperties = sidecarProperties;
|
this.sidecarProperties = sidecarProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void init() throws SocketException {
|
public void init() throws Exception {
|
||||||
super.init();
|
super.init();
|
||||||
|
|
||||||
String ip = sidecarProperties.getIp();
|
String ip = sidecarProperties.getIp();
|
||||||
if (StringUtils.isNotBlank(ip)) {
|
if (!StringUtils.isEmpty(ip)) {
|
||||||
this.setIp(ip);
|
this.setIp(ip);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -92,7 +92,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.zookeeper</groupId>
|
<groupId>org.apache.zookeeper</groupId>
|
||||||
<artifactId>zookeeper</artifactId>
|
<artifactId>zookeeper</artifactId>
|
||||||
<version>3.4.12</version>
|
<version>3.4.14</version>
|
||||||
<optional>true</optional>
|
<optional>true</optional>
|
||||||
<exclusions>
|
<exclusions>
|
||||||
<exclusion>
|
<exclusion>
|
||||||
|
@ -24,15 +24,11 @@ import com.alibaba.cloud.dubbo.service.parameter.RequestBodyServiceParameterReso
|
|||||||
import com.alibaba.cloud.dubbo.service.parameter.RequestHeaderServiceParameterResolver;
|
import com.alibaba.cloud.dubbo.service.parameter.RequestHeaderServiceParameterResolver;
|
||||||
import com.alibaba.cloud.dubbo.service.parameter.RequestParamServiceParameterResolver;
|
import com.alibaba.cloud.dubbo.service.parameter.RequestParamServiceParameterResolver;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.context.annotation.Import;
|
import org.springframework.context.annotation.Import;
|
||||||
import org.springframework.context.annotation.Primary;
|
|
||||||
import org.springframework.core.env.Environment;
|
|
||||||
import org.springframework.core.env.PropertyResolver;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Spring Boot Auto-Configuration class for Dubbo Service.
|
* Spring Boot Auto-Configuration class for Dubbo Service.
|
||||||
@ -49,17 +45,6 @@ public class DubboServiceAutoConfiguration {
|
|||||||
return new DubboGenericServiceFactory();
|
return new DubboGenericServiceFactory();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a primary {@link PropertyResolver} bean to {@link Autowired @Autowired}.
|
|
||||||
* @param environment {@link Environment}
|
|
||||||
* @return alias bean for {@link Environment}
|
|
||||||
*/
|
|
||||||
@Bean
|
|
||||||
@Primary
|
|
||||||
public PropertyResolver primaryPropertyResolver(Environment environment) {
|
|
||||||
return environment;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@Import({ DubboGenericServiceExecutionContextFactory.class,
|
@Import({ DubboGenericServiceExecutionContextFactory.class,
|
||||||
RequestParamServiceParameterResolver.class,
|
RequestParamServiceParameterResolver.class,
|
||||||
|
@ -33,6 +33,7 @@ import com.alibaba.cloud.dubbo.registry.AbstractSpringCloudRegistry;
|
|||||||
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
|
import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent;
|
||||||
import com.alibaba.cloud.dubbo.registry.event.SubscribedServicesChangedEvent;
|
import com.alibaba.cloud.dubbo.registry.event.SubscribedServicesChangedEvent;
|
||||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||||
|
import com.alibaba.cloud.nacos.NacosServiceManager;
|
||||||
import com.alibaba.cloud.nacos.discovery.NacosWatch;
|
import com.alibaba.cloud.nacos.discovery.NacosWatch;
|
||||||
import com.alibaba.nacos.api.exception.NacosException;
|
import com.alibaba.nacos.api.exception.NacosException;
|
||||||
import com.alibaba.nacos.api.naming.NamingService;
|
import com.alibaba.nacos.api.naming.NamingService;
|
||||||
@ -517,8 +518,10 @@ public class DubboServiceDiscoveryAutoConfiguration {
|
|||||||
*/
|
*/
|
||||||
private final Set<String> listeningServices;
|
private final Set<String> listeningServices;
|
||||||
|
|
||||||
NacosConfiguration(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
NacosConfiguration(NacosServiceManager nacosServiceManager,
|
||||||
this.namingService = nacosDiscoveryProperties.namingServiceInstance();
|
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||||
|
this.namingService = nacosServiceManager
|
||||||
|
.getNamingService(nacosDiscoveryProperties.getNacosProperties());
|
||||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||||
this.listeningServices = new ConcurrentSkipListSet<>();
|
this.listeningServices = new ConcurrentSkipListSet<>();
|
||||||
}
|
}
|
||||||
|
@ -75,12 +75,17 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration {
|
|||||||
|
|
||||||
@Around("execution(* org.springframework.cloud.client.serviceregistry.Registration.getPort())")
|
@Around("execution(* org.springframework.cloud.client.serviceregistry.Registration.getPort())")
|
||||||
public Object getPort(ProceedingJoinPoint pjp) throws Throwable {
|
public Object getPort(ProceedingJoinPoint pjp) throws Throwable {
|
||||||
|
/**
|
||||||
|
* move setServerPort from onApplicationStarted() to here for this issue :
|
||||||
|
* https://github.com/alibaba/spring-cloud-alibaba/issues/1383
|
||||||
|
* @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
|
||||||
|
*/
|
||||||
|
setServerPort();
|
||||||
return serverPort != null ? serverPort : pjp.proceed();
|
return serverPort != null ? serverPort : pjp.proceed();
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventListener(ApplicationStartedEvent.class)
|
@EventListener(ApplicationStartedEvent.class)
|
||||||
public void onApplicationStarted() {
|
public void onApplicationStarted() {
|
||||||
setServerPort();
|
|
||||||
register();
|
register();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,18 +103,22 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration {
|
|||||||
*/
|
*/
|
||||||
private void setServerPort() {
|
private void setServerPort() {
|
||||||
if (serverPort == null) {
|
if (serverPort == null) {
|
||||||
for (List<URL> urls : repository.getAllExportedUrls().values()) {
|
synchronized (this) {
|
||||||
urls.stream()
|
|
||||||
.filter(url -> REST_PROTOCOL.equalsIgnoreCase(url.getProtocol()))
|
|
||||||
.findFirst().ifPresent(url -> {
|
|
||||||
serverPort = url.getPort();
|
|
||||||
});
|
|
||||||
|
|
||||||
// If REST protocol is not present, use any applied port.
|
|
||||||
if (serverPort == null) {
|
if (serverPort == null) {
|
||||||
urls.stream().findAny().ifPresent(url -> {
|
for (List<URL> urls : repository.getAllExportedUrls().values()) {
|
||||||
serverPort = url.getPort();
|
urls.stream().filter(
|
||||||
});
|
url -> REST_PROTOCOL.equalsIgnoreCase(url.getProtocol()))
|
||||||
|
.findFirst().ifPresent(url -> {
|
||||||
|
serverPort = url.getPort();
|
||||||
|
});
|
||||||
|
|
||||||
|
// If REST protocol is not present, use any applied port.
|
||||||
|
if (serverPort == null) {
|
||||||
|
urls.stream().findAny().ifPresent(url -> {
|
||||||
|
serverPort = url.getPort();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -125,6 +134,7 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration {
|
|||||||
@EventListener(ServiceInstancePreRegisteredEvent.class)
|
@EventListener(ServiceInstancePreRegisteredEvent.class)
|
||||||
public void onServiceInstancePreRegistered(
|
public void onServiceInstancePreRegistered(
|
||||||
ServiceInstancePreRegisteredEvent event) {
|
ServiceInstancePreRegisteredEvent event) {
|
||||||
|
setServerPort();
|
||||||
registration.setPort(serverPort);
|
registration.setPort(serverPort);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -65,7 +65,6 @@ public class DubboProtocolConfigSupplier implements Supplier<ProtocolConfig> {
|
|||||||
if (protocolConfig == null) {
|
if (protocolConfig == null) {
|
||||||
protocolConfig = new ProtocolConfig();
|
protocolConfig = new ProtocolConfig();
|
||||||
protocolConfig.setName(DEFAULT_PROTOCOL);
|
protocolConfig.setName(DEFAULT_PROTOCOL);
|
||||||
protocolConfig.setPort(-1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return protocolConfig;
|
return protocolConfig;
|
||||||
|
@ -29,7 +29,7 @@ import org.springframework.cloud.client.ServiceInstance;
|
|||||||
public interface ServiceInstanceSelector {
|
public interface ServiceInstanceSelector {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* choose a service instance to get metadata.
|
* Select a service instance to get metadata.
|
||||||
* @param serviceInstances all service instance
|
* @param serviceInstances all service instance
|
||||||
* @return the service instance to get metadata
|
* @return the service instance to get metadata
|
||||||
*/
|
*/
|
||||||
|
@ -16,14 +16,14 @@
|
|||||||
|
|
||||||
package com.alibaba.cloud.dubbo.registry.event;
|
package com.alibaba.cloud.dubbo.registry.event;
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.List;
|
||||||
|
|
||||||
import org.springframework.cloud.client.ServiceInstance;
|
import org.springframework.cloud.client.ServiceInstance;
|
||||||
import org.springframework.context.ApplicationEvent;
|
import org.springframework.context.ApplicationEvent;
|
||||||
import org.springframework.context.event.ApplicationEventMulticaster;
|
import org.springframework.context.event.ApplicationEventMulticaster;
|
||||||
import org.springframework.context.event.SimpleApplicationEventMulticaster;
|
import org.springframework.context.event.SimpleApplicationEventMulticaster;
|
||||||
|
|
||||||
import static java.util.Collections.unmodifiableCollection;
|
import static java.util.Collections.unmodifiableList;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An event raised after the {@link ServiceInstance instances} of one service has been
|
* An event raised after the {@link ServiceInstance instances} of one service has been
|
||||||
@ -35,7 +35,7 @@ public class ServiceInstancesChangedEvent extends ApplicationEvent {
|
|||||||
|
|
||||||
private final String serviceName;
|
private final String serviceName;
|
||||||
|
|
||||||
private final Collection<ServiceInstance> serviceInstances;
|
private final List<ServiceInstance> serviceInstances;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Current event has been processed or not. Typically, Spring Event was based on sync
|
* Current event has been processed or not. Typically, Spring Event was based on sync
|
||||||
@ -51,10 +51,10 @@ public class ServiceInstancesChangedEvent extends ApplicationEvent {
|
|||||||
* @throws IllegalArgumentException if source is null.
|
* @throws IllegalArgumentException if source is null.
|
||||||
*/
|
*/
|
||||||
public ServiceInstancesChangedEvent(String serviceName,
|
public ServiceInstancesChangedEvent(String serviceName,
|
||||||
Collection<ServiceInstance> serviceInstances) {
|
List<ServiceInstance> serviceInstances) {
|
||||||
super(serviceName);
|
super(serviceName);
|
||||||
this.serviceName = serviceName;
|
this.serviceName = serviceName;
|
||||||
this.serviceInstances = unmodifiableCollection(serviceInstances);
|
this.serviceInstances = unmodifiableList(serviceInstances);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -67,7 +67,7 @@ public class ServiceInstancesChangedEvent extends ApplicationEvent {
|
|||||||
/**
|
/**
|
||||||
* @return all {@link ServiceInstance service instances}.
|
* @return all {@link ServiceInstance service instances}.
|
||||||
*/
|
*/
|
||||||
public Collection<ServiceInstance> getServiceInstances() {
|
public List<ServiceInstance> getServiceInstances() {
|
||||||
return serviceInstances;
|
return serviceInstances;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user