SentinelRestTemplate用於 sentinel 集成 RestTemplate
添加在 RestTemplate 主鍵上,全局的限流容錯處理,優先級低於局部限流容錯注解 @SentinelResource
例如:
package com.example;
import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import com.example.exception.ExceptionUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class OrderServiceRestApplication {
@Bean
@LoadBalanced
@SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class,
fallback = "fallback", fallbackClass = ExceptionUtil.class)
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderServiceRestApplication.class, args);
}
}
blockHandler 限流策略 (方法名,方法必須是靜態的)
blockHandlerClass 限流方法類
fallback 熔斷降級策略(方法名,方法必須是靜態的)
fallbackClass 熔斷降級類
例如:
package com.example.exception;
import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.example.pojo.Product;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpResponse;
public class ExceptionUtil {
// 服務流量控制處理
public static ClientHttpResponse handleException(HttpRequest request,
byte[] body,
ClientHttpRequestExecution execution,
BlockException exception) {
exception.printStackTrace();
return new SentinelClientHttpResponse(
JSON.toJSONString(new Product(1, "服務流量控制處理-托底數據", 2, 2666D)));
}
// 服務熔斷降級處理
public static ClientHttpResponse fallback(HttpRequest request,
byte[] body,
ClientHttpRequestExecution execution,
BlockException exception) {
exception.printStackTrace();
return new SentinelClientHttpResponse(
JSON.toJSONString(new Product(1, "服務熔斷降級處理-托底數據", 2, 2666D)));
}
}