之前搭建的注冊中心:http://blog.csdn.net/chenhaotao/article/details/78677328
服務提供者client:http://blog.csdn.net/chenhaotao/article/details/78677858
服務消費者ribbon:http://blog.csdn.net/chenhaotao/article/details/78678445
之前就使用ribbon搭建了一個服務消費者,今天嘗試使用Feign搭建一個服務消費者項目。
Feign介紹
Feign是一個聲明式的web service用戶端,使用Feign搭建項目十分簡便,隻需要建立一個接口并注解等幾個步驟就可以實作,具有可插拔的注解特性,而且Feign預設內建了Ribbon,并和Eureka結合,預設實作了負載均衡的效果。
項目大緻步驟:
1.建立springboot項目,依賴選擇:eureka,feign,web
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.在配置檔案application.yml配置項目名稱端口和注冊中心位址等
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1111/eureka/
server:
port:
spring:
application:
name: service-feign
3.定義一個feign接口,通過@ FeignClient(“服務名”),來指定調用哪個服務
@FeignClient(value = "SERVICE-HELLO")
public interface TestFeignService {
/**
* @RequestMapping指定調用到服務的那個接口,@RequestParam("name")指定傳入的參數名
*/
@RequestMapping(value = "index",method = RequestMethod.GET)
String testEurekaClient(@RequestParam("name")String name);
}
注:雖然在服務提供者client中定義服務項目名稱為service-hello,但是通過注冊中心url:http://localhost:1111/ 檢視到注冊的服務名稱是以大寫形式注冊的,是以這裡調用服務名字要使用大寫SERVICE-HELLO。
4.建立controller類,通過@Autowired注解注入feign接口并調用接口方法實作消費服務方法
@RestController
public class TestFeignController {
@Autowired
private TestFeignService testFeignService;
@RequestMapping(value = "/testFeign",method = RequestMethod.GET)
public String test(@RequestParam String name){
return testFeignService.testEurekaClient(name);
}
}
浏覽器url輸入:http://localhost:9002/testFeign?name=aaa 可以檢查服務消費是否實作
附上項目源碼:https://pan.baidu.com/s/1mih58Re