关于openfeign的参数传递

openfeign接口代码示例:

@FeignClient(name="调用的服务名称", path="demo")
public interface FeignTest{
    /**
     * 参数为空时
     * @return
     */
    @RequestMapping("demo1")
    String demo1();

    /**
     * 当参数在url路径上时
     * @param id
     * @return
     */
    @RequestMapping("demo2/{id}")
    String demo2(@PathVariable("id") int id);

    /**
     * 当传递普通参数时
     * @param name
     * @return
     */
    @RequestMapping("demo3")
    String demo3(@RequestParam("name") String name, @RequestParam("age") int age);

    /**
     * 当传递复杂对象参数时
     * @param userinfo
     * @return
     */
    @RequestMapping("demo4")
    String demo4(@RequestBody Userinfo userinfo);

    /**
     * 当参数放请求头中时
     * @param source
     * @return
     */
    @RequestMapping("demo5")
    String demo5(@RequestHeader("source") String source);
}

对应服务端代码如下:

@RestController
@RequestMapping("demo")
public TestController{
    @RequestMapping("demo1")
    public String demo1() {
        System.out.println("public String demo1() method run!");
        return "success demo1!";
    }
    @RequestMapping("demo2")
    public String demo2(@PathVariable("id") int id) {
        System.out.println("public String demo2() method run!");
        System.out.println("id = " + id);
        return "success demo2!";
    }
    @RequestMapping("demo3")
    public String demo3(@RequestParam("name") String name, @RequestParam("age") int age) {
        System.out.println("public String demo3() method run!");
        System.out.println("name = " + name + ", age = " + age);
        return "success demo3!";
    }
    @RequestMapping("demo4")
    public String demo4(@RequestBody Userinfo userinfo) {
        System.out.println("public String demo4() method run!");
        System.out.println(userinfo.toString());
        return "success demo4!";
    }
    @RequestMapping("demo5")
    public String demo5(@RequestHeader("source") String source) {
        System.out.println("public String demo5() method run!");
        System.out.println(source);
        return "success demo5!";
    }
}

最后通过在消费端注入openfeign接口就可以调用相应的服务端方法了

posted @ 2022-03-16 15:25  蓝狐痕  阅读(1081)  评论(0编辑  收藏  举报