一、给RestTemplate加注解
@Bean
@LoadBalanced
@SentinelRestTemplate(
blockHandler = "handleBlock",
fallback = "handleFallback",
fallbackClass = SentinelBlockHandler.class,
blockHandlerClass = SentinelBlockHandler.class)
public RestTemplate restTemplate(){
return new RestTemplate();
}
二、写异常Handler:SentinelBlockHandler
ClientHttpResponseImpl 是ClientHttpResponse的实现类,自己可以写。
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
@Slf4j
public class SentinelBlockHandler {
//限流熔断业务逻辑
public static ClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
log.info("handleBlock");
return new ClientHttpResponseImpl();
}
//异常熔断业务逻辑
public static ClientHttpResponse handleFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
log.info("handleFallback");
return new ClientHttpResponseImpl();
}
}
三.yml写个开关
resttemplate:
sentinel: #@SentinelRestTemplate 开启、关闭
enabled: true
四.测试
@GetMapping("/testSentinelRestTemplate/{userId}")
public String testSentinelRestTemplate(@PathVariable Integer userId){
UserDTO userDTO = restTemplate.getForObject("http://user-center/users/{userId}",UserDTO.class,userId);
return userDTO.toString();
}