天天看点

SpringCloud之feign

官方文档

feign是什么

用官方文档的话来解释:

feign是一个声明性web服务客户端。它使编写web服务客户端变得更容易。使用feign创建一个接口并对其进行注释。它有可插入的注释支持,包括外部注释和jax-rs注释。feign还支持可插入的编码器和解码器。spring cloud增加了对spring mvc注释的支持,以及对使用spring web中默认使用的httpMessageConverter的支持。spring cloud集成了ribbon和eureka,在使用feign时提供了一个负载平衡的http客户端。

如何使用

首先要引入以下依赖,feign是集成了ribbon的

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
           
SpringCloud之feign

在启动类开启对feign的支持@EnableFeignClients

@SpringBootApplication
@EnableEurekaClient
@RibbonClients({
        @RibbonClient(name="server-user",configuration = UserConfig.class),
        @RibbonClient(name="server-order",configuration = OrderConfig.class)
})
@EnableFeignClients
public class PowerApplication {

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

}
           

feign服务

@FeignClient("server-user")
public interface FeignService {

	@RequestMapping("/hello")
	Map getUser();
}
           
@RestController
public class FeignController {

	@Autowired
	FeignService feignService;

	@RequestMapping("/getFeignUser")
	public Map getFeignUser(){
		return feignService.getUser();
	}
}
           
SpringCloud之feign

如果不想用自己的配置

官网上推荐的方式是

@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
    //..
}
           

fooconfiguration不需要用@configuration注释。但是,如果是,请注意将其从任何@componentscan中排除,否则将包含此配置,因为当指定时,它将成为feign.decoder、feign.encoder、feign.contract等的默认源。这可以通过将它与任何@componentscan或@springbootsapplication放在一个单独的、不重叠的包中来避免,也可以在@componentscan中显式排除它。

也可以通过配置文件的方式

application.yml

feign:
  client:
    config:
      feignName:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: full
        errorDecoder: com.example.SimpleErrorDecoder
        retryer: com.example.SimpleRetryer
        requestInterceptors:
          - com.example.FooRequestInterceptor
          - com.example.BarRequestInterceptor
        decode404: false
        encoder: com.example.SimpleEncoder
        decoder: com.example.SimpleDecoder
        contract: com.example.SimpleContract
           

默认配置可以在@enablefeignclients属性defaultconfiguration中以类似的方式指定,如上所述。不同之处在于,此配置将应用于所有外部客户端。

如果您喜欢使用配置属性来配置所有@feignclient,那么可以使用默认的feign名称创建配置属性。

application.yml

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic
           

官网上说java bean的方式和配置文件都存在时,配置文件的优先级较高,但是没测试过,也没人会两者都配置吧。

继续阅读