原创

OpenFeign简化rest接口的调用

openeign的使用

1、引入pom

<feign.version>9.5.0</feign.version>

<dependency>
  <groupId>io.github.openfeign</groupId>
  <artifactId>feign-core</artifactId>
   <version>${feign.version}</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-slf4j</artifactId>
    <version>${feign.version}</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-hystrix</artifactId>
    <version>${feign.version}</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-jackson</artifactId>
    <version>${feign.version}</version>
</dependency>

2、创建配置类

@Configuration
public class DocServerConfig {
    @Value("${application.docServer.url}")
    private String baseUrl;

    @Bean
    DocServerClient docServerClient() throws InterruptedException {
        return HystrixFeign.builder()
                .decoder(new JacksonDecoder())
                .encoder(new JacksonEncoder())
                .requestInterceptor(new FeignInterceptor())
                .setterFactory(
                        (target, method) ->
                                new SetterFactory.Default()
                                        .create(target, method)
                                        .andCommandPropertiesDefaults(
                                                HystrixCommandProperties.defaultSetter()
                                                        .withExecutionTimeoutInMilliseconds(10000)))
                .target(DocServerClient.class, this.baseUrl);
    }
}

3、定义接口

public interface DocServerClient {
    @Headers({"Content-Type: application/json", "Accept: application/json"})
    @RequestLine("POST /createDocForFileSystem/input")
    DocIdResult createDocForFileSystem(CreateDocForFileSystemInput input);


    @Headers({"Content-Type: application/json", "Accept: application/json"})
    @RequestLine("POST /createDocForHash/input")
    DocIdResult createDocForHash(CreateDocForHashInput input);

}

4、统一设置header

@Slf4j
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("xxxx", "111");
        requestTemplate.header("yyyy", "simple");
    }
}

注入RequestInterceptor,详见步骤二

5、使用接口

@Autowired private DocServerClient docServerClient;

DocIdResult docIdResult = docServerClient.createDocForFileSystem(createDocForFileSystemInput);
正文到此结束
本文目录