天天看點

Eureka服務發現架構和微服務調用元件Feign

作者:tianlongbabu
Eureka服務發現架構和微服務調用元件Feign

1.服務發現元件 Eureka

Eureka是Netflix開發的服務發現架構,SpringCloud将它內建在自己的子項目spring-cloud-netflix中,實作 SpringCloud的服務發現功能。Eureka包含兩個元件:Eureka Server和Eureka Client。

  • Eureka Server提供服務注冊服務,各個節點啟動後,會在Eureka Server中進行注冊,這樣EurekaServer中 的服務系統資料庫中将會存儲所有可用服務節點的資訊,服務節點的資訊可以在界面中直覺的看到。
  • Eureka Client是一個java用戶端,用于簡化與Eureka Server的互動,用戶端同時也就别一個内置的、使用輪 詢(round-robin)負載算法的負載均衡器。在應用啟動後,将會向Eureka Server發送心跳,預設周期為30秒, 如果Eureka Server在多個心跳周期内沒有接收到某個節點的心跳,Eureka Server将會從服務系統資料庫中把這個 服務節點移除(預設90秒)。

1.1Eureka服務端開發

(1)建立ihrm_eureka子產品

(2)引入依賴 父工程pom.xml定義SpringCloud版本

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>           

ihrm_eureka子產品pom.xml引入eureka-server

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
</dependencies>           

(3)ihrm_eureka子產品添加application.yml

server:
  port: 6868 #服務端口
eureka:
  client:
    registerWithEureka: false #是否将自己注冊到Eureka服務中,本身就是所有無需注冊
    fetchRegistry: false #是否從Eureka中擷取注冊資訊
    serviceUrl: #Eureka用戶端與Eureka服務端進行互動的位址
      defaultZone: http://127.0.0.1:${server.port}/eureka/           

(4) 配置啟動類

/**
 * Eure服務端
 */
@SpringBootApplication
@EnableEurekaServer
public class EureApplication {

    public static void main(String[] args) {
        SpringApplication.run(EureApplication.class);
    }
}
           

1.2 微服務注冊

(1)将其他微服務子產品添加依賴

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>           

(2)修改每個微服務的application.yml,添加注冊eureka服務的配置

#微服務注冊到eureka配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:6868/eureka/           

(3)修改每個服務類的啟動類,添加注解

@EnableEurekaClient           

最終,eureka服務運作之後界面如下:

http://localhost:6868/

Eureka服務發現架構和微服務調用元件Feign

2.微服務調用元件Feign

Feign是簡化Java HTTP用戶端開發的工具(java-to-httpclient-binder),它的靈感來自于Retrofit、JAXRS-2.0和 WebSocket。Feign的初衷是降低統一綁定Denominator到HTTP API的複雜度,不區分是否為restful

2.1搭建Feigh調用

(1)在ihrm_system子產品添加依賴

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

(2)修改ihrm_system子產品的啟動類,添加注解

@EnableDiscoveryClient
@EnableFeignClients           

(3)在Ihrm_system子產品建立com.ihrm.system.client包,包下建立接口

其中@FeignClient("ihrm-company")指定需要調用的某個其他微服務名稱,該名稱在yml檔案中已配置如下

#spring配置
spring:
  #1.應用配置
  application:
    name: ihrm-company #指定服務名           
package com.ihrm.system.client;

import com.ihrm.common.entity.Result;
import com.ihrm.domain.company.Department;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 聲明接口,通過feign調用其他微服務
 */
//聲明調用的微服務名稱
@FeignClient("ihrm-company")
public interface DepartmentFeignClient {

    /**
     * 調用微服務的接口
     */
    @RequestMapping(value="/company/department/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable(value="id") String id);

    @RequestMapping(value="/company/department/search",method = RequestMethod.POST)
    public Department findByCode(@RequestParam(value="code") String code, @RequestParam(value="companyId") String companyId);
}
           

(4)修改Ihrm_system子產品的 UserController

@Autowired
private DepartmentFeignClient departmentFeignClient;


/**
 * 測試Feign元件
 * 調用系統微服務的/test接口傳遞部門id,通過feign調用部門微服務擷取部門資訊
 */
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
public Result testFeign(@PathVariable(value = "id") String id) {
    Result result = departmentFeignClient.findById(id);
    return result;
}           

(5)配置Feign攔截器添加請求頭

在ihrm_common服務添加,友善其他子產品都可以調用。

package com.ihrm.common.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Configuration
public class FeignConfiguration {
    //配置feign攔截器,解決請求頭問題
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {

            //擷取所有浏覽器發送的請求屬性,請求頭指派到feign
            public void apply(RequestTemplate requestTemplate) {
                //請求屬性
                ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if(attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    //擷取浏覽器發起的請求頭
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if (headerNames != null) {
                        while (headerNames.hasMoreElements()) {
                            String name = headerNames.nextElement(); //請求頭名稱 Authorization
                            String value = request.getHeader(name);//請求頭資料 "Bearer b1dbb4cf-7de6-41e5-99e2-0e8b7e8fe6ee"
                            requestTemplate.header(name,value);
                        }
                    }
                }

            }
        };
    }
}
           

繼續閱讀