Sentinel-Feign整合Sentinel

步骤一:在feing-api项目中定义类,实现FallbackFactory:

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import cn.itcast.feign.clients.UserClient;
import cn.itcast.feign.pojo.User;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;

@Slf4j //记录日志
public class UserClientFallbackFactory implements FallbackFactory<UserClient> {

@Override
public UserClient create(Throwable throwable) {
return new UserClient() {
/*
在这个方法中编写降级的业务逻辑
返回 友好提示、一个默认值...,都可以在这个方法里面写
*/
@Override
public User findById(Long id) { //在这个方法中编写降级的逻辑
log.error("查询用户异常",throwable);
return new User();
}
};
}
}

步骤二: 在feing-api项目中的DefaultFeignConfiguration类中将UserClientFallbackFactory注册为一个Bean:

代码:

1
2
3
4
5
//将UserClientFallbackFactory注册到bean
@Bean
public UserClientFallbackFactory userClientFallbackFactory(){
return new UserClientFallbackFactory();
}

步骤三: 在feing-api项目中的UserClient接口中使用UserClientFallbackFactory:

代码:

1
2
3
4
5
6
7
8
9
10
11
12
import cn.itcast.feign.clients.fallback.UserClientFallbackFactory;
import cn.itcast.feign.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "userservice", fallbackFactory = UserClientFallbackFactory.class)
public interface UserClient {

@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}