1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

Merge pull request #7 from alibaba/master

update
This commit is contained in:
yuhuangbin 2020-02-23 21:34:50 +08:00 committed by GitHub
commit 40671aae98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
147 changed files with 1298 additions and 397 deletions

57
pom.xml
View File

@ -8,13 +8,13 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>2.2.1.RELEASE</version>
<version>2.2.0.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Cloud Alibaba</name>
<description>Spring Cloud Alibaba</description>
@ -73,14 +73,14 @@
<properties>
<!-- Dependency Versions -->
<spring-cloud-commons.version>2.2.1.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.1.RELEASE</spring-cloud-netflix.version>
<spring-cloud-openfeign.version>2.2.1.RELEASE</spring-cloud-openfeign.version>
<spring-cloud-commons.version>2.2.0.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.2.0.RELEASE</spring-cloud-netflix.version>
<spring-cloud-openfeign.version>2.2.0.RELEASE</spring-cloud-openfeign.version>
<spring-cloud-bus.version>2.2.0.RELEASE</spring-cloud-bus.version>
<spring-cloud-gateway.version>2.2.1.RELEASE</spring-cloud-gateway.version>
<spring-cloud-stream.version>Horsham.SR1</spring-cloud-stream.version>
<spring-cloud-consul.version>2.2.1.RELEASE</spring-cloud-consul.version>
<spring-cloud-config.version>2.2.1.RELEASE</spring-cloud-config.version>
<spring-cloud-gateway.version>2.2.0.RELEASE</spring-cloud-gateway.version>
<spring-cloud-stream.version>Horsham.RELEASE</spring-cloud-stream.version>
<spring-cloud-consul.version>2.2.0.RELEASE</spring-cloud-consul.version>
<spring-cloud-config.version>2.2.0.RELEASE</spring-cloud-config.version>
<spring-cloud-zookeeper.version>2.2.0.RELEASE</spring-cloud-zookeeper.version>
<junit.version>4.12</junit.version>
@ -88,8 +88,7 @@
<slf4j-api.version>1.7.25</slf4j-api.version>
<!-- Apache Dubbo -->
<dubbo-spring-boot.version>2.7.3</dubbo-spring-boot.version>
<dubbo.version>2.7.3</dubbo.version>
<dubbo.version>2.7.4.1</dubbo.version>
<curator.version>4.0.1</curator.version>
<!-- Apache RocketMQ -->
@ -132,7 +131,7 @@
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
@ -228,10 +227,31 @@
<scope>import</scope>
</dependency>
<!-- Dubbo Dependencies -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-bom</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
<scope>import</scope>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>${dubbo-spring-boot.version}</version>
<version>${dubbo.version}</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-actuator</artifactId>
<version>${dubbo.version}</version>
</dependency>
<dependency>
@ -241,15 +261,7 @@
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<artifactId>spring-context</artifactId>
</exclusion>
</exclusions>
</dependency>
@ -420,5 +432,4 @@
</profiles>
</project>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -13,7 +13,7 @@
<name>Spring Cloud Alibaba Coverage</name>
<properties>
<spring.cloud.alibaba.version>2.2.0.BUILD-SNAPSHOT</spring.cloud.alibaba.version>
<spring.cloud.alibaba.version>2.2.1.BUILD-SNAPSHOT</spring.cloud.alibaba.version>
</properties>
<dependencies>
<dependency>

View File

@ -6,13 +6,13 @@
<parent>
<artifactId>spring-cloud-dependencies-parent</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>2.2.1.RELEASE</version>
<version>2.2.0.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Spring Cloud Alibaba Dependencies</name>
<description>Spring Cloud Alibaba Dependencies</description>
@ -402,6 +402,7 @@
</dependencyManagement>
<profiles>
<profile>
<id>spring</id>
<repositories>
@ -432,13 +433,6 @@
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>sonatype-nexus</id>
<url>https://oss.sonatype.org/content/repositories/releases</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
@ -460,7 +454,16 @@
<enabled>false</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release-local</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</project>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -10,7 +10,7 @@ Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.1.BUILD-SNAPSHOT</version>
<version>2.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>

View File

@ -8,7 +8,7 @@ If youre a Maven Central user, add our BOM to your pom.xml <dependencyManagem
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.1.BUILD-SNAPSHOT</version>
<version>2.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -13,30 +13,6 @@
<artifactId>spring-cloud-alibaba-dubbo</artifactId>
<name>Spring Cloud Alibaba Dubbo</name>
<dependencyManagement>
<dependencies>
<!-- Spring Boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Apache Dubbo dependencies-->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-bom</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
@ -162,7 +138,6 @@
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-actuator</artifactId>
<version>${dubbo-spring-boot.version}</version>
<optional>true</optional>
</dependency>

View File

@ -118,7 +118,7 @@ public class DubboServiceDiscoveryAutoConfiguration {
/**
* NacosDiscoveryAutoConfiguration.
*/
public static final String NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration";
public static final String NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration";
private final DubboServiceMetadataRepository dubboServiceMetadataRepository;

View File

@ -29,7 +29,7 @@ import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;
import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOCOL;
import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties;
import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getPrefixedProperties;
/**
* Missing {@link SpringCloudRegistry} Property {@link Condition}.
@ -61,8 +61,8 @@ public class MissingSpringCloudRegistryConfigPropertyCondition
"'spring-cloud' protocol was found from 'dubbo.registry.address'");
}
Map<String, Object> properties = getSubProperties(environment,
"dubbo.registries.");
Map<String, Object> properties = getPrefixedProperties(
environment.getPropertySources(), "dubbo.registries.");
boolean found = properties.entrySet().stream().anyMatch(entry -> {
String key = entry.getKey();

View File

@ -35,7 +35,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL;
import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties;
import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getPrefixedProperties;
/**
* Dubbo {@link WebApplicationType#NONE Non-Web Application}
@ -149,8 +149,8 @@ public class DubboNonWebApplicationEnvironmentPostProcessor
String restPort = null;
Map<String, Object> subProperties = getSubProperties(environment,
PROTOCOLS_PROPERTY_NAME_PREFIX);
Map<String, Object> subProperties = getPrefixedProperties(
environment.getPropertySources(), PROTOCOLS_PROPERTY_NAME_PREFIX);
Properties properties = new Properties();

View File

@ -297,12 +297,15 @@ public class DubboServiceMetadataRepository
}
/**
* Remove the metadata of Dubbo Services if no there is no service instance.
* Remove the metadata and initialized service of Dubbo Services if no there is no
* service instance.
* @param serviceName the service name
*/
public void removeInitializedService(String serviceName) {
public void removeMetadataAndInitializedService(String serviceName) {
synchronized (monitor) {
initializedServices.remove(serviceName);
dubboRestServiceMetadataRepository.remove(serviceName);
subscribedDubboMetadataServiceURLs.remove(serviceName);
}
}
@ -644,11 +647,6 @@ public class DubboServiceMetadataRepository
dubboMetadataConfigServiceProxy.initProxy(serviceName, version);
}
public void removeMetadata(String serviceName) {
dubboRestServiceMetadataRepository.remove(serviceName);
subscribedDubboMetadataServiceURLs.remove(serviceName);
}
@Override
public void setApplicationEventPublisher(
ApplicationEventPublisher applicationEventPublisher) {

View File

@ -224,8 +224,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry {
if (CollectionUtils.isEmpty(serviceInstances)) {
dubboMetadataConfigServiceProxy.removeProxy(serviceName);
repository.removeInitializedService(serviceName);
repository.removeMetadata(serviceName);
repository.removeMetadataAndInitializedService(serviceName);
dubboGenericServiceFactory.destroy(serviceName);
if (logger.isWarnEnabled()) {
logger.warn(

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -3,3 +3,4 @@ server.port=18089
spring.cloud.alicloud.acm.server-list=127.0.0.1
spring.cloud.alicloud.acm.server-port=8080
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -3,3 +3,5 @@ server.port=18082
# The following configuration can be omitted.
spring.cloud.alicloud.ans.server-list=127.0.0.1
spring.cloud.alicloud.ans.server-port=8080
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -2,3 +2,5 @@ spring.application.name=ans-provider
server.port=18081
spring.cloud.alicloud.ans.server-list=127.0.0.1
spring.cloud.alicloud.ans.server-port=8080
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -1,2 +1,3 @@
server.port=18084
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -41,6 +41,11 @@
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>

View File

@ -2,6 +2,6 @@
n=1
while [ $n -le 10 ]
do
echo `curl -s http://localhost:18083/echo-feign/openfeign`
echo `curl -s http://localhost:18083/test`
let n++
done

View File

@ -0,0 +1,7 @@
#!/usr/bin/env bash
n=1
while [ $n -le 10 ]
do
echo `curl -s http://localhost:18083/divide-feign2?a=1`
let n++
done

View File

@ -0,0 +1,7 @@
#!/usr/bin/env bash
n=1
while [ $n -le 10 ]
do
echo `curl -s http://localhost:18083/divide-feign?a=1\&b=0`
let n++
done

View File

@ -0,0 +1,7 @@
#!/usr/bin/env bash
n=1
while [ $n -le 10 ]
do
echo `curl -s http://localhost:18083/index`
let n++
done

View File

@ -0,0 +1,7 @@
#!/usr/bin/env bash
n=1
while [ $n -le 10 ]
do
echo `curl -s http://localhost:18083/sleep`
let n++
done

View File

@ -19,6 +19,8 @@ package com.alibaba.cloud.examples;
import java.util.List;
import java.util.Random;
import com.alibaba.cloud.examples.ConsumerSCLBApplication.EchoService;
import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
@ -28,6 +30,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.reactive.DefaultResponse;
@ -58,10 +61,18 @@ public class ConsumerSCLBApplication {
@LoadBalanced
@Bean
@SentinelRestTemplate(urlCleanerClass = UrlCleaner.class, urlCleaner = "clean")
public RestTemplate restTemplate() {
return new RestTemplate();
}
@LoadBalanced
@Bean
@SentinelRestTemplate
public RestTemplate restTemplate1() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerSCLBApplication.class, args);
}
@ -112,7 +123,8 @@ public class ConsumerSCLBApplication {
}
@FeignClient(name = "service-provider")
@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class,
configuration = FeignConfiguration.class)
public interface EchoService {
@GetMapping("/echo/{str}")
@ -136,9 +148,15 @@ public class ConsumerSCLBApplication {
@Autowired
private RestTemplate restTemplate;
@Autowired
private RestTemplate restTemplate1;
@Autowired
private EchoService echoService;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/echo-rest/{str}")
public String rest(@PathVariable String str) {
return restTemplate.getForObject("http://service-provider/echo/" + str,
@ -150,6 +168,76 @@ public class ConsumerSCLBApplication {
return echoService.echo(str);
}
@GetMapping("/index")
public String index() {
return restTemplate1.getForObject("http://service-provider", String.class);
}
@GetMapping("/test")
public String test() {
return restTemplate1.getForObject("http://service-provider/test",
String.class);
}
@GetMapping("/sleep")
public String sleep() {
return restTemplate1.getForObject("http://service-provider/sleep",
String.class);
}
@GetMapping("/notFound-feign")
public String notFound() {
return echoService.notFound();
}
@GetMapping("/divide-feign")
public String divide(@RequestParam Integer a, @RequestParam Integer b) {
return echoService.divide(a, b);
}
@GetMapping("/divide-feign2")
public String divide(@RequestParam Integer a) {
return echoService.divide(a);
}
@GetMapping("/services/{service}")
public Object client(@PathVariable String service) {
return discoveryClient.getInstances(service);
}
@GetMapping("/services")
public Object services() {
return discoveryClient.getServices();
}
}
}
class FeignConfiguration {
@Bean
public EchoServiceFallback echoServiceFallback() {
return new EchoServiceFallback();
}
}
class EchoServiceFallback implements EchoService {
@Override
public String echo(@PathVariable("str") String str) {
return "echo fallback";
}
@Override
public String divide(@RequestParam Integer a, @RequestParam Integer b) {
return "divide fallback";
}
@Override
public String notFound() {
return "notFound fallback";
}
}

View File

@ -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.examples;
public class UrlCleaner {
public static String clean(String url) {
System.out.println("enter urlCleaner");
if (url.matches(".*/echo/.*")) {
System.out.println("change url");
url = url.replaceAll("/echo/.*", "/echo/{str}");
}
return url;
}
}

View File

@ -4,3 +4,16 @@ management.endpoints.web.exposure.include=*
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.loadbalancer.ribbon.enabled=false
feign.sentinel.enabled=true
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.eager=true
spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
spring.cloud.sentinel.datasource.ds2.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds2.file.data-type=json
spring.cloud.sentinel.datasource.ds2.file.rule-type=degrade

View File

@ -0,0 +1,26 @@
[
{
"resource": "GET:http://service-provider/test",
"count": 0.5,
"grade": 1,
"timeWindow": 30
},
{
"resource": "GET:http://service-provider",
"count": 0.5,
"grade": 1,
"timeWindow": 10
},
{
"resource": "GET:http://service-provider/sleep",
"count": 20.0,
"grade": 0,
"timeWindow": 30
},
{
"resource": "GET:http://service-provider/divide",
"count": 0.5,
"grade": 1,
"timeWindow": 30
}
]

View File

@ -0,0 +1,10 @@
[
{
"resource": "GET:http://service-provider/echo/{str}",
"controlBehavior": 0,
"count": 2,
"grade": 1,
"limitApp": "default",
"strategy": 0
}
]

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -2,3 +2,4 @@ server.port=18082
spring.application.name=service-provider
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-discovery-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-gateway-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>nacos-gateway-example</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -16,6 +16,10 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

View File

@ -1,5 +1,6 @@
spring.application.name=account-service
server.port=18084
spring.cloud.nacos.discovery.server-addr=localhost:8848
spring.datasource.name="accountDataSource"
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -16,17 +16,21 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -18,11 +18,13 @@ package com.alibaba.cloud.examples;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
@ -31,6 +33,7 @@ import org.springframework.web.client.RestTemplate;
*/
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient(autoRegister = false)
public class BusinessApplication {
public static void main(String[] args) {
@ -42,16 +45,16 @@ public class BusinessApplication {
return new RestTemplate();
}
@FeignClient(value = "storage", url = "http://127.0.0.1:18082")
@FeignClient("storage-service")
public interface StorageService {
@RequestMapping(path = "/storage/{commodityCode}/{count}")
String storage(@RequestParam("commodityCode") String commodityCode,
@RequestParam("count") int count);
@GetMapping(path = "/storage/{commodityCode}/{count}")
String storage(@PathVariable("commodityCode") String commodityCode,
@PathVariable("count") int count);
}
@FeignClient(value = "order", url = "http://127.0.0.1:18083")
@FeignClient("order-service")
public interface OrderService {
@PostMapping(path = "/order")

View File

@ -1,5 +1,6 @@
server.port=18081
spring.application.name=business-service
spring.cloud.nacos.discovery.server-addr=localhost:8848
# The following configuration can be omitted.
#feign.hystrix.enabled=true
@ -12,6 +13,8 @@ seata.service.vgroup-mapping=default
seata.service.grouplist=127.0.0.1:8091
seata.service.disable-global-transaction=false
spring.cloud.loadbalancer.ribbon.enabled=true
## if use registry center
#seata.registry.type=nacos
#seata.registry.nacos.cluster=default

View File

@ -5,13 +5,17 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>order-service</artifactId>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>

View File

@ -1,5 +1,6 @@
spring.application.name=order-service
server.port=18083
spring.cloud.nacos.discovery.server-addr=localhost:8848
spring.datasource.name="orderDataSource"
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -16,6 +16,10 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

View File

@ -1,5 +1,6 @@
spring.application.name=storage-service
server.port=18082
spring.cloud.nacos.discovery.server-addr=localhost:8848
spring.datasource.name="storageDataSource"
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -60,14 +60,14 @@ public class TestController {
@GetMapping("/slow")
public String slow() {
return circuitBreakerFactory.create("show").run(() -> {
return circuitBreakerFactory.create("slow").run(() -> {
try {
Thread.sleep(1000L);
Thread.sleep(500L);
}
catch (InterruptedException e) {
e.printStackTrace();
}
return "success";
return "slow";
}, throwable -> "fallback");
}

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -16,9 +16,16 @@
package com.alibaba.cloud.examples;
import java.util.Collections;
import com.alibaba.cloud.circuitbreaker.sentinel.ReactiveSentinelCircuitBreakerFactory;
import com.alibaba.cloud.circuitbreaker.sentinel.SentinelConfigBuilder;
import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import reactor.core.publisher.Mono;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@ -46,4 +53,23 @@ public class MyConfiguration {
};
}
@Bean
public Customizer<ReactiveSentinelCircuitBreakerFactory> slowCustomizer() {
return factory -> {
factory.configure(builder -> builder.rules(Collections.singletonList(
new DegradeRule("slow_mono").setGrade(RuleConstant.DEGRADE_GRADE_RT)
.setCount(100).setTimeWindow(5))),
"slow_mono");
factory.configure(builder -> builder.rules(Collections.singletonList(
new DegradeRule("slow_flux").setGrade(RuleConstant.DEGRADE_GRADE_RT)
.setCount(100).setTimeWindow(5))),
"slow_flux");
factory.configureDefault(id -> new SentinelConfigBuilder().resourceName(id)
.rules(Collections.singletonList(new DegradeRule(id)
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT)
.setCount(0.5).setTimeWindow(10)))
.build());
};
}
}

View File

@ -20,8 +20,11 @@ import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
@ -29,6 +32,9 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class SentinelWebFluxController {
@Autowired
private ReactiveCircuitBreakerFactory circuitBreakerFactory;
@GetMapping("/mono")
public Mono<String> mono() {
return Mono.just("simple string")
@ -50,4 +56,26 @@ public class SentinelWebFluxController {
.transform(new SentinelReactorTransformer<>("flux"));
}
@GetMapping("/cbSlow")
public Mono<String> cbSlow() {
int delaySecs = 2;
return WebClient.builder().baseUrl("http://httpbin.org/").build().get()
.uri("/delay/" + delaySecs).retrieve().bodyToMono(String.class)
.transform(it -> circuitBreakerFactory.create("slow_mono").run(it, t -> {
t.printStackTrace();
return Mono.just("fallback");
}));
}
@GetMapping("/cbError")
public Mono<String> cbError() {
String code = "500";
return WebClient.builder().baseUrl("http://httpbin.org/").build().get()
.uri("/status/" + code).retrieve().bodyToMono(String.class)
.transform(it -> circuitBreakerFactory.create("cbError").run(it, t -> {
t.printStackTrace();
return Mono.just("fallback");
}));
}
}

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -10,7 +10,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

View File

@ -5,14 +5,14 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<name>Spring Cloud Alibaba Dubbo Examples</name>
<packaging>pom</packaging>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -13,7 +13,7 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-dubbo-client-sample</artifactId>
<name>Spring Cloud Dubbo Client Sample</name>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<dependencies>
<!-- Sample API -->

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -136,18 +136,6 @@
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-bom</artifactId>
<version>${dubbo.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -14,7 +14,7 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-dubbo-server-sample</artifactId>
<name>Spring Cloud Dubbo Server Sample</name>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<dependencies>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dubbo-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>spring-cloud-alibaba-examples</artifactId>
<groupId>com.alibaba.cloud</groupId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -32,6 +32,7 @@ import javax.annotation.PostConstruct;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.spring.util.PropertySourcesUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -88,6 +89,7 @@ public class NacosConfigProperties {
.getLogger(NacosConfigProperties.class);
@Autowired
@JsonIgnore
private Environment environment;
@PostConstruct

View File

@ -17,9 +17,8 @@
package com.alibaba.cloud.nacos.client;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
@ -39,7 +38,7 @@ public class NacosPropertySourceBuilder {
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class);
private static final Properties EMPTY_PROPERTIES = new Properties();
private static final Map<String, Object> EMPTY_MAP = new LinkedHashMap();
private ConfigService configService;
@ -72,14 +71,15 @@ public class NacosPropertySourceBuilder {
*/
NacosPropertySource build(String dataId, String group, String fileExtension,
boolean isRefreshable) {
Properties p = loadNacosData(dataId, group, fileExtension);
Map<String, Object> p = loadNacosData(dataId, group, fileExtension);
NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId,
propertiesToMap(p), new Date(), isRefreshable);
p, new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource);
return nacosPropertySource;
}
private Properties loadNacosData(String dataId, String group, String fileExtension) {
private Map<String, Object> loadNacosData(String dataId, String group,
String fileExtension) {
String data = null;
try {
data = configService.getConfig(dataId, group, timeout);
@ -87,16 +87,16 @@ public class NacosPropertySourceBuilder {
log.warn(
"Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
dataId, group);
return EMPTY_PROPERTIES;
return EMPTY_MAP;
}
if (log.isDebugEnabled()) {
log.debug(String.format(
"Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId,
group, data));
}
Properties properties = NacosDataParserHandler.getInstance()
Map<String, Object> dataMap = NacosDataParserHandler.getInstance()
.parseNacosData(data, fileExtension);
return properties == null ? EMPTY_PROPERTIES : properties;
return dataMap == null ? EMPTY_MAP : dataMap;
}
catch (NacosException e) {
log.error("get data from Nacos error,dataId:{}, ", dataId, e);
@ -104,14 +104,7 @@ public class NacosPropertySourceBuilder {
catch (Exception e) {
log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e);
}
return EMPTY_PROPERTIES;
}
@SuppressWarnings("unchecked")
private Map<String, Object> propertiesToMap(Properties properties) {
Map<String, Object> result = new HashMap<>(16);
properties.forEach((k, v) -> result.put(String.valueOf(k), v));
return result;
return EMPTY_MAP;
}
}

View File

@ -20,9 +20,13 @@ import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
/**
* The {@link HealthIndicator} for Nacos Config.
*
* @author xiaojing
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class NacosConfigHealthIndicator extends AbstractHealthIndicator {
@ -34,10 +38,21 @@ public class NacosConfigHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
builder.up();
// Just return "UP" or "DOWN"
String status = configService.getServerStatus();
// Set the status to Builder
builder.status(status);
switch (status) {
case "UP":
builder.up();
break;
case "DOWN":
builder.down();
break;
default:
builder.unknown();
break;
}
}
}

View File

@ -17,9 +17,12 @@
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.util.StringUtils;
@ -32,6 +35,8 @@ public abstract class AbstractNacosDataParser {
protected static final String VALUE = "value";
protected static final String EMPTY_STRING = "";
private String extension;
private AbstractNacosDataParser nextParser;
@ -66,7 +71,7 @@ public abstract class AbstractNacosDataParser {
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
public final Properties parseNacosData(String data, String extension)
public final Map<String, Object> parseNacosData(String data, String extension)
throws IOException {
if (extension == null || extension.length() < 1) {
throw new IllegalStateException("The file extension cannot be empty");
@ -86,7 +91,7 @@ public abstract class AbstractNacosDataParser {
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
protected abstract Properties doParse(String data) throws IOException;
protected abstract Map<String, Object> doParse(String data) throws IOException;
protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) {
this.nextParser = nextParser;
@ -108,23 +113,36 @@ public abstract class AbstractNacosDataParser {
|| this.extension.contains(extension);
}
/**
* Generate key-value pairs from the map.
*/
protected Properties generateProperties(Map<String, Object> map) {
if (null == map || map.isEmpty()) {
return null;
}
Properties properties = new Properties();
for (Map.Entry<String, Object> entry : map.entrySet()) {
protected void flattenedMap(Map<String, Object> result, Map<String, Object> dataMap,
String parentKey) {
Set<Map.Entry<String, Object>> entries = dataMap.entrySet();
for (Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); iterator
.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
if (StringUtils.isEmpty(key)) {
Object value = entry.getValue();
String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[")
? parentKey.concat(key) : parentKey.concat(DOT).concat(key);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
flattenedMap(result, map, fullKey);
continue;
}
key = key.startsWith(DOT) ? key.replaceFirst("\\.", "") : key;
properties.put(key, entry.getValue());
else if (value instanceof Collection) {
int count = 0;
Collection<Object> collection = (Collection<Object>) value;
for (Object object : collection) {
flattenedMap(result,
Collections.singletonMap("[" + (count++) + "]", object),
fullKey);
}
continue;
}
result.put(fullKey, value);
}
return properties;
}
/**
@ -134,7 +152,7 @@ public abstract class AbstractNacosDataParser {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Object> result = new HashMap<>(map);
Map<String, Object> result = new LinkedHashMap<>(map);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (key.contains(DOT)) {

View File

@ -17,13 +17,8 @@
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -41,12 +36,12 @@ public class NacosDataJsonParser extends AbstractNacosDataParser {
}
@Override
protected Properties doParse(String data) throws IOException {
protected Map<String, Object> doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, Object> map = parseJSON2Map(data);
return this.generateProperties(this.reloadMap(map));
return this.reloadMap(map);
}
/**
@ -55,49 +50,17 @@ public class NacosDataJsonParser extends AbstractNacosDataParser {
* @return the map convert by json string
* @throws IOException thrown if there is a problem parsing config.
*/
public static Map<String, Object> parseJSON2Map(String json) throws IOException {
Map<String, Object> result = new HashMap<>(32);
private Map<String, Object> parseJSON2Map(String json) throws IOException {
Map<String, Object> result = new LinkedHashMap<>(32);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nacosDataMap = mapper.readValue(json, Map.class);
Map<String, Object> nacosDataMap = mapper.readValue(json, LinkedHashMap.class);
if (CollectionUtils.isEmpty(nacosDataMap)) {
return result;
}
parseNacosDataMap(result, nacosDataMap, "");
flattenedMap(result, nacosDataMap, EMPTY_STRING);
return result;
}
private static void parseNacosDataMap(Map<String, Object> result,
Map<String, Object> dataMap, String parentKey) {
Set<Map.Entry<String, Object>> entries = dataMap.entrySet();
for (Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); iterator
.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[")
? parentKey.concat(key) : parentKey.concat(DOT).concat(key);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
parseNacosDataMap(result, map, fullKey);
continue;
}
else if (value instanceof Collection) {
int count = 0;
Collection<Object> collection = (Collection<Object>) value;
for (Object object : collection) {
parseNacosDataMap(result,
Collections.singletonMap("[" + (count++) + "]", object),
fullKey);
}
continue;
}
result.put(fullKey, value);
}
}
}

View File

@ -17,7 +17,7 @@
package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.util.Properties;
import java.util.Map;
/**
* @author zkz
@ -34,10 +34,11 @@ public final class NacosDataParserHandler {
* Parsing nacos configuration content.
* @param data config from Nacos
* @param extension file extension. json or xml or yml or yaml or properties
* @return result of properties
* @return result of LinkedHashMap
* @throws IOException thrown if there is a problem parsing config.
*/
public Properties parseNacosData(String data, String extension) throws IOException {
public Map<String, Object> parseNacosData(String data, String extension)
throws IOException {
if (null == parser) {
parser = this.createParser();
}

View File

@ -16,24 +16,49 @@
package com.alibaba.cloud.nacos.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @author zkz
*/
public class NacosDataPropertiesParser extends AbstractNacosDataParser {
private static final Logger log = LoggerFactory
.getLogger(NacosDataPropertiesParser.class);
public NacosDataPropertiesParser() {
super("properties");
}
@Override
protected Properties doParse(String data) throws IOException {
Properties properties = new Properties();
properties.load(new StringReader(data));
return properties;
protected Map<String, Object> doParse(String data) throws IOException {
Map<String, Object> result = new LinkedHashMap<>();
try (BufferedReader reader = new BufferedReader(new StringReader(data))) {
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
String dataLine = line.trim();
if (StringUtils.isEmpty(dataLine) || dataLine.startsWith("#")) {
continue;
}
int index = dataLine.indexOf("=");
if (index == -1) {
log.warn("the config data is invalid {}", dataLine);
continue;
}
result.put(dataLine.substring(0, index), dataLine.substring(index + 1));
}
}
return result;
}
}

View File

@ -18,9 +18,8 @@ package com.alibaba.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@ -46,17 +45,17 @@ public class NacosDataXmlParser extends AbstractNacosDataParser {
}
@Override
protected Properties doParse(String data) throws IOException {
protected Map<String, Object> doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, Object> map = parseXml2Map(data);
return this.generateProperties(this.reloadMap(map));
return this.reloadMap(map);
}
private Map<String, Object> parseXml2Map(String xml) throws IOException {
xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "");
Map<String, Object> map = new HashMap<>(32);
Map<String, Object> map = new LinkedHashMap<>(32);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();

View File

@ -16,9 +16,10 @@
package com.alibaba.cloud.nacos.parser;
import java.util.Properties;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ByteArrayResource;
/**
@ -31,10 +32,13 @@ public class NacosDataYamlParser extends AbstractNacosDataParser {
}
@Override
protected Properties doParse(String data) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
protected Map<String, Object> doParse(String data) {
YamlMapFactoryBean yamlFactory = new YamlMapFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
Map<String, Object> result = new LinkedHashMap<>();
flattenedMap(result, yamlFactory.getObject(), EMPTY_STRING);
return result;
}
}

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>2.2.0.BUILD-SNAPSHOT</version>
<version>2.2.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -108,6 +108,18 @@
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -19,6 +19,7 @@ package com.alibaba.cloud.nacos.discovery;
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -30,6 +31,7 @@ import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
/**
* @author xiaojing
@ -54,8 +56,9 @@ public class NacosDiscoveryClientConfiguration {
@ConditionalOnMissingBean
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.watch.enabled",
matchIfMissing = true)
public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosWatch(nacosDiscoveryProperties);
public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties,
ObjectProvider<TaskScheduler> taskScheduler) {
return new NacosWatch(nacosDiscoveryProperties, taskScheduler);
}
}

View File

@ -16,18 +16,15 @@
package com.alibaba.cloud.nacos.discovery;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.listener.EventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
@ -54,10 +51,6 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl
private ScheduledFuture<?> watchFuture;
private Set<String> cacheServices = new HashSet<>();
private HashMap<String, EventListener> subscribeListeners = new HashMap<>();
public NacosWatch(NacosDiscoveryProperties properties) {
this(properties, getTaskScheduler());
}
@ -67,8 +60,21 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl
this.taskScheduler = taskScheduler;
}
/**
* The constructor with {@link NacosDiscoveryProperties} bean and the optional.
* {@link TaskScheduler} bean
* @param properties {@link NacosDiscoveryProperties} bean
* @param taskScheduler the optional {@link TaskScheduler} bean
* @since 2.2.0
*/
public NacosWatch(NacosDiscoveryProperties properties,
ObjectProvider<TaskScheduler> taskScheduler) {
this(properties, taskScheduler.getIfAvailable(NacosWatch::getTaskScheduler));
}
private static ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setBeanName("Nacso-Watch-Task-Scheduler");
taskScheduler.initialize();
return taskScheduler;
}
@ -100,13 +106,17 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl
@Override
public void stop() {
if (this.running.compareAndSet(true, false) && this.watchFuture != null) {
// shutdown current user-thread,
// then the other daemon-threads will terminate automatic.
((ThreadPoolTaskScheduler)this.taskScheduler).shutdown();
this.watchFuture.cancel(true);
}
}
@Override
public boolean isRunning() {
return false;
return this.running.get();
}
@Override

View File

@ -0,0 +1,59 @@
/*
* 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.discovery.actuate.health;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
/**
* The {@link HealthIndicator} for Nacos Discovery.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 2.2.0
* @see HealthIndicator
*/
public class NacosDiscoveryHealthIndicator extends AbstractHealthIndicator {
private final NamingService namingService;
public NacosDiscoveryHealthIndicator(NamingService namingService) {
this.namingService = namingService;
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
// Just return "UP" or "DOWN"
String status = namingService.getServerStatus();
// Set the status to Builder
builder.status(status);
switch (status) {
case "UP":
builder.up();
break;
case "DOWN":
builder.down();
break;
default:
builder.unknown();
break;
}
}
}

View File

@ -18,16 +18,22 @@ package com.alibaba.cloud.nacos.endpoint;
import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.discovery.actuate.health.NacosDiscoveryHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The AutoConfiguration class for Nacos Discovery's Endpoints.
*
* @author xiaojing
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Endpoint.class)
@ -42,4 +48,12 @@ public class NacosDiscoveryEndpointAutoConfiguration {
return new NacosDiscoveryEndpoint(nacosDiscoveryProperties);
}
@Bean
@ConditionalOnEnabledHealthIndicator("nacos-discovery")
public HealthIndicator nacosDiscoveryHealthIndicator(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosDiscoveryHealthIndicator(
nacosDiscoveryProperties.namingServiceInstance());
}
}

View File

@ -28,6 +28,8 @@ import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.util.StringUtils;
import static org.springframework.util.ReflectionUtils.rethrowRuntimeException;
/**
* @author xiaojing
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
@ -66,6 +68,9 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
catch (Exception e) {
log.error("nacos registry, {} register failed...{},", serviceId,
registration.toString(), e);
// rethrow a RuntimeException if the registration is failed.
// issue : https://github.com/alibaba/spring-cloud-alibaba/issues/1132
rethrowRuntimeException(e);
}
}

View File

@ -22,6 +22,9 @@ import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.commons.util.UtilAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import static org.assertj.core.api.Assertions.assertThat;
@ -33,7 +36,12 @@ public class NacosDiscoveryClientConfigurationTest {
private ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class,
NacosDiscoveryClientConfiguration.class));
NacosDiscoveryClientConfiguration.class, this.getClass()));
@Bean
public TaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
@Test
public void testDefaultInitialization() {

View File

@ -0,0 +1,331 @@
/*
* 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;
import java.util.List;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class MockNamingService implements NamingService {
@Override
public void registerInstance(String serviceName, String ip, int port)
throws NacosException {
}
@Override
public void registerInstance(String serviceName, String groupName, String ip,
int port) throws NacosException {
}
@Override
public void registerInstance(String serviceName, String ip, int port,
String clusterName) throws NacosException {
}
@Override
public void registerInstance(String serviceName, String groupName, String ip,
int port, String clusterName) throws NacosException {
}
@Override
public void registerInstance(String serviceName, Instance instance)
throws NacosException {
}
@Override
public void registerInstance(String serviceName, String groupName, Instance instance)
throws NacosException {
}
@Override
public void deregisterInstance(String serviceName, String ip, int port)
throws NacosException {
}
@Override
public void deregisterInstance(String serviceName, String groupName, String ip,
int port) throws NacosException {
}
@Override
public void deregisterInstance(String serviceName, String ip, int port,
String clusterName) throws NacosException {
}
@Override
public void deregisterInstance(String serviceName, String groupName, String ip,
int port, String clusterName) throws NacosException {
}
@Override
public void deregisterInstance(String serviceName, Instance instance)
throws NacosException {
}
@Override
public void deregisterInstance(String serviceName, String groupName,
Instance instance) throws NacosException {
}
@Override
public List<Instance> getAllInstances(String serviceName) throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, String groupName)
throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, boolean subscribe)
throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, String groupName,
boolean subscribe) throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, List<String> clusters)
throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, String groupName,
List<String> clusters) throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, List<String> clusters,
boolean subscribe) throws NacosException {
return null;
}
@Override
public List<Instance> getAllInstances(String serviceName, String groupName,
List<String> clusters, boolean subscribe) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, boolean healthy)
throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, String groupName,
boolean healthy) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, boolean healthy,
boolean subscribe) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, String groupName,
boolean healthy, boolean subscribe) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, List<String> clusters,
boolean healthy) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, String groupName,
List<String> clusters, boolean healthy) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, List<String> clusters,
boolean healthy, boolean subscribe) throws NacosException {
return null;
}
@Override
public List<Instance> selectInstances(String serviceName, String groupName,
List<String> clusters, boolean healthy, boolean subscribe)
throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName) throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, String groupName)
throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, boolean subscribe)
throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, String groupName,
boolean subscribe) throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters)
throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, String groupName,
List<String> clusters) throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters,
boolean subscribe) throws NacosException {
return null;
}
@Override
public Instance selectOneHealthyInstance(String serviceName, String groupName,
List<String> clusters, boolean subscribe) throws NacosException {
return null;
}
@Override
public void subscribe(String serviceName, EventListener listener)
throws NacosException {
}
@Override
public void subscribe(String serviceName, String groupName, EventListener listener)
throws NacosException {
}
@Override
public void subscribe(String serviceName, List<String> clusters,
EventListener listener) throws NacosException {
}
@Override
public void subscribe(String serviceName, String groupName, List<String> clusters,
EventListener listener) throws NacosException {
}
@Override
public void unsubscribe(String serviceName, EventListener listener)
throws NacosException {
}
@Override
public void unsubscribe(String serviceName, String groupName, EventListener listener)
throws NacosException {
}
@Override
public void unsubscribe(String serviceName, List<String> clusters,
EventListener listener) throws NacosException {
}
@Override
public void unsubscribe(String serviceName, String groupName, List<String> clusters,
EventListener listener) throws NacosException {
}
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize)
throws NacosException {
return null;
}
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize,
String groupName) throws NacosException {
return null;
}
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize,
AbstractSelector selector) throws NacosException {
return null;
}
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize,
String groupName, AbstractSelector selector) throws NacosException {
return null;
}
@Override
public List<ServiceInfo> getSubscribeServices() throws NacosException {
return null;
}
@Override
public String getServerStatus() {
return null;
}
}

View File

@ -16,15 +16,25 @@
package com.alibaba.cloud.nacos.registry;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Properties;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration;
import com.alibaba.nacos.api.NacosFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@ -42,7 +52,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author xiaojing
*/
@RunWith(SpringRunner.class)
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosFactory.class })
@SpringBootTest(
classes = NacosAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class,
properties = { "spring.application.name=myTestService1",
@ -62,6 +75,23 @@ public class NacosAutoServiceRegistrationIpNetworkInterfaceTests {
@Autowired
private InetUtils inetUtils;
static {
try {
Method method = PowerMockito.method(NacosFactory.class, "createNamingService",
Properties.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return new MockNamingService();
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void contextLoads() throws Exception {
assertThat(registration).isNotNull();

Some files were not shown because too many files have changed in this diff Show More