Sentinel服务熔断
- sentinel整合ribbon+openFeign+fallback
- Ribbon:
- 提供者9003/9004
- 消费者84
-Feign:
提供者(9003/9004)
1.新建cloudalibaba-provider-payment9003/9004
2.pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2020</artifactId>
<groupId>pers.zhang.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-provider-payment9003</artifactId>
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>pers.zhang.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!-- SpringBoot整合Web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.配置:application.yml
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848
management:
endpoints:
web:
exposure:
include: '*'
4.Controller:
@RestController
public class PaymentController {
@Value("${server.port}")
String serverPort;
public static HashMap<Long, Payment> hashMap = new HashMap<>();
static {
hashMap.put(1L, new Payment(1L, "1111111111111"));
hashMap.put(2L, new Payment(2L, "2222222222222"));
hashMap.put(3L, new Payment(3L, "3333333333333"));
}
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult(200, "from mysql, serverPort: " + serverPort, payment);
return result;
}
}
5.启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class Payment9003 {
public static void main(String[] args) {
SpringApplication.run(Payment9003.class, args);
}
}
消费者84
1.cloudalibaba-consumer-nacos-order84
2.pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud2020</artifactId>
<groupId>pers.zhang.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-consumer-nacos-order84</artifactId>
<dependencies>
<!--SpringCloud openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--SpringCloud ailibaba sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>pers.zhang.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!-- SpringBoot整合Web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.配置:application.yml
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-payment-provider
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getTemplate() {
return new RestTemplate();
}
}
4.Controller:
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback")//没有配置,如果没有配置的话,当出现参数id异常的话,这样会出现error page页面,给客户的体验不好
//@SentinelResource(value = "fallback", fallback = "handlerFallback")//fallback只负责业务异常,像下面的参数id传递4出现的错误,这是业务出现异常
//@SentinelResource(value = "fallback", blockHandler = "blockHandler")//blockHandler只负责sentinel控制台配置违规,不负责业务代码出现的error page,但是可以在控制台设置异常数来避免出现error page
//@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler")//既负责了业务异常,有控制了sentinel控制台配置违规,但是以blockHandler为主
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException 非法参数异常...");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException 空指针异常...");
}
return result;
}
//本例是fallback
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
}
//本例是blockHandler
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
5.启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
测试:
启动nacos、Sentinel、9003、9004以及84微服务:
访问:localhost:84/consumer/fallback/id
id为4,返回非法参数
id为其它,返回空指针
直接返回错误不够友好,所以我们添加fallback方法。
修改@SentinelResource,并添加fallback方法:
重启84,访问:localhost:84/consumer/fallback/id
修改@SentinelResource,只配置blockHandler:
配置降级规则:
重启84,访问:localhost:84/consumer/fallback/id,第一次结果如下:
访问:localhost:84/consumer/fallback/id,(2秒内)第三次结果如下:
触发blockHandler。
同时配置fallback和blockHandler
流控配置:
重启84,快速多次访问(1秒内超过1次):localhost:84/consumer/fallback/1
结论:程序本身无异常,如果触发blockHandler则执行blockHandler。
单次访问:localhost:84/consumer/fallback/4:
快速多次访问(1秒内超过1次):localhost:84/consumer/fallback/4
结论:在未触发blockHandler的情况下,程序出现异常则执行fallback;如果触发blockHandler,优先执行BlockHandler;
异常忽略:
忽略非法参数异常,假如报该异常,不再有fallback方法兜底,失去降级效果
重启84,访问:localhost:84/consumer/fallback/4
整合Feign
对消费者84
1.增加依赖:
<!--SpringCloud openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.application.yml
#激活sentinel对feign的支持
feign:
sentinel:
enabled: true
3.启动类:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients//开启Feign
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
4.新增接口:
@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
5.兜底类:
@Component
public class PaymentFallbackService implements PaymentService {
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(444, "服务降级返回,-----PaymentFallbackService",new Payment(id, "errorSerial"));
}
}
6.Controller:
//==================OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
{
return paymentService.paymentSQL(id);
}
7.测试:启动nacos,启动sentinel,启动9003、9004和84微服务:
访问:localhost:84/consumer/paymentSQL/1
测试84调用9003/9004,此时故意关闭9003/9004微服务提供者,看84消费侧自动降级,不会被耗死: