004声明式服务调用Feign & 断路器Hystrix

1、POM配置

  和普通Spring Boot工程相比,添加了Eureka Client、Feign、Hystrix依赖和Spring Cloud依赖管理

<dependencies>
  <!--Eureka Client依赖-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <!--声明式服务消费-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
  </dependency>
  <!-- 整合断路器hystrix,其实feign中自带了hystrix,引入该依赖主要是为了使用其中的hystrix-metrics-event-stream,用于dashboard -->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
  </dependency>
  <!-- 服务健康检查,必须添加,否则此服务不会启动hystrix.stream -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
</dependencies>
<!--Spring Cloud依赖版本管理-->
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>Dalston.SR1</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

02、使能

@SpringBootApplication
@EnableFeignClients  //声明式服务消费
@EnableCircuitBreaker  //断路器
@EnableEurekaClient  //Eureka客户端
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

03、src/main/resources工程配置文件 application.yml

server:
  port: 3010
spring:
  application:
    name: feign-hello-service-consumer
eureka:
  client:
    serviceUrl:
      defaultZone: http://discovery:1000/eureka/
feign:
  hystrix:
    enabled: true  #在新版本Feign中,hystrix默认关闭,必须手动打开

04、声明式服务消费

@FeignClient(name = "hello-service-provider", fallback = HelloFallback.class)
public interface HelloFeignService {
@RequestMapping("/hello")
public String hello(); } @Component
class HelloFallback implements HelloFeignService { @Override
public String hello() {
return "Error";
}
}

05、Controller

@RestController
public class FeignController {
@Autowired
private HelloFeignService helloService; @GetMapping("feign")
public String hello() {
    return this.helloService.hello();
}
}
上一篇:Java - 记录String中intern()方法的学习与理解


下一篇:【Dalston】【第三章】声明式服务调用(Feign)