Feign实现远程接口调用

远程接口调用

一般在调用第三方远程接口时使用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;
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值