1.Sentinel整合Ribbon
1.1.Sentinel服务熔断Ribbon环境准备
sentinel整合ribbon+openFeign+fallback
Ribbon系列
- 启动nacos和sentinel
- 提供者9003/9004
- 消费者84
1.1.1提供者9003/9004
新建cloudalibaba-provider-payment9003/9004,两个一样的做法
POM
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</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>
<!--日常通用组件-->
<dependency>
<groupId>com.tianxia</groupId>
<artifactId>api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
YML,记得修改不同的端口号
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
主启动
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* 启动类
* @author liqb
* @date 2023-05-26 18:17
**/
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class, args);
}
}
业务类
import com.tianxia.alibaba.entity.CommonResult;
import com.tianxia.alibaba.entity.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
/**
* 启动类
* @author liqb
* @date 2023-05-26 18:17
**/
@RestController
public class PaymentController {
@Value("${server.port}")
private String serverPort;
// 模拟数据库
public static HashMap<Long, Payment> hashMap = new HashMap<>();
static {
hashMap.put(1L, new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
hashMap.put(2L, new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
hashMap.put(3L, new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
}
@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;
}
}
**测试地址 **
http://localhost:9003/paymentSQL/1
1.1.2.消费者84
新建cloudalibaba-consumer-nacos-order84
POM
<dependencies>
<!--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>
<!-- 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>
<!--日常通用组件-->
<dependency>
<groupId>com.tianxia</groupId>
<artifactId>api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
YML
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
# 激活Sentinel对Feign的支持
feign:
sentinel:
enabled: true
主启动
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author liqb
* @date 2023-05-26 23:45
**/
@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
业务类
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.tianxia.alibaba.entity.CommonResult;
import com.tianxia.alibaba.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* 业务类
* @author liqb
* @date 2023-05-26 23:47
*/
@Slf4j
@RestController
public class CircleBreakerController {
@Value(value = "${service-url.nacos-user-service}")
public String SERVICE_URL;
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback") //没有配置
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
}
配置类ApplicationContextConfig
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* 配置类
* @author liqb
* @date 2023-05-26 23:46
**/
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
修改后请重启微服务
- 热部署对java代码级生效及时
- 对@SentinelResource注解内属性,有时效果不好
目的
- fallback管运行异常
- blockHandler管配置违规
测试地址 - http://localhost:84/consumer/fallback/1
没有任何配置
只配置fallback
只配置blockHandler
fallback和blockHandler都配置
忽略属性
1.2.Sentinel服务熔断无配置
没有任何配置 - 给用户error页面,不友好
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback") // 没有配置
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
}
1.3.Sentinel服务熔断只配置fallback
fallback只负责业务异常
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
/**
* sentinel熔断
* @author liqb
* @date 2023-05-27 10:17
* @return
*/
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") // 没有配置
@SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback只负责业务异常
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
/**
* 异常兜底方法 - 本例是fallback
* @author liqb
* @date 2023-05-27 10:17
* @return
*/
public CommonResult<Payment> handlerFallback(@PathVariable Long id, Throwable e){
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 " + e.getMessage(), payment);
}
}
测试地址 - http://localhost:84/consumer/fallback/4
1.4.Sentinel服务熔断只配置blockHandler
blockHandler只负责sentinel控制台配置违规
@Slf4j
@RestController
public class CircleBreakerController {
@Value(value = "${service-url.nacos-user-service}")
public String SERVICE_URL;
@Resource
private RestTemplate restTemplate;
/**
* sentinel熔断
* @author liqb
* @date 2023-05-27 10:17
* @return
*/
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") // 没有配置
// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback只负责业务异常
@SentinelResource(value = "fallback",blockHandler = "blockHandler") // blockHandler只负责sentinel控制台配违规
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
/**
* sentinel配违规兜底方法 - 本例是blockHandler
* @author liqb
* @date 2023-05-27 10:23
* @return
*/
public CommonResult<Payment> blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445, "blockHandler-sentinel限流,无此流水: blockException " + blockException.getMessage(), payment);
}
}
1.5.Sentinel服务熔断fallback和blockHandler都配置
若blockHandler和fallback 都进行了配置,则被限流降级而抛出BlockException时只会进入blockHandler处理逻辑。
/**
* 业务类
* @author liqb
* @date 2023-05-26 23:47
*/
@Slf4j
@RestController
public class CircleBreakerController {
@Value(value = "${service-url.nacos-user-service}")
public String SERVICE_URL;
@Resource
private RestTemplate restTemplate;
/**
* sentinel熔断
* @author liqb
* @date 2023-05-27 10:17
* @return
*/
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") // 没有配置
// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback只负责业务异常
// @SentinelResource(value = "fallback", blockHandler = "blockHandler") // blockHandler只负责sentinel控制台配违规
@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler")
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
/**
* 异常兜底方法 - 本例是fallback
* @author liqb
* @date 2023-05-27 10:17
* @return
*/
public CommonResult<Payment> handlerFallback(@PathVariable Long id, Throwable e){
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 " + e.getMessage(), payment);
}
/**
* sentinel配违规兜底方法 - 本例是blockHandler
* @author liqb
* @date 2023-05-27 10:23
* @return
*/
public CommonResult<Payment> blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445, "blockHandler-sentinel限流,无此流水: blockException " + blockException.getMessage(), payment);
}
}
1.6.Sentinel服务熔断exceptionsToIgnore忽略异常
exceptionsToIgnore:忽略指定异常,即这些异常不用兜底方法处理。
/**
* sentinel熔断
* @author liqb
* @date 2023-05-27 10:17
* @return
*/
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") // 没有配置
// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback只负责业务异常
// @SentinelResource(value = "fallback", blockHandler = "blockHandler") // blockHandler只负责sentinel控制台配违规
// @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler")
@SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class})
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
2.Sentinel整合Feign
修改84模块
- 84消费者调用提供者9003
- Feign组件一般是消费侧
POM
<!--SpringCloud openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
YML
# 激活Sentinel对Feign的支持
feign:
sentinel:
enabled: true
业务类
带@Feignclient注解的业务接口,fallback = PaymentFallbackService.class
import com.tianxia.alibaba.entity.CommonResult;
import com.tianxia.alibaba.entity.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* 服务类
* @author liqb
* @date 2023-05-27 11:13
*/
@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
import com.tianxia.alibaba.entity.CommonResult;
import com.tianxia.alibaba.entity.Payment;
import org.springframework.stereotype.Component;
/**
* 兜底方法
* @author liqb
* @date 2023-05-27 11:02
*/
@Component
public class PaymentFallbackService implements PaymentService {
/**
* 微服务调用异常兜底方法
* @author liqb
* @date 2023-05-27 11:03
* @return
*/
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService", new Payment(id,"errorSerial"));
}
}
Controller
/**
* openfeign调用
* @author liqb
* @date 2023-05-27 11:19
* @return
*/
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
return paymentService.paymentSQL(id);
}
主启动
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* 启动类
* @author liqb
* @date 2023-05-26 23:45
**/
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients(basePackages="com.tianxia.alibaba.minisevice") // <------------------------
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
测试 - http://localhost:84/consumer/paymentSQL/1
测试84调用9003,此时故意关闭9003微服务提供者,84消费侧自动降级,不会被耗死。
3.熔断框架比较
- | Sentinel | Hystrix | resilience4j |
---|---|---|---|
隔离策略 | 信号量隔离(并发线程数限流) | 线程池隔商/信号量隔离 | 信号量隔离 |
熔断降级策略 | 基于响应时间、异常比率、异常数 | 基于异常比率 | 基于异常比率、响应时间 |
实时统计实现 | 滑动窗口(LeapArray) | 滑动窗口(基于RxJava) | Ring Bit Buffer |
动态规则配置 | 支持多种数据源 | 支持多种数据源 | 有限支持 |
扩展性 | 多个扩展点 | 插件的形式 | 接口的形式 |
基于注解的支持 | 支持 | 支持 | 支持 |
限流 | 基于QPS,支持基于调用关系的限流 | 有限的支持 | Rate Limiter |
流量整形 | 支持预热模式匀速器模式、预热排队模式 | 不支持 | 简单的Rate Limiter模式 |
系统自适应保护 | 支持 | 不支持 | 不支持 |
控制台 | 提供开箱即用的控制台,可配置规则、查看秒级监控,机器发观等 | 简单的监控查看 | 不提供控制台,可对接其它监控系统 |