Spring Cloud Feign 使用方式

结合 Spring Cloud 使用 Feign 的步骤如下:

Feign 结合 Spring Cloud 时,可使用 Springmvc 提供的注解支持,如 @RequestMapping @GetMapping 等

1.开启 Feign 支持 @EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}
2.定义 Feign 接口

Get 请求方式:

展示两种定义 Get 请求的方式,注意必须要定义属性名称,不能像 mvc 省略 @RequestParam

@FeignClient(Constants.SERVICE_NAME)
public interface ApiClient {

	public static final String URL = "/api/user";

	@GetMapping(URL + "/get")
	User get(@RequestParam("uid") String uid);

	@GetMapping(URL + "/get/{uid}")
	User show(@PathVariable("uid") String uid);

}
同时也可以用 Map 构建参数

public User get(@RequestParam Map<String, Object> map);
Post 请求方式:

@PostMapping(URL + "/update")
User update(@RequestBody User user);
服务端:
@RestController
public class UserApi {

    @PostMapping("/update")
    public User update(@RequestBody User user) {
      ...
    }
}

一些坑:

1.@RequestMapping 不要在接口上注解,否则会当成 controller 暴露出去

2.使用 Get 请求时,参数只能是基本数据对象,可以是 String、Integer、Map (如果传入复杂对象,如 User ,则 Get 请求会被转为 Post 请求)

3.参数必须使用 @RequestParam 或 @PathVariable 进行注解,并定义属性名称,否则报错 no suitable HttpMessageConverter found for response type [type] and content type [text/plain;charset=UTF-8]

4.在 Feign 中使用 @RequestParam 的作用是向请求 url 中附加参数,如 /api/user/get?uid=1 中 ?uid=1 ,所以参数名称必须与服务接口的参数一致

Feign 项目文档

https://github.com/OpenFeign/feign

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值