-
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
相关推荐
山荷枝1 小时前
03-框架--SpringChaHae-In1 小时前
SpringBoot统一功能处理coder!mq2 小时前
说几个常见的语法糖?gugucoding2 小时前
38. 【Java】Stream API(下):高级操作与性能心平气和量大福大2 小时前
android-实例-蒲公英-更新与安装-5-签名与生成APK952363 小时前
Spring-cloud配置中心ydd1001003 小时前
寻找两个正序数组的中位数 Java 题解,二分分割详解真上帝的左手4 小时前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录Zane19945 小时前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲云烟成雨TD5 小时前
Micrometer 系列【42】链路追踪:Span 体系 | 核心 API