OpenFeign 传递普通表单参数

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2023年3月28日 (二) 05:28的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1My4y1W7vy?p=4

被调用的 application service

import io.github.jihch.pojo.People;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class DemoController {

    @RequestMapping("/demo2")
    public String demo2(String name, Integer age) {
        return "name:" + name + ",age:" + age;
    }

}


使用 OpenFeign 调用的 application client

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

@FeignClient("MYPROJECT")
public interface ServiceDemoFeign {

    /**
     * 在 OpenFeign 中方法参数前如果没有注解,默认添加 @RequestBody 注解,最多只能存在一个不带注解的参数
     *
     * 普通表单参数必须添加 @RequestParam 注解。如果变量名和参数名称对应可以不写 name
     *
     * @return
     */
    @RequestMapping("/demo2")
    String suiyi2(@RequestParam String name, @RequestParam Integer age);

}
public interface FeignDemoService {

    String demo();

    String demo2(String name, Integer age);

}
import io.github.jihch.feign.ServiceDemoFeign;
import io.github.jihch.service.FeignDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FeignDemoServiceImpl implements FeignDemoService {

    @Autowired
    private ServiceDemoFeign serviceDemoFeign;

    @Override
    public String demo() {
        return serviceDemoFeign.suiyi();
    }

    @Override
    public String demo2(String name, Integer age) {
        return serviceDemoFeign.suiyi2(name, age);
    }
}
import io.github.jihch.service.FeignDemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FeignDemoController {

    @Autowired
    private FeignDemoService feignDemoService;

    @RequestMapping("/demo")
    public String demo() {
        return feignDemoService.demo();
    }

    @RequestMapping("/demo2")
    public String demo2(String name, Integer age) {
        return feignDemoService.demo2(name, age);
    }

}

访问:http://localhost:8088/demo2?name=abc&age=15 进行测试