Spring Cloud 之 Feign 使用HTTP請求遠程服務


  Feign是從Netflix中分離出來的輕量級項目,能夠在類接口上添加注釋,成為一個REST API 客戶端,Feign默認集成了Ribbon。

  Feign中對 Hystrix 有依賴關系。Feign只是一個便利的rest框架,簡化調用,最后還是通過ribbon在注冊服務器中找到服務實例,然后對請求進行分配

  Feign是一種聲明式、模板化的HTTP客戶端。在Spring Cloud中使用Feign, 我們可以做到使用HTTP請求遠程服務時能與調用本地方法一樣的編碼體驗,開發者完全感知不到這是遠程方法,更感知不到這是個HTTP請求。

一、使用方式

  1、首先寫好需要注冊進注冊中心的服務接口UserServiceController,該接口相當於service層,只是以RestFULL接口的形式供遠程調用

@RestController
@RequestMapping("userService")
public class UserServiceController {

    @GetMapping("getUser/{userId}")
    public User getUser(@PathVariable("userId") String userId){
        System.out.println("獲取User,更具UserId,查詢User-->" + userId);
        User user = new User();
        user.setUserName("Tom");
        user.setPassword("123");return user;
    }

    @PostMapping("saveUser")
    public String saveUser(@RequestBody User user){
        System.out.println("保存User--->" + JSON.toJSONString(user));
        return "userId:010100100101";
    }

    @GetMapping("deleteUser/{userId}")
    public Boolean deleteUser(@PathVariable("userId") String userId){
        System.out.println("刪除用戶--->" + userId);
        return true;
    }

    @RequestMapping(value = "findUserByUserNameAndPassword")
    public User findUserByUserNameAndPassword(String userName, String password){
        System.out.println("userService--->" + userName + "  password--->" + password);
        User user = new User();
        user.setUserName("Tomcat");
        user.setPassword("123");return user;
    }

  2、在請求遠程服務的項目的POM.XML文件中引入對Feign依賴

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

  3、創建FeignClient 

@FeignClient(value="springcloud-userservcie")
public interface UserClient {

    @RequestMapping(value = "userService/getUser/{userId}", method = RequestMethod.GET)
    public User getUser(@PathVariable("userId") String userId);

    @RequestMapping(value = "userService/saveUser", method = RequestMethod.POST)
    public String saveUser(User user);

    @RequestMapping(value = "userService/deleteUser/{userId}", method = RequestMethod.GET)
    public Boolean deleteUser(@PathVariable("userId") String userId);

    @RequestMapping(value = "userService/findUserByUserNameAndPassword", method = RequestMethod.GET)
    public User findUserByUserNameAndPassword(@RequestParam("userName") String userName, @RequestParam("password") String password);    

}
  • @FeignClient(value="springcloud-userservcie"):用於通知Feign組件對該接口進行代理(不需要編寫接口實現),value屬性指定我們要調用注冊中心的服務ID。使用者可直接通過@Autowired注入。
  • @RequestMapping表示在調用該方法時需要向/group/{groupId}發送請求。
  • @PathVariable與SpringMVC中對應注解含義相同。

原理:Spring Cloud應用在啟動時,Feign會掃描標有@FeignClient注解的接口,生成代理,並注冊到Spring容器中。生成代理時Feign會為每個接口方法創建一個RequetTemplate對象,該對象封裝了HTTP請求需要的全部信息,請求參數名、請求方法等信息都是在這個過程中確定的,Feign的模板化就體現在這里

  4、在Controller調用

@RestController
@RequestMapping("userClient")
public class UserController {
    @Autowired
    private UserClient userClient;

    @RequestMapping(value = "getUser/{userId}", method = RequestMethod.GET)
    public User getUser(@PathVariable("userId") String userId){
        return userClient.getUser(userId);
    }

    @RequestMapping(value = "saveUser", method = RequestMethod.POST)
    public String saveUser(User user){

        return userClient.saveUser(user);
    }

    @RequestMapping(value = "deleteUser/{userId}", method = RequestMethod.GET)
    public Boolean deleteUser(@PathVariable("userId") String userId){

        return userClient.deleteUser(userId);
    }

    @RequestMapping(value = "findUserByUserNameAndPassword")
    public User findUserByUserNameAndPassword(String userName, String password){
        System.out.println("userClient--->" + userName + "  password--->" + password);
        return userClient.findUserByUserNameAndPassword(userName, password);
    }

}

  5、啟動類上添加Feign注解@EnableFeignClients

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM