update examples

pull/1195/head^2
fangjian0423 5 years ago
parent 97528396fd
commit 57e3059d8d

@ -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>

@ -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

@ -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

@ -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

@ -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

@ -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";
}
}

@ -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;
}
}

@ -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

@ -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
}
]

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

@ -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>

@ -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

@ -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.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
@ -24,6 +28,10 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

@ -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")

@ -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

@ -12,6 +12,10 @@
<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>

@ -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

@ -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>

@ -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

@ -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");
}

@ -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());
};
}
}

@ -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");
}));
}
}

Loading…
Cancel
Save