-
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
相关推荐
用户033212666367几秒前
Java 高效处理 Word 文档:查找并替换文本的全面指南轮到我狗叫了1 分钟前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)渣哥5 分钟前
你遇到过 ConcurrentModificationException 吗?其实很常见lunzi_fly7 分钟前
【源码解读之 Mybatis】【基础篇】-- 第1篇:MyBatis 整体架构设计JIngJaneIL22 分钟前
汽车租赁|基于Java+vue的汽车租赁系统(源码+数据库+文档)渣哥37 分钟前
有一天,我和 CopyOnWriteArrayList 杯“线程安全”的咖啡喂完待续41 分钟前
【序列晋升】28 云原生时代的消息驱动架构 Spring Cloud Stream的未来可能性叽哥44 分钟前
Kotlin学习第 3 课:Kotlin 流程控制:掌握逻辑分支与循环的艺术杨杨杨大侠44 分钟前
第5章:实现Spring Boot集成华仔啊1 小时前
工作5年没碰过分布式锁,是我太菜还是公司太稳?网友:太真实了!