這篇文章主要講解了“Sentinel中RestTemplate與Feign分析”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Sentinel中RestTemplate與Feign分析”吧!
Github : WIKI
Sphu (指明要保護的資源名稱)
Tracer (指明調用來源,異常統計接口)
ContextUtil(標示進入調用鏈入口)
流控規則(針對來源屬性)
@GetMapping("/test-sentinel-api")
public String testSentinelAPI(@RequestParam(required = false) String a) {
String resourceName = "test-sentinel-api";
ContextUtil.enter(resourceName, "user-center-service");
// 定義一個sentinel 保護的資源,名稱是test-sentinel-api
Entry entry = null;
try {
entry = SphU.entry(resourceName);
// ...被保護的業務邏輯處理
if (StringUtils.isEmpty(a)) {
// Sentinel 默認只會統計BlockException & BlockException的子類,如果想統計其他異常信息,添加Tracer
throw new IllegalArgumentException("A is not empty.");
}
return a;
// block Exception: 如果被保護的資源被限流或者降級了,就會拋異常出去
} catch (BlockException e) {
log.error("我被限流啦??!{}", e);
return "我被限流啦??!";
} catch (IllegalArgumentException argEx) {
// 統計當前異常發生次數 / 占比
Tracer.trace(argEx);
return "非法參數信息";
} finally {
if (entry != null) {
entry.exit();
}
ContextUtil.exit();
}
}降級規則
@GetMapping("/test-sentinel-api")
public String testSentinelAPI(@RequestParam(required = false) String a) {
// 定義一個sentinel 保護的資源,名稱是test-sentinel-api
Entry entry = null;
try {
entry = SphU.entry("test-sentinel-api");
// ...被保護的業務邏輯處理
if (StringUtils.isEmpty(a)) {
// Sentinel 默認只會統計BlockException & BlockException的子類,如果想統計其他異常信息,添加Tracer
throw new IllegalArgumentException("A is not empty.");
}
return a;
// block Exception: 如果被保護的資源被限流或者降級了,就會拋異常出去
} catch (BlockException e) {
log.error("我被限流啦??!{}", e);
return "我被限流啦??!";
} catch (IllegalArgumentException argEx) {
// 統計當前異常發生次數 / 占比
Tracer.trace(argEx);
return "非法參數信息";
} finally {
if (entry != null) {
entry.exit();
}
}
}源碼:com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect & com.alibaba.csp.sentinel.annotation.aspectj.AbstractSentinelAspectSupport
SentinelResource 使用該注解重構上述方法
@GetMapping("/test-sentinel-resource")
@SentinelResource(value = "test-sentinel-api", blockHandler = "blockException", fallback = "fallback")
public String testSentinelResource(@RequestParam(required = false) String a) {
// ...被保護的業務邏輯處理
if (StringUtils.isEmpty(a)) {
// Sentinel 默認只會統計BlockException & BlockException的子類,如果想統計其他異常信息,添加Tracer
throw new IllegalArgumentException("A is not empty.");
}
return a;
}
/**
* testSentinelResource BlockException method
*/
public String blockException(String a, BlockException e) {
log.error("限流了,{}", e);
return "blockHandler 對應《限流規則》";
}
/**
* testSentinelResource fallback method
* {@link SentinelResource} #fallback 在< 1.6的版本中,不能補貨BlockException
*/
public String fallback(String a) {
return "fallback 對應《降級規則》";
}使用 @SentinelRestTemplate.
resttemplate.sentinel.enabled可以開關是否啟用該注解。(開發階段很有意義。)
源碼:com.springframework.cloud.alibaba.sentinel.custom.SentinelBeanPostProcessor
@Bean
@LoadBalanced
@SentinelRestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
...配置文件中添加 feign.sentinel.enabled: true來開啟

編寫fallback 類,實現feign client
@Component
public class UserCenterFeignClientFallback implements IUserCenterFeignClient {
@Override
public UserDTO findById(Long userId) {
UserDTO userDTO = new UserDTO();
userDTO.setWxNickname("默認用戶");
return userDTO;
}
}
@Slf4j
@Component
public class UserCenterFeignClientFallbackFactory implements FallbackFactory<IUserCenterFeignClient> {
@Override
public IUserCenterFeignClient create(Throwable cause) {
return new IUserCenterFeignClient() {
@Override
public UserDTO findById(Long userId) {
log.warn("遠程調用被限流/降級,{}", cause);
UserDTO userDTO = new UserDTO();
userDTO.setWxNickname("默認用戶");
return userDTO;
}
};
}
}應用fallback class
/**
* IUserCenterFeignClient for 定義 user-center feign client
* fallbackFactory 可以拿到異常信息
* fallback 無法拿到異常信息
*
* @author <a href="mailto:magicianisaac@gmail.com">Isaac.Zhang | 若初</a>
* @since 2019/7/15
*/
@FeignClient(name = "user-center",
// fallback = UserCenterFeignClientFallback.class,
fallbackFactory = UserCenterFeignClientFallbackFactory.class
)
public interface IUserCenterFeignClient {
@GetMapping(path = "/users/{userId}")
public UserDTO findById(@PathVariable Long userId);
}啟動應用,設置流控規則,結果展示如下
{
id: 1,
...
wxNickName: "默認用戶"
}感謝各位的閱讀,以上就是“Sentinel中RestTemplate與Feign分析”的內容了,經過本文的學習后,相信大家對Sentinel中RestTemplate與Feign分析這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。