首页 > 其他 > 详细

使用Feign的两种方式

时间:2021-03-04 10:15:05      阅读:237      评论:0      收藏:0      [点我收藏+]

在SpringCloud中通常使用OpenFeign来封装微服务接口,有如下两种方式:

RequestLine注解

1.准备config

@Configuration
public class FeginConfig {
    @Bean
    public Contract feignConfiguration() {
        return new feign.Contract.Default();
    }
}

2.申明接口

@FeignClient(name = "EMPLOYEE", configuration = FeginConfig.class)
public interface EmployeeService1 {
    @RequestLine("POST /employee/add")
    @Headers({"Content-Type: application/json", "Accept: application/json"})
    CommonResult add(TblEmployee employee);

    @RequestLine("POST /employee/addBatch")
    @Headers({"Content-Type: application/json", "Accept: application/json"})
    CommonResult addBatch(List<TblEmployee> employee);
}

RequestMapping/PostMapping/GetMapping注解

此种方式比较简单,直接定义接口

@FeignClient("EMPLOYEE")
public interface EmployeeService {
    //@PostMapping(value = "/employee/add")
    @RequestMapping(value="/employee/add",consumes = "application/json",method = RequestMethod.POST)
    CommonResult add(TblEmployee employee);

    @PostMapping(value = "/employee/addBatch")
        //@RequestMapping(value="/employee/addBatch",consumes = "application/json",method = RequestMethod.POST)
    CommonResult addBatch(List<TblEmployee> employee);
}

常见问题

1.在使用RequestMapping/PostMapping/GetMapping时,如果注入了Contract,且实例为new feign.Contract.Default()。就会出现如下异常:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘webApp‘: Unsatisfied dependency expressed through field ‘employeeService‘; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘com.laowu.service.EmployeeService‘: FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: Method EmployeeService#add(TblEmployee) not annotated with HTTP method type (ex. GET, POST)
Warnings:
- Class EmployeeService has annotations [FeignClient] that are not used by contract Default
- Method add has an annotation RequestMapping that is not used by contract Default

有两种解决办法:

1.不注入Contract

//@Configuration
public class FeginConfig {
    //@Bean
    public Contract feignConfiguration() {
       return new feign.Contract.Default();
    }
}

2.注入SpringMvcContract。

@Configuration
public class FeginConfig {
    @Bean
    public Contract feignConfiguration() {
        return new SpringMvcContract();
    }
}

使用Feign的两种方式

原文:https://www.cnblogs.com/wugang/p/14477803.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!