当前位置:网站首页>Sentinel service fusing practice (sentinel integration ribbon + openfeign + fallback)

Sentinel service fusing practice (sentinel integration ribbon + openfeign + fallback)

2022-04-23 18:38:00 Hua Weiyun

@toc

Source code address :gitee Warehouse address

1、Ribbon series

1.1 start-up nacos and sentinel

image-20220416234815852

image-20220416234829591

1.2 Create two service providers payment9003 and payment9004

   newly build cloudalibaba-provider-payment9003/9004 The two do the same thing

image-20220416235040599

   because 9003 and 9004 Except for the port number , Almost the same as others , This is just a demonstration 9003 How to build ports .

  pom.xml

  <dependencies>        <!--SpringCloud ailibaba nacos -->        <dependency>            <groupId>com.alibaba.cloud</groupId>            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>        </dependency>        <dependency><!--  Introduce your own definition of api General package , have access to Payment payment Entity -->            <groupId>com.atguigu.springcloud</groupId>            <artifactId>cloud-api-commons</artifactId>            <version>${project.version}</version>        </dependency>        <!-- SpringBoot Integrate Web Components  -->        <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>        <!-- Everyday use jar Package configuration -->        <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>

  application.yml

 server:  port: 9003spring:  application:    name: nacos-payment-provider  cloud:    nacos:      discovery:        server-addr: localhost:8848 # To configure Nacos Address management:  endpoints:    web:      exposure:        include: '*'

   Remember to modify different port numbers

   Main startup class

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

   Business class

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

   This is for testing , I didn't connect to the database , Simulated several data , The effect is the same .

   Start the service and test whether the business class is normal :http://localhost:9003/paymentSQL/1

image-20220416235755999

  http://localhost:9004/paymentSQL/1

image-20220416235931322

   The two service providers were successfully built .

1.3 Build service consumers order84

1.3.1 Basic module construction

   newly build cloudalibaba-consumer-nacos-order84

image-20220417000034209

  pom.xml

<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>        <!--  Introduce your own definition of api General package , have access to Payment payment Entity -->        <dependency>            <groupId>com.atguigu.springcloud</groupId>            <artifactId>cloud-api-commons</artifactId>            <version>${project.version}</version>        </dependency>        <!-- SpringBoot Integrate Web Components  -->        <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>        <!-- Everyday use jar Package configuration -->        <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>

  application.yml

server:  port: 84spring:  application:    name: nacos-order-consumer  cloud:    nacos:      discovery:        server-addr: localhost:8848    sentinel:      transport:        # To configure Sentinel dashboard Address         dashboard: localhost:8080        # Default 8719 port , If it is occupied, it will be automatically transferred from 8719 Start in sequence +1 scanning , Until the unoccupied port is found         port: 8719# The name of the micro service the consumer is going to visit ( Successfully registered nacos Micro service providers of )service-url:  nacos-user-service: http://nacos-payment-provider

   Main startup class

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

   Business class

   Load balancing configuration :

@Configurationpublic class ApplicationContextConfig{    @Bean    @LoadBalanced    public RestTemplate getRestTemplate()    {        return new RestTemplate();    }}

  CircleBreakerController

@RestController@Slf4jpublic 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, Illegal parameter exception ....");        }else if (result.getData() == null) {            throw new NullPointerException ("NullPointerException, The ID There is no corresponding record , Null pointer exception ");        }        return result;    }}

   The above code is in id=1/2/3 It's normal ,id=4 Throw when IllegalArgumentException abnormal , Greater than 4 A null pointer exception is thrown when the .

   The purpose of the test here :fallback The tube runs abnormally ,blockHandler Pipe configuration violation

   There is no configuration above @SentinelResource, Will directly return to the customer error page , Very unfriendly .

1.3.2 Configure only fallback

  @RequestMapping("/consumer/fallback/{id}")// @SentinelResource(value = "fallback")    @SentinelResource(value = "fallback",fallback = "handlerFallback")    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, Illegal parameter exception ....");        }else if (result.getData() == null) {            throw new NullPointerException ("NullPointerException, The ID There is no corresponding record , Null pointer exception ");        }        return result;    }// //fallback Method     public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {        Payment payment = new Payment(id,"null");        return new CommonResult<>(444," The bottom of the bag is abnormal handlerFallback,exception Content  "+e.getMessage(),payment);    }

   Be careful : There is no configuration sentinel.

   Access test :

  http://localhost:84/consumer/fallback/1

image-20220417000937192

  http://localhost:84/consumer/fallback/4

image-20220417000956764

  http://localhost:84/consumer/fallback/5

image-20220417001012956

   At this point, the specified fallback, Friendly to callers .

1.3.3 Configure only blockHandler

   @RequestMapping("/consumer/fallback/{id}")    @SentinelResource(value = "fallback",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, Illegal parameter exception ....");        }else if (result.getData() == null) {            throw new NullPointerException ("NullPointerException, The ID There is no corresponding record , Null pointer exception ");        }        return result;    }// //fallback Method // public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {// Payment payment = new Payment(id,"null");// return new CommonResult<>(444," The bottom of the bag is abnormal handlerFallback,exception Content  "+e.getMessage(),payment);// }//    //blockHandler    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {        Payment payment = new Payment(id,"null");        return new CommonResult<>(445,"blockHandler-sentinel Current limiting , No such flow : blockException "+blockException.getMessage(),payment);    }

   Here you need to configure sentinel

image-20220417001348466

image-20220417001420614

   Abnormally more than 2 Later , The circuit breaker is on , Power off trip , The system is protected .

image-20220417001915291

   test :

   First visit :http://localhost:84/consumer/fallback/4

image-20220417002558240

   I found that I still gave a error page , Be careful , What we configured above is that when the dissimilarity constant is greater than 2 The circuit breaker will not open until .

   A few more visits .

image-20220417002701266

   You can see , It's restricted .

1.3.4 fallback and blockHandler All configured

@RequestMapping("/consumer/fallback/{id}")// @SentinelResource(value = "fallback")// @SentinelResource(value = "fallback",fallback = "handlerFallback")// @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler Responsible for sentinel The degraded current limit configured inside     @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, Illegal parameter exception ....");        }else if (result.getData() == null) {            throw new NullPointerException ("NullPointerException, The ID There is no corresponding record , Null pointer exception ");        }        return result;    }    //fallback Method     public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {        Payment payment = new Payment(id,"null");        return new CommonResult<>(444," The bottom of the bag is abnormal handlerFallback,exception Content  "+e.getMessage(),payment);    }// //blockHandler    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {        Payment payment = new Payment(id,"null");        return new CommonResult<>(445,"blockHandler-sentinel Current limiting , No such flow : blockException "+blockException.getMessage(),payment);    }

image-20220417002941407

   You need to configure Sentinel Flow control

image-20220417003808238

   Configuration interpretation :1 Seconds can only be processed 1 A request , Otherwise, the current will be limited .

   We test ,http://localhost:84/consumer/fallback/4, Frequent access always triggers current limiting degradation .

image-20220417004423470

  == Conclusion : if blockHandler and fallback It's all configured , It is degraded by current limiting and thrown BlockException It will only enter blockHandler Processing logic .==

1.3.5 Ignore property configuration

image-20220417004520079

   We give @SentinelResource Annotation add configuration exceptionsToIgnore = {IllegalArgumentException.class}

   At this point, if we pass the parameters id=4, Will ignore IllegalArgumentException abnormal .

   Visit again at this time :http://localhost:84/consumer/fallback/4

image-20220417004715815

   The exception is printed to the foreground , Not user friendly .

2、Feign series

   Our general service invocation uses OpenFeign Of , stay FeignClient We will deal with it in a unified way fallback

2.1 modify 84 modular .

   In serving consumers (order84) Introduced in the module OpenFeign

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

image-20220417005307090

2.2 The configuration file application.yml Active in Sentinel Yes Feign Support for

image-20220417005354023

2.3 Business class

   belt @FeignClient Annotated business interface

/** *  Use  fallback  The method is unable to obtain exception information , *  If you want to get exception information , have access to  fallbackFactory Parameters  */@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)// Close... In call 9003 Service providers public interface PaymentService{    @GetMapping(value = "/paymentSQL/{id}")    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);}

  fallback = PaymentFallbackService.class Implementation class of

@Componentpublic class PaymentFallbackService implements PaymentService{    @Override    public CommonResult<Payment> paymentSQL(Long id)    {        return new CommonResult<>(44444444," Service degradation returns ,-------PaymentFallbackService",new Payment(id, "errorSerial......"));    }}

  Controller:

image-20220417014201295

   Main startup class

   add to @EnableFeignClients start-up Feign The function of

image-20220417014252214

   Access test :http://localhost:84/consumer/paymentSQL/1

image-20220417014508218

   test 84 call 9003, At this time, it is deliberately closed 9003 Micro service providers , see 84 The consumer side is automatically downgraded , Will not be consumed

   close 9003 Service provider

image-20220417014536417

   Revisit http://localhost:84/consumer/paymentSQL/1

image-20220417014600726

   You can see , The service has been degraded . What we return is that we are FeignClient Interface falback.

3、 Comparison of three fuse frames

image-20220417014729090

   Here we are ,Sentinel The testing of integrated services is over , About Sentinel There are too many current limiting configurations , It's hard to elaborate , You'd better check the official website . I also posted a current limiting article last year , Fuck me SpringCloud Alibaba In the column

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231836021915.html