Hystix熔断、Feign以及ZUUL网关
- Hystix
|
- Feign
2.1 添加依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> 2.2 编写接口 @FeignClient("user-service") public interface UserFeignClient { @GetMapping("/{userId}") UserInfo findById(@PathVariable int userId); } 2.3 启动类配置 添加注解 @SpringCloudApplication @EnableFeignClients public class UserConsumerApplication { //Feign中已经自动集成了Ribbon负载均衡,因此我们不需要自己定义RestTemplate了。 /*@Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); }*/ public static void main(String[] args) { SpringApplication.run(UserConsumerApplication.class, args); } } 2.4 客户端调用 @RestController @DefaultProperties(defaultFallback = "fallback01") public class UserController { @Autowired private UserFeignClient userFeignClient ; @GetMapping("/{userId}") public UserInfo findById(@PathVariable("userId") int userId) { return userFeignClient.findById(userId); }
/*@Autowired private RestTemplate restTemplate;*/ /*@GetMapping("/{userId}") @HystrixCommand( //指定请求超时后去响应其他方法 fallbackMethod = "fallback01", commandProperties={ //更改超时时间,默认1000 /1秒 @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1000") } ) public UserInfo findById(@PathVariable("userId") int userId) { System.out.println("这是消费端接收的ID是 " + userId); String url = "http://user-service/" + userId ; System.out.println("Url"+url); UserInfo userInfo = restTemplate.getForObject(url, UserInfo.class); System.out.println("消费者接收的数据"+userInfo.getUsername()); return userInfo ; }*/ public UserInfo fallback01( int userId) { System.out.println("接收的参数ID是:"+userId); UserInfo userInfo = new UserInfo(); userInfo.setUserId(110); userInfo.setUsername("服务器炸了!"); return userInfo; } } 2.5 负载均衡 Feign中本身已经集成了Ribbon依赖和自动配置 2.6 Feign对Hystix支持 Feign默认也有对Hystix的集成,只不过,默认情况下是关闭的 开启Hystix配置:feign.hystrix.enabled=true 2.6.1 编写熔断器实现接口
2.6.2 修改实现类
2.6.3 当使用Feign的时候,不能够再加入来自于Spring自带的包下面的@HystrixCommand注解,会产生冲突。
2.6.4 测试运行
|
- ZUUL网关
3.1 添加依赖
3.2 设置启动类
3.3 配置application.properties
3.4 编写路由规则
4 面向服务的路由
|