欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot项目基于Spring Cloud Feign调用第三方外部接口

程序员文章站 2024-01-28 11:38:04
...

一、添加maven依赖

(1)添加SpringCloud依赖

<properties>
    <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>

(2)添加dependencyManagement相关依赖控制Spring Cloud的版本

<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>

(3)添加openfeign的依赖

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

二、配置config类

import feign.Feign;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignConfig {

    @Bean
    public okhttp3.OkHttpClient okHttpClient(){
        return new okhttp3.OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool())
                .build();
    }
}

三、主类添加注解

@EnableFeignClients

四、编写feign调用接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "testfeignSerive", url = "http://ip:port/")
public interface FeignService {

    @RequestMapping(value = "testmethod",method = RequestMethod.POST)
    String getMaillist(@RequestParam(value = "t") String t);

}

五、调用时,直接在controller中,注入该接口即可

@Autowired
    private FeignService feignClientProxy;
String obj = feignClientProxy.getMaillist(t);

程序员改变世界,每天进步一点点,立志不做一个单纯的CV程序员!