-
resttemplate开启sentinel保护配置
propertiesresttemplate.sentinel.enabled=true -
配置sentinel-dashboard地址
propertiesspring.cloud.sentinel.transport.dashboard=localhost:8858\ spring.cloud.sentinel.transport.dashboard.port=8739 -
实例化RestTemplate并加入@SentinelRestTemplate注解
java@Configuration public class RestTemplateConfig { @Bean @LoadBalanced @SentinelRestTemplate( fallbackClass = ExceptionUtil.class,fallback = "fallBack", blockHandlerClass = ExceptionUtil.class, blockHandler = "handleBlock") public RestTemplate restTemplate() { return new RestTemplate(); } public static class ExceptionUtil { public static ClientHttpResponse handleBlock( HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException be){ RestResponse<Void> commonResult = RestResponse.error("500","降级处理函数 block 。。。。。"); return new SentinelClientHttpResponse(JSON.toJSONString(commonResult)); } public static ClientHttpResponse fallBack( HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException be){ RestResponse<Void> commonResult = RestResponse.error("500","异常处理函数 fallback 。。。。。"); return new SentinelClientHttpResponse(JSON.toJSONString(commonResult)); } } } -
编写测试代码,并使用postman访问对应的url
java@Slf4j @RestController @RequestMapping("/test") public class TestController { @Autowired private RestTemplate restTemplate ; @GetMapping("/index") public RestResponse<String> index(){ String url = "http://hello-nacos-client/hello/index" ; RestResponse<String> retValue = restTemplate.getForObject(url, RestResponse.class); log.info("ret value : {}", retValue); return retValue ; } @GetMapping("/exception") public Object exception(){ String url = "http://hello-nacos-client/hello/exception" ; RestResponse<String> retValue = restTemplate.getForObject(url, RestResponse.class); log.info("ret value : {}", retValue); return retValue ; } } -
在dashboard上配置限流规则,再次通过postman调用url,能正常触发SentinelRestTemplate的blockHandler方法处理
-
在dashboard上配置熔断规则,再次通过postman调用url,能正常触发SentinelRestTemplate的fallBack方法处理
Sentinel整合RestTemplate
yicj2023-09-23 9:53
相关推荐
凌波粒5 小时前
MyBatis完整教程IDEA版(2)--ResultMap/注解/一对多/多对一/lombok/log4j蓝-萧5 小时前
【玩转全栈】----Django基本配置和介绍priority_key5 小时前
排序算法:堆排序、快速排序、归并排序汤姆yu6 小时前
基于SpringBoot的动漫周边商场系统的设计与开发皮皮林5516 小时前
快速解决 Maven 版本冲突指南 !灰小猿6 小时前
Spring前后端分离项目时间格式转换问题全局配置解决算法与编程之美7 小时前
理解Java finalize函数怕什么真理无穷7 小时前
C++面试4-线程同步lkbhua莱克瓦247 小时前
Java基础——常用算法5牢七7 小时前
javan小案例。