当前位置:网站首页>Sentinel annotation support - @sentinelresource usage details
Sentinel annotation support - @sentinelresource usage details
2022-06-11 06:18:00 【Milo_】
Hello, Hello everyone , This is Milo , Let's take you to know about Sentinel in @SentinelResource How to use , This article mainly introduces the following contents to you
List of articles
Due to the limited level of the author , The article is unavoidably improper , Please give me your advice and suggestions
At present, the official account has no message function , How to find me ? You can pay attention to my official account. : Today, Java, The background to reply " Add group " You can get my personal wechat , At the same time, we can also pull everyone into the exchange group to exchange and learn together
@SentinelResource annotation
Be careful : Annotation embedding is not supported private Method .
Note introduction
@SentinelResource Used to define resources , And provides optional exception handling and fallback Configuration item .
@SentinelResource The annotation contains the following properties :
value: Resource name , Required ( Can't be empty )entryType:entrytype , optional ( The default isEntryType.OUT)blockHandler/blockHandlerClass:blockHandlerDeal withBlockExceptionThe function name of , optional .blockHandlerThe function access range needs to bepublic, Return type needs to match the original method , The parameter type needs to match the original method and add an extra parameter , The type isBlockException.blockHandlerFunction default needs to be in the same class as the original method . If you want to use functions of other classes , You can specifyblockHandlerClassFor the corresponding classClassobject , Note that the corresponding function must bestaticfunction , Otherwise, it cannot be parsed .fallback/fallbackClass:fallbackThe name of the function , optional , Used to provide... When an exception is thrownfallbackProcessing logic .fallbackFunctions can be used for all types of exceptions ( exceptexceptionsToIgnoreThe types of exceptions excluded ) To deal with .fallbackFunction signature and location requirements :- The return value type must be the same as the return value type of the original function ;
- Method parameter list should be consistent with the original function , Or maybe one more
ThrowableThe parameter of type is used to receive the corresponding exception . fallbackFunction default needs to be in the same class as the original method . If you want to use functions of other classes , You can specifyfallbackClassFor the corresponding classClassobject , Note that the corresponding function must bestaticfunction , Otherwise, it cannot be parsed .
defaultFallback(since 1.6.0): defaultfallbackThe name of the function , optional , Usually used for general purposefallbackLogic ( It can be used in many services or methods ). DefaultfallbackFunctions can be used for all types of exceptions ( exceptexceptionsToIgnoreThe types of exceptions excluded ) To deal with . If you configurefallbackanddefaultFallback, onlyfallbackWill take effect .defaultFallbackFunction signature requirements :- The return value type must be the same as the return value type of the original function ;
- Method parameter list needs to be empty , Or maybe one more
ThrowableThe parameter of type is used to receive the corresponding exception . - defaultFallback Function default needs to be in the same class as the original method . If you want to use functions of other classes , You can specify
fallbackClassFor the corresponding classClassobject , Note that the corresponding function must be static function , Otherwise, it cannot be parsed .
exceptionsToIgnore(since 1.6.0): Used to specify which exceptions are excluded , It will not be included in the abnormal statistics , And will not enterfallbackIn the logic , But will throw out as is .
1.8.0 Version start ,defaultFallback Support configuration at the class level .
notes :1.6.0 Previous version fallback Function is only for degraded exceptions (
DegradeException) To deal with , Can't handle business exceptions .
Specially , if blockHandler and fallback It's all configured , It is degraded by current limiting and thrown BlockException It will only enter blockHandler Processing logic . If not configured blockHandler、fallback and defaultFallback, When it is degraded by current limiting, it will BlockException Direct selling ( If the method itself is undefined throws BlockException Will be JVM Packaging layer UndeclaredThrowableException).
Annotations use
Code writing

SentinelController
/** * annotation @SentinelResource Study * @author Milo Lee * @date 2021-03-23 11:33 */
@RestController
public class SentinelController {
@Autowired
private ISentinelService service;
@GetMapping(value = "/hello/{s}")
public String apiHello(@PathVariable long s) {
return service.hello(s);
}
}
ISentinelService
/** * @author Milo Lee * @date 2021-03-23 11:34 */
public interface ISentinelService {
String hello (long s);
}
SentinelServiceImpl
/** * @author Milo Lee * @date 2021-03-23 11:34 */
@Service
@Slf4j
public class SentinelServiceImpl implements ISentinelService {
/** *Sentinel Provides @SentinelResource Annotations are used to define resources * @param s * @return */
@Override
//value: Resource name , Required ( Can't be empty )
//blockHandler Deal with BlockException The function name of
//fallback Used to provide... When an exception is thrown fallback Processing logic
@SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
public String hello(long s) {
log.error("hello:{}",s);
return String.format("Hello at %d", s);
}
// Fallback function , The signature of the function is the same as the original function or add one Throwable Parameters of type .
public String helloFallback(long s) {
log.error("helloFallback:{}",s);
return String.format("Halooooo %d", s);
}
// Block Exception handling functions , One more parameter at the end BlockException, The rest is consistent with the original function .
public String exceptionHandler(long s, BlockException ex) {
// Do some log here.
log.error("exceptionHandler:{}",s);
ex.printStackTrace();
return "Oops, error occurred at " + s;
}
}
Launch our project , Visit our test methods ( Refresh several times , Look at the control panel )


Current limiting test
Now we're looking for our resources :hello Configure a flow control rule , The configuration steps are shown in the figure below

Configuration is successful :

Back to our page , Quickly refresh the page , We will find the following information occasionally , It shows that our configured flow control rules are successfully intercepted

Console log :

According to what we learned above , If it exceeds our configuration QPS, The code will throw BlockException abnormal , Why is it in the code FlowException, By looking at the source code, we will find FlowException It's actually BlockException The children of
After the above test , We found that the successful implementation of annotation development achieved current limiting
Degradation test
Before the downgrade test , We need to modify our code
front :
@SentinelResource(value = "hello", blockHandler = "exceptionHandler", fallback = "helloFallback")
after :
@SentinelResource(value = "hello", fallback = "helloFallback")
Configure flow control rules


Configure degradation rules :


The test method
According to our configuration rules , If qps>1, I'm sure we'll start BlockException, At this time, the degradation rule judges that the exception ratio exceeds the number of requests 20%, Will automatically trigger a downgrade ;

My click rate : uniform ------ Fast
Look at the logs here , When I started clicking at a constant speed , Did not enter helloFallback Method , When I click quickly , Into the helloFallback Method , It means that the demotion rule will take effect at this time , Trigger downgrade , Enter the callback function helloFallback in ;

Today's sharing is here , Thank you.
边栏推荐
- Servlet
- Ethical discussion on reptile Technology
- QT socket设置连接超时时间
- What do you need to know about Amazon evaluation?
- autojs,读取一行删除一行,停止自己外的脚本
- Do you know the functions of getbit and setbit in redis?
- Cocoatouch framework and building application interface
- FPGA Design -- ping pong operation implementation and Modelsim simulation
- Shandong University machine learning experiment VI k-means
- FPGA设计中提高工作频率及降低功耗题目合集
猜你喜欢

FPGA面试题目笔记(一)——FPGA开发流程、亚稳态和竞争冒险、建立保持时间、异步FIFO深度等

Can Amazon, express, lazada and shrimp skin platforms use the 911+vm environment to carry out production number, maintenance number, supplement order and other operations?

Box model

山东大学项目实训之examineListActivity

How to use the markdown editor

Twitter data collection (content, fans, keywords, etc.)

The artistic director and production designer of Disney's Mandalorian revealed the virtual scene production behind it

FPGA设计——乒乓操作实现与modelsim仿真

FPGA interview notes (II) -- synchronous asynchronous D flip-flop, static and dynamic timing analysis, frequency division design, retiming

Matlab实现均值滤波与FPGA进行对比,并采用modelsim波形仿真
随机推荐
autojs,读取一行删除一行,停止自己外的脚本
Delegation agreement, data source agreement and advanced view in view
go的fmt包使用和字符串的格式化
Pycharm usage experience
Jenkins voucher management
Functional interface lambda, elegant code development
Simple understanding of pseudo elements before and after
This is probably the most comprehensive project about Twitter information crawler search on the Chinese Internet
End of 2021 graphics of Shandong University
Devsecops in Agile Environment
Cocoatouch framework and building application interface
ERROR 1215 (HY000): Cannot add foreign key constraint
Dichotomy find template
jenkins-凭证管理
The classification effect of converting video classification data set to picture classification data set on vgg16
The difference between call and apply and bind
Squid agent
Learn C language well from keywords
Quantitative understanding (Quantitative deep revolutionary networks for effective information: a whitepaper)
Servlet