💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、豆包、星火、月之暗面及文生图、文生视频 广告
此处以前面第五节实验的为例: 当`电影服务`调用`用户服务`接口出现问题的时候,触发熔断,返回默认的值。 * 复制实验五中的项目`microservice-consumer-movie-ribbon`、`microservice-eureka-server`和`microservice-provider-user`三个服务。 * 在`microservice-consumer-movie-ribbon`的 pom.xml 中引入 Hystrix 依赖: ~~~xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> ~~~ * 加注解:在启动类`App.java`上添加`@EnableCircuitBreaker`注解。 ~~~java package com.shiyanlou; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class App { @Bean @LoadBalanced // 添加注解 public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(App.class, args); } } ~~~ * 然后在需要熔断的接口方法上面通过注解的方式添加熔断: ~~~java package com.shiyanlou; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; @RequestMapping("/movies") @RestController public class MovieController { @Autowired private RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "findByIdFallback") @GetMapping("/users/{id}") public User findById(@PathVariable Long id) { // 这里用到了RestTemplate的占位符能力 User user = this.restTemplate.getForObject("http://microservice-provider-user/users/{id}", User.class, id); // ...电影微服务的业务... return user; } public User findByIdFallback(Long id) { return new User(id, "default username", "default name", 0, new BigDecimal(1)); } } ~~~ 以上代码的作用:`@HystrixCommand(fallbackMethod = "findByIdFallback")`使用了一个`fallbackMethod`为`/users/{id}`接口添加了熔断机制,在该接口请求过程中出错时会调用`findByIdFallback`方法返回一个默认的用户值。