04 Feign

五、Feign

1. 简介

​ Feign是一个HTTP客户端,可以更快捷、优雅地调用HTTP服务,使编写HTTPClient变得更简单。

​ 在Spring Cloud中使用Feign非常简单,只需要创建一个接口,然后在接口上添加一些注解就可以了。

2. 用法

​ 步骤:

  1. 编辑pom.xml文件,配置Feign和Eureka-Client依赖

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    
  2. 编辑application.yml文件,配置eureka

    eureka:
      client:
        # 是否将自己注册到Eureka-Server中,默认的为true
        register-with-eureka: false
        # 指定服务注册中心的地址
        service-url:
          defaultZone: http://localhost:7001/eureka/
    
  3. 编辑启动类,启用Eureka客户端

    @SpringBootApplication
    @EnableEurekaClient
    // 启用Feign客户端,扫描指定包下所有的feign注解
    @EnableFeignClients(basePackages = "com.itany.service")
    public class CloudConsumer8080Application {
        public static void main(String[] args) {
            SpringApplication.run(CloudConsumer8080Application.class, args);
        }
    }
    
  4. 创建接口并配置

// 调用的服务名,到Eureka中寻找对应的微服务
@FeignClient("user-provider/user")
public interface UserService {

    @GetMapping
    public ResponeResult userList();

    @GetMapping("/{id}")
    public ResponseResult user(@PathVariable(value = "id") Integer id);  

  	@PostMapping("/form")
     @Headers({"Content-Type:x-www-form-urlencode"})
     public ResponeResult addForm(User user);
     
 	@PostMapping("/json")
     @Headers({"Content-Type:application/json"})
     public ResponeResult addJson(@RequestBody User user);

    @DeleteMapping("/{id}")
 	public ResponeResult delete(@PathVariable("id") Integer id);

    @PutMapping("/v2/user-service/user")
     @Headers({"Content-Type:application/json"})
     public ResponeResult update(@RequestBody User user);
}

3. 传参

​ feign传递对象参数的解决方式:

  • 方式一:将对象参数拆为多个简单类型参数,且必须添加@RequestParam注解
  • 方式二:使用Map替代对象参数,且必须添加@RequestParam注解
  • 方式三:标明请求的Content-Type
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值