-
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
相关推荐
ITKEY_2 分钟前
neovim基于nvim-jdtls 开发java报错leon873 分钟前
MyBatis-Plus与AOP实现动态数据权限过滤的实践与踩坑记录电气研究所4 分钟前
Java + Redis 实现工业设备告警去抖,避免变频器故障重复推送無限進步D4 分钟前
Java 代码块用户3126874877209 分钟前
@Async 加了没生效?Spring Boot 异步编程全链路拆解:从线程池到自调用陷阱zfoo-framework22 分钟前
安装pi agent 支持duojie和deepseek君顾11 小时前
代驾跑腿业务系统实战开发指南智码看视界2 小时前
Day 45 | Sentinel流量治理:从限流到熔断降级再到系统自适应保护NGINX开源社区2 小时前
NGINX Ingress Controller 5.5:安全性与性能提升,迁移更轻松云烟成雨TD2 小时前
Micrometer 系列【25】Spring Boot Actuator | Spring MVC、Spring WebFlux 指标