Spring Cloud學習系列第四篇【聲明式服務調用】

來源:互聯網
上載者:User

標籤:tco   eth   port   lin   .post   介面調用   抽取   tor   服務   

  之前的隨筆我們訪問其它微服務方式都是通過Ribbon組件提供的一些模板方法去訪問的,使用過程中會發現一個問題就是對某服務介面調用往往不是一處的,於是我們需要這個服務介面進行一個封裝,其它地方統一調用這個封裝,而每個封裝其實也就是對用RestTemplate的模板方法對目標服務介面的調用,這樣代碼裡就會有很多冗餘的RestTemplate方法了,代碼很不優雅,而使用了Spring Cloud Feign就不一樣了,它是Spring Cloud Hystrix和Spring Cloud Ribbon整合,有了它在架構層面Spring Cloud就幫我們封裝好這些東西了,我們只需要定義一個需要訪問目標服務方法的介面,就可以直接通過依賴注入直接使用了,省去了我們自己封裝那一步,代碼也更加優雅了。

  下面改寫一下之前的例子,體驗一下吧。我們新增一個Feign項目作為採用聲明式服務調用這種方式去訪問ServiceA的服務。由於Feign需要定義訪問ServiceA方法的介面,然後ServiceA需要提供對應的HTTP服務,於是我們在新增一個FeignApi項目把公用的介面定義在這,然後Feign和ServiceA依賴FeignApi,達到代碼共用的效果。結合下代碼來理解下。

 

 一、 新增FeignApi項目 

  再次說明FeigApi作用了抽取共用代碼給Feign和ServiceA使用的,哪裡會有共用代碼?這就是需要Feign需要訪問的ServiceA的幾個介面資訊 。

  

  FeignService介面定義需要訪問的URL路徑。

package com.pumpkin.service;import com.pumpkin.dto.User;import org.springframework.web.bind.annotation.*;@RequestMapping("/user")public interface FeignService {    @RequestMapping(value = "/hello1.do", method = RequestMethod.GET)    String hello(@RequestParam("name") String name);    @RequestMapping(value = "/hello2.do", method = RequestMethod.GET)    User hello(@RequestParam("name") String name, @RequestParam("sex") Integer sex);    @RequestMapping(value = "/hello3.do", method = RequestMethod.POST)    String hello(@RequestBody User user);}

 

二、Feign項目使用聲明式調用

  寫個controller作為等下我們調用ServcieA的入口,URL為:127.0.0.1:7000/feign/hello.do

spring.application.name=feign#eureka.instance.instance-id=${spring.application.name}:${random.int}server.port=7000eureka.client.serviceUrl.defaultZone=http://localhost:5001/eureka/,http://localhost:5002/eureka/

 

package com.pumpkin.controller;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import com.pumpkin.dto.User;import com.pumpkin.service.FeignService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/feign")public class FeignController {    @Autowired    private FeignService feignService;    @RequestMapping(value = "/hello.do", method = RequestMethod.GET)    public String feignHello() {        StringBuilder sb = new StringBuilder();        sb.append(feignService.hello("MIMI")).append("\n");        sb.append(feignService.hello("MIMI", 20)).append("\n");        sb.append(feignService.hello(new User("MIMI", 20))).append("\n");        return sb.toString();    }    }

 

 

  編寫FeignServiceImpl介面,因為FeignService在FeignApi項目,所以我們要先依賴FeignApi項目。然後FeignServiceImpl只需要繼承FeignService,並添加@FeignClient(value = "SERVICE-A")註解後就可以通過依賴注入給Controller層的入口使用了。

package com.pumpkin.service.impl;import com.pumpkin.service.FeignService;import org.springframework.cloud.netflix.feign.FeignClient;@FeignClient(value = "SERVICE-A")public interface FeignServiceImp extends FeignService {}

 

 

三、改造ServiceA項目

  新增一個FeignController提供對外服務。可以看到FeignController是通過實現FeignService介面,這樣ServiceA項目就不需要冗餘那個幾個方法的代碼了,直接依賴FeignApi即可。

package com.pumpkin.controller;import com.pumpkin.dto.User;import com.pumpkin.service.FeignService;import org.apache.log4j.Logger;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class FeignController implements FeignService {    private final Logger LOGGER = Logger.getLogger(getClass());    @Override    public String hello(@RequestParam("name")String name) {        return "hello";    }    @Override    public User hello(@RequestParam("name")String name, @RequestParam("sex")Integer sex) {        LOGGER.info("name=" +name+ " ,sex=" +sex);        return new User("pumpkin", 0);    }    @Override    public String hello(@RequestBody User user) {        return "hello user=" +user.toString();    }}

 

 

四、啟動看看效果

五、總結

  Spring Cloud Feign是對Spring Cloud Ribbon和Spring Hystrix封裝整合。這篇隨筆主要介紹了Spring Cloud Feign的簡單使用,對於如何進行服務熔斷和降級並沒有涉及,但從使用層面來講也就是幾個註解的問題,只要對Hystrix機制有一定的理解,使用起來是非常容易的,另外Feign並沒有對Hysrix的請求合并和請求緩衝進行封裝,所以需要這些功能的話,只能使用回Ribbon了。

 六、參考資料

Spring Cloud微服務實戰-翟永超。本系列的學習都是參考該書籍學習的,同時源碼使用的Spring Boot和Spring Cloud的版本也與該書保持一致。

七、源碼

碼雲地址:[email protected]:pumpkingg/Spring-Cloud-Study.git 該篇隨筆對應的代碼是master分支下命名為blog3的Tag

 

  

 

Spring Cloud學習系列第四篇【聲明式服務調用】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.