当前位置:网站首页>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


1.2 Create two service providers payment9003 and payment9004
newly build cloudalibaba-provider-payment9003/9004 The two do the same thing

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

http://localhost:9004/paymentSQL/1

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

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

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

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

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


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

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

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 .

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

You need to configure Sentinel Flow control

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

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

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

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>

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

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:

Main startup class
add to @EnableFeignClients start-up Feign The function of

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

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

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

You can see , The service has been degraded . What we return is that we are FeignClient Interface falback.
3、 Comparison of three fuse frames

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
边栏推荐
- K210串口通信
- listener.log
- How to restore MySQL database after win10 system is reinstalled (mysql-8.0.26-winx64. Zip)
- Implementation of TCP UDP communication with golang language
- Summary of actual business optimization scheme - main directory - continuous update
- Daily CISSP certification common mistakes (April 14, 2022)
- listener. log
- CISSP certified daily knowledge points (April 19, 2022)
- About the operation of unit file reading (I)
- Imx6 debugging LVDS screen technical notes
猜你喜欢

ESP32 LVGL8. 1 - arc (arc 19)

Solution to Chinese garbled code after reg file is imported into the registry

Halo 开源项目学习(七):缓存机制

With the use of qchart, the final UI interface can be realized. The control of qweight can be added and promoted to a user-defined class. Only the class needs to be promoted to realize the coordinate

Excel intercept text

QT tablewidget insert qcombobox drop-down box

Notepad + + replaces tabs with spaces

教你用简单几个步骤快速重命名文件夹名

Multifunctional toolbox wechat applet source code

How to restore MySQL database after win10 system is reinstalled (mysql-8.0.26-winx64. Zip)
随机推荐
ESP32 LVGL8. 1 - arc (arc 19)
STM32 learning record 0008 - GPIO things 1
使用晨曦记账本,分析某个时间段每个账户收支结余
硬核解析Promise对象(这七个必会的常用API和七个关键问题你都了解吗?)
listener.log
Query the logistics update quantity according to the express order number
Druid SQL和Security在美团点评的实践
Stm32mp157 wm8960 audio driver debugging notes
Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha
After CANopen starts PDO timing transmission, the heartbeat frame time is wrong, PDO is delayed, and CANopen time axis is disordered
Nacos作为服务注册中心
机器学习实战 -朴素贝叶斯
Ctfshow - web362 (ssti)
Seata处理分布式事务
CISSP certified daily knowledge points (April 15, 2022)
Chondroitin sulfate in vitreous
listener. log
Daily CISSP certification common mistakes (April 15, 2022)
函数递归以及趣味问题的解决
解决:cnpm : 無法加載文件 ...\cnpm.ps1,因為在此系統上禁止運行脚本