1. 添加依赖: sentinel,feign
2. 配置feign允许sentinel
3. 编写: feign,请求客户端
4. 为客户端添加(sentinel)异常处理类
1.添加依赖: sentinel,feign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2.配置feign允许sentinel
feign:
sentinel:
enabled: true
3.编写: feign,请求客户端
@FeignClient(name = "user-center")
public interface UserCenterFeignClient {
public ApiResult findBy(Integer id);
public ApiResult getDetail(User user);
}
4.为客户端添加(sentinel)异常处理类
方式(1).
// 用户中心 Feign 接口
@FeignClient(name = "user-center",fallback = FeignClientFallback.class)
public interface UserCenterFeignClient {
public ApiResult findBy(Integer id);
public ApiResult getDetail(User user);
}
// 用户中心 Feign异常接收处理类
@Component
public class UserCenterFeignClientFallback implements UserCenterFeignClient {
@Override
public ApiResult findBy(Integer id) {
return ApiResult.error("异常");
}
@Override
public ApiResult getDetail(User users) {
return ApiResult.error("异常");
}
}
方式(2).
// 接口
@FeignClient(name = "user-center",fallbackFactory = FeignClientFallback.class) // 方法上可以拿到异常
public interface UserCenterFeignClient {
public ApiResult findBy(Integer id);
public ApiResult getDetail(User user);
}
// 异常处理类
@Component
@Slf4j
public class UserCenterFeignClientFallbackFactory implements FallbackFactory<UserCenterFeignClient> {
// 用户中心 Feign异常接收处理类
@Override
public UserCenterFeignClient create(Throwable throwable) {
return new UserCenterFeignClient() {
@Override
public ApiResult findBy(Integer id) {
log.warn("异常",throwable);
return ApiResult.error("Sentinel 异常");
}
@Override
public ApiResult getDetail(User users) {
return ApiResult.error("Sentinel 异常");
}
};
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。