1. 程式人生 > >2、springcloud微服務:基於Feign的服務呼叫

2、springcloud微服務:基於Feign的服務呼叫

摘要:Feign是一個宣告式、模板化的HTTP客戶端呼叫元件,它可以像呼叫本地方法一樣呼叫遠端服務

建立一個新的服務:microservice-provider-user,在microservice-provider-user中使用Feign呼叫microservice-provider-org釋出的服務/org/query/{id}。

1、以microservice-provider-org作為模板建立一個springboot服務:microservice-provider-user,在maven配置中增加依賴:

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

2、修改application.yml的服務名和埠號:

server:  
  port: 9002  
spring:  
  application:  
    name: user-service #服務名,將註冊到eureka註冊中心  
eureka:  
  instance:  
    statusPageUrlPath: ${management.context-path}/info  
    healthCheckUrlPath: ${management.context-path}/health  
  client:  
    serviceUrl:  
      defaultZone: http://localhost:8761/eureka/ #註冊地址,eureka服務地址  

3、啟動類增加Feign註解:@EnableFeignClients。

4、使用Feign呼叫microservice-provider-org釋出的服務:

package com.netsframe.user.service;  
  
import org.springframework.cloud.netflix.feign.FeignClient;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@FeignClient("org-service")  
public interface UserService {  
    @RequestMapping("/org/query/{id}")  
    public String queryOrg(@PathVariable("id") String id);  
}  
@FeignClient:發現microservice-provider-org釋出到註冊中的服務。

5、在controller呼叫UserService:

package com.netsframe.user.rest;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
import com.netsframe.user.service.UserService;  
  
@RestController()  
public class UserController {  
    @Autowired  
    UserService userService;  
  
    @RequestMapping("/user/query/{id}")  
    public String query(@PathVariable("id") String id) {  
        String org = userService.queryOrg(id);  
        return "小陳所屬組織:" + org;  
    }  
}  

6、依次啟動microservice-register-eureka、microservice-provider-org、microservice-provider-user,訪問http://localhost:8761/,顯示如下介面:


從上圖看出,新的服務USER-SERVICE已經發布到註冊中心了,訪問user-service中的請求:http://localhost:9002/user/query/1,返回:


從上面返回結果看,在microservice-provider-user中通過feign呼叫microservice-provider-org釋出的服務成功。

至此,本文介紹的通過Feign呼叫服務結束。