第一步:
Feign默认也有对Hystix的集成,只不过,默认情况下是关闭的。我们需要通过下面的参数来开启:(在消费端consumer中yml文件中加配置)
feign:
hystrix:
enabled: true
注意:(实现方法多种这里先介绍一种)
第二步:在controller中开放接口
@Autowired private UserFeign userFeign; @GetMapping("/user/{id}") public User getUserById(@PathVariable("id") Long id) { User user = userFeign.getById(id); return user; }
第三步:导入依赖
<!--Feign可以把Rest的请求进行隐藏,伪装成类似Spring MVC的Controller一样。你不用再自己拼接url,拼接参数等等操作--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
第四步:定义一个类作为fallback的处理类
import com.itheima.consumer.entity.User; import org.springframework.stereotype.Service; import java.util.Date; @Service public class UserFeignImpl implements UserFeign { @Override public User getById(Long id) { //降级逻辑 return new User(id, "我是feign降级策略,C计划", 108, new Date()); } }
第五步:然后在UserFeign中,指定刚才编写的实现类
import com.itheima.consumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
// http://localhost:8001/user/123
@FeignClient(value = "user-service",fallback = UserFeignImpl.class)// 替换http://localhost:8001
public interface UserFeign {
@GetMapping("/user/{id}")
public User getById(@PathVariable("id") Long id);
}
最后测试:
注意:要在feign中value指定的服务中制造异常,然后访问当前服务,否则页面出错
制造异常
//模拟异常 if (id == 1L) { int i = 1/0; }