Java——使用@FeignClient调用远程服务

前言

@FeignClient 用于定义接口,通过该接口调用远程服务的方法

一、使用

  1. 开启Feign
@EnableFeignClients
public class 启动类{}
  1. 配置调用远程服务的接口
@FeignClient(
	url = "https://www.test.com",
	name = "test-url",
	configuration = TestFeignConfiguration.class
)
public interface ITestClient {

	String API_PREFIX = "/test-api";

	@PostMapping(value = API_PREFIX + "/forward/{id}")
	Resp<String> forward(@RequestParam String name,
						 @RequestParam List<String> hobbies,
						 @PathVariable String id);

  1. Feign接口的配置类 (这里在用feign调用其他服务时,在header中加上了token等)
@Configuration
public class TestFeignConfiguration implements RequestInterceptor {


	@Override
	public void apply(RequestTemplate template) {
		template.header("Content-Type", "application/json; charset=UTF-8");
		template.header("X-Auth-Token", "我的token啦啦啦");
	}

}
  1. 表现层调用
@Resource
private ITestClient  testClient;

@RequestMapping(value = "/forward/{id}",method = RequestMethod.POST)
	public Resp<String> forward(@RequestParam String name,
								@RequestParam List<String> hobbies,
								@PathVariable String id){
		return  testClient.forward(name,hobbies,id);
	}

二、@RequestParam、@RequestBody区别在这里插入图片描述

参数中有个content-type,指定了传参类型,默认为application/x-www-form-urlencoded

① 请求url中的参数、form-data(表单)、x-www-form-urlencoded:只可以用@RequestParam

② application/json:json字符串部分可以用@RequestBody

③GET请求不能用@RequestBody


RequestBody 只能有一个!!
RequestBody 只能有一个!!
RequestBody 只能有一个!!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Cloud中,可以使用@FeignClient注解来调用远程服务接口。@FeignClient注解是一个声明式的Web服务客户端,可以将一个服务接口定义成Java接口,然后使用注解的方式来调用远程服务。 具体步骤如下: 1. 引入Feign依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 2. 创建服务接口 创建一个Java接口,用于定义远程服务的接口方法。例如: ``` @FeignClient(name = "remote-service") public interface RemoteService { @GetMapping("/hello") String sayHello(); } ``` @FeignClient注解中的name属性指定了远程服务的名称,这个名称对应了服务注册中心中的服务名。 3. 调用远程服务 在需要调用远程服务的地方,通过@Autowired注入RemoteService接口实例,然后直接调用接口中的方法即可。 ``` @RestController public class MyController { @Autowired private RemoteService remoteService; @GetMapping("/test") public String test() { return remoteService.sayHello(); } } ``` 在上面的例子中,MyController通过调用RemoteService接口中的sayHello()方法来调用远程服务中的/hello接口。 需要注意的是,@FeignClient注解默认使用的是Spring MVC注解,因此在定义服务接口方法时需要使用Spring MVC的注解来指定请求方式、请求路径等信息。例如,在RemoteService接口中的sayHello()方法上使用@GetMapping注解来指定使用GET请求访问/hello接口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值