有服务消费方调用提供方,之前采用的是restTemplate。
(1)在pom.xml中引入openfeign的启动器
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
(2)在application.yml中开启feign的熔断功能
feign: hystrix: enabled: true # 开启Feign的熔断功能
(3)在引导类上加上feign的注解
@SpringBootApplication
@EnableDiscoveryClient // 开启Eureka客户端
@EnableCircuitBreaker //开启熔断器
@EnableFeignClients // 开启feign客户端
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
(4)创建一个接口com..client.UserClient,在接口上添加@FeignClient
@FeignClient(value = "service-provider", fallback = UserClientFallback.class) // 标注该类是一个feign接口 public interface UserClient { @GetMapping("user/{id}") User queryById(@PathVariable("id") Integer id); }
(5)在接口中定义一些方法,这些方法来自服务提供方,但是不用写方法的具体实现见
(6)创建一个熔断类,实现feign的接口,实现对应的方法,这些方法就是熔断方法。
@Component public class UserClientFallback implements UserClient { @Override public User queryById(Integer id) { User user = new User(); user.setUsername("服务器繁忙,请稍后再试!"); return user; } }
(7)关闭服务提供方,访问页面会触发熔断方法,显示熔断方法里面的信息。