一:Feign簡介
Feign 是一種聲明式、模板化的 HTTP 客戶端,在 Spring Cloud 中使用 Feign,能夠作到使用 HTTP請求遠程服務時能與調用本地方法同樣的編碼體驗,開發者徹底感知不到這是遠程方法,更感知不到這是個 HTTP 請求。web
Feign 的靈感來源於 Retrofit、JAXRS-2.0 和 WebSocket,它使得 Java HTTP 客戶端編寫更方便,旨在經過最少的資源和代碼來實現和 HTTP API 的鏈接。spring
二:Feign使用步驟
在客戶端集成Feign便可mybatis
第一步:pom依賴app
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
因爲可能特別多的模塊須要調用其餘模塊的項目,那麼就須要進行統一依賴,減小重複依賴:負載均衡
因此將這個依賴添加至父工程裏面編碼
啓動類添加註解開啓遠程調用:spa
package com.cxy; import com.netflix.loadbalancer.BestAvailableRule; import com.netflix.loadbalancer.IRule; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; /*** * @ClassName: PersonApplication * @Description: * @Auther: * @Date: 2019/1/2816:30 * @version : V1.0 */ @SpringBootApplication @EnableEurekaClient //開啓註解,註冊服務 @MapperScan("com.cxy") @EnableFeignClients public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class,args); } @Bean @LoadBalanced //使用負載均衡器Ribbon public RestTemplate getRestTemplate(){ return new RestTemplate(); } /*@Bean public IRule myRule(){ //return new RoundRobinRule();//輪詢 // return new RetryRule();//重試 return new BestAvailableRule(); }*/ }
@EnableFeignClients,這個註解
遠程調用方法首先須要寫一個接口,能夠看成是service:
package com.cxy.service; import com.cxy.dataObject.PersonDo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Component @FeignClient("cxy-person-service") public interface IPersonService { @RequestMapping("/person/{id}") PersonDo getPersonDoById(@PathVariable("id") Integer id); }
contrller調用.net
@Autowired private IPersonService personService;
**/ @RequestMapping(value = "/get/{id}",method = RequestMethod.GET) public PersonDo selectPsersonById(@PathVariable Integer id){ PersonDo personDo =personService.getPersonDoById(id); return personDo; }
啓動訪問:code
直接訪問結果:blog
此處已經成功了