天天看點

Spring Cloud 學習筆記 —— OpenFeign 參數傳遞9.3 OpenFeign 參數傳遞

9.3 OpenFeign 參數傳遞

OpenFeign 傳遞參數,一定要綁定參數名,即有參數要加上 @RequestParam 注解,如果通過 Header 來傳遞參數,一定要中文轉碼,測試 provider 服務中的接口

Spring Cloud 學習筆記 —— OpenFeign 參數傳遞9.3 OpenFeign 參數傳遞
  • (1)在 provider 服務中定義接口如下:
@RestController
public class HelloController{
    @Value("${server.port}")
    Integer port;
    @RequestMapping("/hello")
    public String hello(){
        return "hello   " + port;
    }
    @GetMapping("/hello2")
    public String hello2(String name){
        System.out.println(new Date() + ">>> " + name);
        return "hello" + name;
    }
    @PostMapping("/user2")
    public User addUser2(@RequestBody User user){
        return user;
    }
    @DeleteMapping("/user2/{id}")
    public void deleteUser2(@PathVariable Integer id){
        System.out.println(id);
    }
    @GetMapping("/user3")
    public void getUserByName(@RequestHeader("name") String name) throws UnsupportedEncodingException {
        System.out.println(URLDecoder.decode(name,"UTF-8"));
    }

}
           
  • (2)在 openfeign 中 HelloService
@FeignClient(value = "provider")
public interface HelloService {
    @RequestMapping("/hello")
    String hello();

    @GetMapping("/hello2")
    String hello2(@RequestParam("name") String name);

    @PostMapping("/user2")
    User addUser2(@RequestBody User user);

    @DeleteMapping("/user2/{id}")
    void deleteUser2(@PathVariable("id") Integer id);

    @GetMapping("/user3")
    void getUserByName(@RequestHeader("name") String name) throws UnsupportedEncodingException;
    
}
           
  • (2)在 openfeign 中定義 HelloController,來調用 HelloService
@RestController
public class HelloController {
    @Autowired
    HelloService helloService;
    @GetMapping("/hello")
    public String hello() throws UnsupportedEncodingException {
        String hello = helloService.hello();
        System.out.println(hello);
        String s = helloService.hello2("江南一點雨");
        System.out.println(s);
        User user = new User();
        user.setId(1);
        user.setUsername("javaboy");
        user.setPassword("123");
        User user1 = helloService.addUser2(user);
        System.out.println(user1);
        helloService.deleteUser2(1);
        helloService.getUserByName(URLEncoder.encode("江南一點雨","UTF-8"));
        return hello;

    }
}
           
  • (3)啟動服務,測試接口
    Spring Cloud 學習筆記 —— OpenFeign 參數傳遞9.3 OpenFeign 參數傳遞
Spring Cloud 學習筆記 —— OpenFeign 參數傳遞9.3 OpenFeign 參數傳遞

openfeign中

Spring Cloud 學習筆記 —— OpenFeign 參數傳遞9.3 OpenFeign 參數傳遞

provider 中

Spring Cloud 學習筆記 —— OpenFeign 參數傳遞9.3 OpenFeign 參數傳遞

總結

至此在 OpenFeign 中幾種方式傳遞參數已成功

注解 參數形式
@RequestHeader(“param”) 如果有中文,要進行 URL 編碼 放在請求的 Head 頭中
@RequestParam(“param” GET 請求
@PathVariable(“param”) 請求路徑上
@RequestBody POST 請求的 JSON
不知道 Form 表單

OpenFeign 的傳參方式,簡化了 RestTemplate 代碼,這點跟 Mybatis 有點像,為什麼 Mybatis 寫個 Mapper 接口就能查詢,是架構使用代理模式幫你完成的,這裡的接口也是代理模式,架構幫忙實作的

繼續閱讀