当前位置:网站首页>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
边栏推荐
- Multifunctional toolbox wechat applet source code
- listener.log
- Test questions of daily safety network (February 2024)
- Domestic GD chip can filter
- 14个py小游戏源代码分享第二弹
- os_ authent_ Prefix
- In win10 system, all programs run as administrator by default
- CANopen STM32 transplantation
- CISSP certified daily knowledge points (April 15, 2022)
- QT error: no matching member function for call to ‘connect‘
猜你喜欢
解决:cnpm : 无法加载文件 ...\cnpm.ps1,因为在此系统上禁止运行脚本
logstash 7. There is a time problem in X. the difference between @ timestamp and local time is 8 hours
Setting up keil environment of GD single chip microcomputer
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
ESP32 LVGL8. 1 - arc (arc 19)
【ACM】376. Swing sequence
Quantexa CDI(场景决策智能)Syneo平台介绍
CANopen STM32 transplantation
实战业务优化方案总结---主目录---持续更新
Kettle paoding jieniu Chapter 17 text file output
随机推荐
[mathematical modeling] - analytic hierarchy process (AHP)
机器学习实战 -朴素贝叶斯
Daily CISSP certification common mistakes (April 13, 2022)
深入理解 Golang 中的 new 和 make 是什么, 差异在哪?
CANopen usage method and main parameters of object dictionary
After CANopen starts PDO timing transmission, the heartbeat frame time is wrong, PDO is delayed, and CANopen time axis is disordered
Notepad + + replaces tabs with spaces
多功能工具箱微信小程序源码
Can filter
数据库上机实验四(数据完整性与存储过程)
Quantexa CDI(场景决策智能)Syneo平台介绍
ESP32 LVGL8. 1 - label (style 14)
In win10 system, all programs run as administrator by default
How to restore MySQL database after win10 system is reinstalled (mysql-8.0.26-winx64. Zip)
Teach you to quickly rename folder names in a few simple steps
Jeecg boot microservice architecture
ESP32 LVGL8. 1 - BTN button (BTN 15)
Excel intercept text
Use of regular expressions in QT
ctfshow-web362(SSTI)