Feign實現RPC呼叫
阿新 • • 發佈:2019-02-15
前言
Feign的中文名稱翻譯過來是偽裝
那麼Feign偽裝的是什麼呢?答案很明確,Feign偽裝的是服務提供者。
Feign可以用來做什麼?既然能偽裝,當然能提供服務提供者的功能,即RPC呼叫服務提供者功能。
一、構建Feign
step1
新建一個SpringBoot專案,匯入web,feign,eureka client的pom依賴;這種依賴在各種IDE及SpringBoot構建網頁上都是直接輸入關鍵字按Enter就可以的
step2
配置application.yml檔案,還是用前兩篇的Eureka server
eureka: client: serviceUrl: defaultZone: http://server1:20001/eureka/ server: port: 8766 spring: application: name: service-feign
step3
配置負載均衡策略,新建一個類,配置bean Irule就可以了
import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RandomRule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LoadBalancerConfig { @Bean public IRule getRule() { return new RandomRule(); } }
step4
主類開啟Feign註解@EnableFeignClients,即允許開啟Feign
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; @EnableEurekaClient @EnableFeignClients @SpringBootApplication public class FeignApplication { public static void main(String[] args) { SpringApplication.run(FeignApplication.class, args); } }
step5
關鍵步驟來了,建立一個偽服務提供者介面(不需要實現),你偽裝誰@FeignClient的value就寫誰的名字。呼叫哪個介面就在RequestMapping 的value標註那個介面的url,方法名隨便起,引數要給人間傳過去
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "service-hi")
public interface ServiceFeign {
@RequestMapping(value = "/hi", method = RequestMethod.GET)
String sayHi(@RequestParam(value = "name") String name);
}
step6
建立一個Controller便於前端觀察
@RestController
public class FeignController {
@Autowired
private ServiceFeign serviceFeign;
@GetMapping(value = "/hi")
public String sayHi(@RequestParam String name) {
return serviceFeign.sayHi(name);
}
}
step7
啟動eureka server,啟動三個service-hi,啟動service-feign,點選service-feign
step8
輸入url,多次重新整理,發現確實是按照負載均衡的隨機策略來的
image.png