天天看點

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷

整個項目請看gitee:https://gitee.com/xwb1056481167/spring-cloud

sentinel的安裝和項目內建:https://blog.csdn.net/www1056481167/article/details/113679945

相關項目Ribbon:cloudalibaba-provider-payment9003,cloudalibaba-provider-payment9004

Feign:cloudalibaba-consumer-nacos-order84

nacos的配置安裝請到:https://blog.csdn.net/www1056481167/article/details/113612177檢視

Ribbon熔斷

服務提供者9003,9004

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷

1、建立cloudalibaba-provider-payment9003(9004下同)

<!-- alibaba nacos 服務端 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 引入api 公共包 -->
<dependency>
    <groupId>org.xwb.springcloud</groupId>
    <artifactId>cloud-api-commons</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<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>
           

2、yml配置

server:
  port: 9002
spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos位址
management:
  endpoints:
    web:
      exposure:
        include:  '*'
           

3、主啟動類

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain9002.class, args);
    }
}
           

4、controller

@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, "210374208734KJEWFKW0U20sklfw0uor023u4"));
        hashMap.put(2l, new Payment(2L, "3498hofwsefhls93984rfhseohf2890343rwe"));
        hashMap.put(3l, new Payment(3L, "09snkjdfhjoiwhefdsnfjkhweo5235wefhwee"));
    }
    @GetMapping("/paymentSQL/{id}")
    public CommonResult paymentSQL(@PathVariable("id") Long id) {
        Payment payment = hashMap.get(id);
        CommonResult<Payment> result = new CommonResult<>(200, "from mysql,serverPort" + serverPort, payment);
        return result;
    }
}
           

服務消費者cloudalibaba-consumer-nacos-order84

1、pom.xml

<!-- alibaba sentinel -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- alibaba nacos -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- alibaba nacos sentinel -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
           

2、yml

server:
  port: 84
spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        # 預設8719端口,假如被占用會自動從8719開始一次+1稻苗,知道找到違背占用的端口
        port: 8719
# 消費者将要去通路的服務名稱(注冊進nacos的服務提供者名稱)
service-url:
  nacos-user-service: http://nacos-payment-provider
           

3、主啟動類

@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain84.class, args);
    }
}
           

4、負載均衡

@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getLoadBalanced() {
        return new RestTemplate();
    }
}
           

5、controller

@Slf4j
@RestController
public class CirleBreakerController {
    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);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法參數異常");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,該id沒有對應的記錄,空指針異常");
        }
        return result;
    }
    public CommonResult<Payment> fallback(BlockException blockException) {
        return new CommonResult<Payment>(444, "", null);
    }
}
           

測試

啟動順序nacos,sentinel,9003,9004,最後啟動調用方84

1、@SentinelResource(value = "fallback", fallback = "handlerFallback") fallback

@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback", fallback = "handlerFallback")//隻負責業務異常
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,該id沒有對應的記錄,空指針異常");
    }
    return result;
}
public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
    Payment payment = new Payment(id, null);
    return new CommonResult(444, "兜底異常handlerFallback,exception内容" + e.getMessage(), payment);
}
           

測試結果

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷

2、測試@SentinelResource(value = "fallback", blockHandler = "handlerFallback")blockHandler 。blockHandler隻負責sentinel控制台的配置

@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);
    if (id == 4) {
        throw new IllegalArgumentException("IllegalArgumentException,非法參數異常");
    } else if (result.getData() == null) {
        throw new NullPointerException("NullPointerException,該id沒有對應的記錄,空指針異常");
    }
    return result;
}
public CommonResult blockHandler(@PathVariable("id")Long id, BlockException blockException){
    Payment payment=new Payment(id,null);
    return new CommonResult(445,"blockHandler-sentinel限流,無此流水,blockException:"+blockException.getMessage(),payment);
}
           

測試結果(第一次異常頁面,連續一秒内重新整理超過2次,出現sentinel的限流規則)

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷

3、如果fallback和blockHandler都配置了,該怎麼執行

@RequestMapping("/consumer/fallback/{id}")
@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);
    if (id == 4) {
        throw new IllegalArgumentException("IllegalArgumentException,非法參數異常");
    } else if (result.getData() == null) {
        throw new NullPointerException("NullPointerException,該id沒有對應的記錄,空指針異常");
    }
    return result;
}
public CommonResult blockHandler(@PathVariable("id")Long id, BlockException blockException){
    Payment payment=new Payment(id,null);
    return new CommonResult(445,"blockHandler-sentinel限流,無此流水,blockException:"+blockException.getMessage(),payment);
}
public CommonResult handlerFallback(@PathVariable("id") Long id, Throwable e) {
    Payment payment = new Payment(id, null);
    return new CommonResult(444, "兜底異常handlerFallback,exception内容" + e.getMessage(), payment);
}
           

結果(重新整理浏覽器1秒超過2次)

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷
若blockHandler和fallback都配置了,則被限流降級而抛出BlockException時隻會進入blockHandler處理邏輯

exceptionsToIgnore

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷

Fenign熔斷

修改cloudalibaba-consumer-nacos-order84使用feign調用

1、pom.xml

<!-- openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
           

2、aplication.yml

# 激活sentinel對feign的支援
feign:
  sentinel:
    enabled: true
           

3、開啟對feign的支援@EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderNacosMain84 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain84.class, args);
    }
}
           

4、openFeign提供接口調用OpenClient

@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class)
public interface PaymentService {
    @GetMapping("/paymentSQL/{id}")
    public CommonResult paymentSQL(@PathVariable("id") Long id);
}
@Component
public class PaymentFallbackService implements PaymentService {
    @Override
    public CommonResult paymentSQL(Long id) {
        return new CommonResult<Payment>(4444,"",new Payment(id,"errorSerial"));
    }
}
           

測試

啟動nacos,sentinel,9003,9004,84,通路一下位址

1、 http://localhost:84/consumer/paymentSQL/1  通路結果(正常通路)

2、此時關閉9003,或者9004,再次重新整理通路如下效果

Sentinel熔斷Feign和RibbonRibbon熔斷Fenign熔斷

會發現調用失敗,服務自動降級

繼續閱讀