Springboot整合openfeign使用详解

2022-07-08 10:48:58

环境:springboot2.3.8.RELEASE+springcloud Hoxton.SR8

图片


引入依赖:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
  </dependency>
</dependencies>
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
  • 通过URL直接配置目标服务

@FeignClient(value = "mv", url = "${feign.url}")
public interface PersonWeb {
	
  @GetMapping("/person/{id}")
  public String get(@PathVariable Integer id) ;
	
}
feign:
  url: http://localhost:8001

目标服务:

@RestController
public class PersonController {
  @GetMapping("/person/{id}")
  public Object get(@PathVariable Integer id) {
    return "Person" ;
  }
}

需要注意:目标服务返回值是Object(实际就是String),在定义Feign接口是必须明确数据类型,也就是必须是String。

  • @FeignClient 修改默认配置属性

@FeignClient(value = "mv", url = "${feign.url}", configuration = FeignConfig.class)
public interface PersonWeb {
  ...
}
public class FeignConfig {
	
  @Bean
  public Logger.Level feignLoggerLevel() {
    return Logger.Level.FULL;
  }
	
}

这里是通过JavaConfig的方式来配置默认的日志级别,也可以通过配置文件。

注意这里的FeignConfig可以不加@Configuration注解;并且你的这个配置会覆盖默认配置中的相关配置。

为了使得日志生效还需要配置如下:

logging:
  level:
    com.pack.controller.PersonWeb: debug

调用控制台输出:

图片

  • 设置超时时间

feign:
  url: http://localhost:8001 
  httpclient:
    enabled: true
  client:
    config:
      mv:
        connectTimeout: 2000
        readTimeout: 2000

这里的mv 为你@FeignClient 中配置的value或name的值。

调整目标服务的响应时间:

@GetMapping("/person/{id}")
public Object get(@PathVariable Integer id) {
  try {
    TimeUnit.SECONDS.sleep(5) ;
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  return "Person" ;
}

在这里休眠5秒

请求调用:

图片

控制台输出了错误信息。配置的超时时间生效readTimeout。

  • 日志级别配置

feign:
  url: http://localhost:8001 
  httpclient:
    enabled: true
  client:
    config:
      mv:
        logger-level: basic

这里配置的日志级别会覆盖JavaConfig中配置的级别。

  • 断路器的支持

支持断路器的类型:

  • Netfix Hystrix

  • Resilience4J

  • Sentinel

  • Spring Retry

这里使用Hystrix

首先开启hystrix

feign:
  hystrix:
    enabled: true
@Component
public class PersonFallback implements PersonWeb {

  @Override
  public String get(Integer id) {
    return "我是返回的默认值";
  }

}
@FeignClient(value = "mv", url = "${feign.url}", configuration = FeignConfig.class, fallback = PersonFallback.class)
public interface PersonWeb {
  ...
}

图片

hystrix 默认超时是1s,目标服务休眠了5s。

通过配置修改默认超时时间

引入hystrix依赖:

<dependency>
  <groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>

</dependency>

hystrix:
  command:
    default:  #服务名
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000
        timeout:
          enabled: true

通过如下方式可以获取发生的异常信息:

@Component
public class PersonFallbackFactory implements FallbackFactory<PersonFallback> {

  @Override
  public PersonFallback create(Throwable cause) {
    cause.printStackTrace() ;
    return new PersonFallback() ;
  }

}
@FeignClient(value = "mv", url = "${feign.url}", configuration = FeignConfig.class, fallbackFactory = PersonFallbackFactory.class)
public interface PersonWeb {
  ...
}
  • Feign继承支持

public interface BaseController {

  @GetMapping("/person/{id}")
  public String get(@PathVariable Integer id) ;
	
}
@RestController
@RequestMapping("/demo")
public class DemoController implements BaseController {
	
  @Resource
  private PersonWeb personWeb ;
	
  @GetMapping("/person/{id}")
  public String get(@PathVariable Integer id) {
    return personWeb.get(id) ;
  }
	
}
@FeignClient(value = "mv", url = "${feign.url}", configuration = FeignConfig.class, fallbackFactory = PersonFallbackFactory.class)
public interface PersonWeb extends BaseController {
	
}

一般是不建议这样使用的。

最后启动类:

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class SpringBootOpenfeignApplication {

  public static void main(String[] args) {
   SpringApplication.run(SpringBootOpenfeignApplication.class, args);
  }

}

完毕!!!

  • 作者:asoklove
  • 原文链接:https://blog.csdn.net/asoklove/article/details/117191654
    更新时间:2022-07-08 10:48:58