当前位置:网站首页>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
边栏推荐
- Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha
- 【数学建模】—— 层次分析法(AHP)
- Usage of functions decode() and replace() in SQL
- 深入理解 Golang 中的 new 和 make 是什么, 差异在哪?
- MVVM模型
- SQL database syntax learning notes
- Keil RVMDK compiled data type
- 机器学习实战 -朴素贝叶斯
- kettle庖丁解牛第17篇之文本文件输出
- CISSP certified daily knowledge points (April 15, 2022)
猜你喜欢
CANopen STM32 transplantation
[popular science] CRC verification (I) what is CRC verification?
listener. log
Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha
Halo open source project learning (VII): caching mechanism
使用 bitnami/postgresql-repmgr 镜像快速设置 PostgreSQL HA
Function recursion and solving interesting problems
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
机器学习理论之(7):核函数 Kernels —— 一种帮助 SVM 实现非线性化决策边界的方式
kettle庖丁解牛第17篇之文本文件输出
随机推荐
使用 bitnami/postgresql-repmgr 镜像快速设置 PostgreSQL HA
Jeecg boot microservice architecture
C language simulates entering and leaving the stack, first in first out, first in first out, shared memory
深入理解 Golang 中的 new 和 make 是什么, 差异在哪?
Cygwin64 right click to add menu, and open cygwin64 here
listener.log
ctfshow-web362(SSTI)
ctfshow-web361(SSTI)
Ctfshow - web362 (ssti)
Iptables - L executes slowly
Error reported when running tensorboard: valueerror: duplicate plugins for name projector, solution
ESP32 LVGL8. 1 - input devices (input devices 18)
Quantexa CDI(场景决策智能)Syneo平台介绍
Daily CISSP certification common mistakes (April 19, 2022)
Multifunctional toolbox wechat applet source code
实战业务优化方案总结---主目录---持续更新
Linux installs MySQL in RPM (super simple)
硬核解析Promise對象(這七個必會的常用API和七個關鍵問題你都了解嗎?)
22年字节跳动飞书人力套件三面面经
【科普】CRC校验(一)什么是CRC校验?