zoukankan      html  css  js  c++  java
  • 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(); } }
  • 相关阅读:
    表单提交
    后台返回来的数据是字符串
    背景图充满屏幕
    微信小程序添加模板消息
    axios
    前端常见的跨域解决方案
    gulp的压缩
    git的使用步骤
    vue项目使用mint UI
    利用HBuilder将vue项目打包成移动端app
  • 原文地址:https://www.cnblogs.com/geniushuangxiao/p/7219515.html
Copyright © 2011-2022 走看看