OpenFeign实现HTTP接口远程调用
远程接口调用
一般在调用第三方远程接口时使用RestTemplate,这里使用Feign来进行远程接口调用。
1.Maven依赖
核心依赖是io.github.openfeign,此外可能还需引入web、fastjson等其他依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>10.2.3</version>
</dependency>
2.Feign配置类
import com.demo.client.FeignClient;
import feign.Feign;
import feign.Request;
import feign.Retryer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
@Value("${host.ip}")
private String ip;
@Value("${host.port}")
private String port;
private static final int CONNECT_TIMEOUT = 6000;
private static final int READ_TIMEOUT = 6000;
@Bean
public FeignClient feignClient(){
String url = new StringBuilder()
.append("http://")
.append(ip)
.append(":")
.append(port)
.toString();
return Feign.builder()
.options(new Request.Options(CONNECT_TIMEOUT, READ_TIMEOUT))
.retry(Retryer.NEVER_RETRY)
.target(FeignClient.class, url);
}
}
3.声明式接口调用
import feign.Headers;
import feign.RequestLine;
public interface FeignClient {
@RequestLine("GET /index")
String getTest();
//POST请求入参返回值均使用字符串类型,直接使用实体会报编解码异常
@RequestLine("POST /post")
@Headers({"Content-Type: application/json", "Accept: application/json"})
String postTest(String user);
}
4.接口使用
@RestController
public class TestController {
//配置类中已经使用@Bean注册了FeignClient,这里直接注入使用
@Autowired
private FeignClient feignClient;
@RequestMapping("/test")
public void testFeign(){
//远程调用GET方法
String getResult = feignClient.getTest();
//远程调用POST方法
String postResult = feignClient.postTest(JSON.toJSONString(new user()));
}
}
5.第三方接口提供者
@RestController
public class DemoController {
@GetMapping("/index")
public String index(){
retuern new User().toString();
}
@PostMapping("/post")
public User post(@RequestBody User user){
...
return user;
}
}