SpringCloud Feign 使用

SpringCloud Feign 使用

  • SpringCloud版本: Hoxton.RELEASE

Spring Cloud 之 Feign. - JMCui - 博客园
@FeignClient 参数详解

  1. 引入 maven 依赖
  2. 配置 Feign, @EnableFeignClients
  3. 接口声明

1. 引入 maven 依赖

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

2. 配置 Feign

在 SpringBootApplication 处打上注解, @EnableFeingClients

3. 接口声明

配置 feign 接口的声明,简单的例子

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

/**
 * feign声明
 * @author suwenguang
 **/
@FeignClient(value = "test-user-provider-service")
public interface FeignUserService {

	@RequestMapping("/user/get")
	String get();
}

接口声明包含但不限于以下部分
3.1 路径声明
3.2 参数声明
3.3 返回声明
Spring Cloud OpenFeign

3.1 路径声明

3.1.1. 服务注册中心内部调用
3.1.2. 外部接口的调用

3.1.1. 服务注册中心内部调用

  • 通过指定注册中心的服务名 @FeignClient(value="xxx-service")

例子:

@FeignClient(value = "test-user-provider-service")
public interface FeignUserService {

	@RequestMapping("/user/get")
	String get();
}

3.1.2. 外部接口的调用

feign 不单单可以用作微服务调用,只要是 HTTP 请求都基本上可以满足

  • 通过指定 url 补全地址

例子:

@FeignClient(url = "192.168.9.233:19192/ttc",name = "commision-service")
public interface FeignCommisionService {

	@RequestMapping(method = RequestMethod.GET,value = "/health/get")
	Object health();

}

3.2 参数声明

对于内部请求,我们一般限于json格式的请求参数,但是HTTP请求不单单是json
这里只介绍json的方式

feign复杂参数传递

主要注解:

  • @RequestBody
  • @RequestParam
  • @PathVariable

如果对应接口接收的格式是json格式,只需要将对应的json序列化为对象, 将对象传入, 使用@RequestBody序列化,同时可以使用@RequestParam指定数据

如何使用Feign构造多参数的请求 | 周立的博客 - 关注Spring Cloud、Docker

例子:

@FeignClient(name = "microservice-provider-user")
public interface UserFeignClient {
  @RequestMapping(value = "/get", method = RequestMethod.GET)
  public User get1(@RequestParam("id") Long id, @RequestParam("username") String username);
}

feign如何带文件参数?
以前在restTemplate中可以指定multipartForm,传入File对象即可.那么feign如何使
Spring Cloud OpenFeign

使用@SpringQueryMap支持
例子:

@FeignClient("demo")
public interface DemoTemplate {

    @GetMapping(path = "/demo")
    String demoEndpoint(@SpringQueryMap Params params);
}

3.3 返回声明

其实只需要用object去接受即可.
或者直接用统一返回体接收对象.如果调用双方都协调好协议的话.

4. feign配置

  1. 全局配置
  2. 单独配置

查看官网Spring Cloud OpenFeign

5. 断路器Hystrix配置

Hoxton已经集成了hystrix断路器,使用配置文件可以配置hystrix的开关

可以全局配置, 也可以单独配置

发布了161 篇原创文章 · 获赞 140 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/qq_37933685/article/details/103755724