Springboot整合openfeign使用详解

95 篇文章 3 订阅
60 篇文章 2 订阅

环境: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);
  }

}

完毕!!!

公众号:

图片

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Cloud是一个为开发者提供了快速构建分布式系统的工具集,其中非常重要的一部分就是OpenFeignOpenFeign是一个声明式、模板化的HTTP客户端,它可以让开发者更加方便的调用HTTP接口。下面我们来详细了解一下Spring Cloud整合OpenFeign使用方式。 首先,我们需要在pom.xml文件中添加依赖,如下所示: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>{版本号}</version> </dependency> ``` 然后,我们需要在启动类上添加@EnableFeignClients注解,表示开启Feign客户端自动配置。同时,我们还需要通过@FeignClient注解来定义接口。例如: ``` @FeignClient(name = "user-service") public interface UserFeignClient { @GetMapping("/user/findById") User findById(@RequestParam("id") Long id); } ``` 在上面的代码中,@FeignClient注解中的name属性表示调用的服务名,而接口中的findById方法就是定义的远程调用的接口。其中,@RequestParam注解表示使用@RequestParam方式传参。 最后,我们在业务代码中使用定义的接口即可。例如: ``` @RestController public class UserController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/findUser") public User findUser(Long id) { return userFeignClient.findById(id); } } ``` 通过以上步骤,我们就可以方便地使用OpenFeign来调用HTTP接口,实现微服务之间的远程调用。整合OpenFeign有很多细节需要注意,例如如何处理调用异常、如何配置重试等等。但总体来说,Spring Cloud整合OpenFeign使用起来非常简单,是我们构建分布式系统的重要利器之一。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值