Openfeign如何传参

lijunyi2022-06-29SpringCloud微服务

OpenFeign 如何传参

1、传递JSON数据

TIP

openFeign默认的传参方式就是JSON传参(@RequestBody),因此定义接口的时候可以不用@RequestBody注解标注

provider接口:

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController
{

    @PostMapping("/order2")
    public Order createOrder2(@RequestBody Order order){
        return order;
    }
}

consumer中openFeign接口:

@FeignClient(value = "openFeign-provider")
public interface OpenFeignService
{

    /**
     * 参数默认是@RequestBody标注的,这里的@RequestBody可以不填
     * 方法名称任意
     */
    @PostMapping("/openfeign/provider/order2")
    Order createOrder2(@RequestBody Order order);
}

2、POJO表单传参

官方文档描述-@SpringQueryMapopen in new window

provider接口:

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController 
{

    @PostMapping("/order1")
    public Order createOrder1(Order order){
        return order;
    }
}

consumer中openFeign接口:

@FeignClient(value = "openFeign-provider")
public interface OpenFeignService 
{

    /**
     * 参数默认是@RequestBody标注的,如果通过POJO表单传参的,使用@SpringQueryMap标注
     */
    @PostMapping("/openfeign/provider/order1")
    Order createOrder1(@SpringQueryMap Order order);
}

3、URL中携带参数传递

provider接口:

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController 
{

    @GetMapping("/test/{id}")
    public String test(@PathVariable("id")Integer id){
        return "accept one msg id="+id;
}

consumer中openFeign接口:

@FeignClient(value = "openFeign-provider")
public interface OpenFeignService 
{

    @GetMapping("/openfeign/provider/test/{id}")
    String get(@PathVariable("id")Integer id);
}

4、普通表单参数

provider接口:

@RestController
@RequestMapping("/openfeign/provider")
public class OpenFeignProviderController 
{
    @PostMapping("/test2")
    public String test2(String id,String name){
        return MessageFormat.format("accept on msg id={0},name={1}",id,name);
    }
}

consumer中openFeign接口:

@FeignClient(value = "openFeign-provider")
public interface OpenFeignService 
{
    /**
     * 必须要@RequestParam注解标注,且value属性必须填上参数名
     * 方法参数名可以任意,但是@RequestParam注解中的value属性必须和provider中的参数名相同
     */
    @PostMapping("/openfeign/provider/test2")
    String test(@RequestParam("id") String arg1,@RequestParam("name") String arg2);
}

Last Updated 2024/5/24 16:21:58