Spring Clound用Eureka和Feign實現微服務發現、註冊和調用

一、Eureka實現服務發現和註冊

1.新建maven空的父項目(SpringCloud)

由於使用的模塊型開發,故創建一個父工程,用於儲存子模塊共用的依賴,下面是文件夾樹

2)pom文件依賴如下

    <!-- lookup parent from repository -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/> 
    </parent>

    <!-- 子模塊依賴不用顯示錶明依賴版本,統一沿用父項目的依賴版本 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Edgware.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

3)新建子模塊註冊中心maven工程(Eureka'Server1),子模塊依賴如下

    <dependencies>
        <!-- Eureka服務端開始 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
        <!-- Eureka服務端結束 -->
    </dependencies>

4)編寫註冊中心配置文件,application.yml,不設置defaultZone時,默認是http://localhost:8761/eureka

#註冊中心端口
server:
  port: 8083
eureka:
  client:
    #由於註冊中心的職責就是維護服務實例,它並不需要去檢索服務,所以也設置爲false
    fetch-registry: false 
    #由於該應用爲註冊中心,所以設置爲false,代表不向註冊中心註冊自己
    register-with-eureka: false 
    service-url:
      defaultZone: http://localhost:8083/eureka
#是否優先從文件系統加載template
spring:
  freemarker:
    prefer-file-system-access: false

5)編寫啓動類,一個簡單java類就行,如果不配置去除數據庫源,啓動時會找不到數據庫源而報異常

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * 去除自動注入數據庫源
 * exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}
 * Eureka服務端聲明註解標籤EnableEurekaServer
 */
@EnableEurekaServer
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class EurekaServer {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer.class);
    }
}

6)啓動和訪問註冊中心界面,http://localhost:8083/,看到如下界面證明註冊中心啓動成功。

2.服務發現和註冊

1)編寫子模塊maven工程(FeignClient1),導入依賴,pom文件內容如下

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- euraka實現服務發現和註冊的依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <!-- Feign依賴,爲使用Feign進行服務調用作準備,服務註冊和發現時可不導入 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2)編寫application.yml配置文件

server:
  port: 8082
spring:
  application:
    name: FeignConsumer #在註冊中心註冊服務時使用的名字   
  freemarker:
    prefer-file-system-access: false
eureka:
  client:
    service-url:
       #必須配上和註冊中心一樣的地址,否則註冊不成功
      defaultZone: http://localhost:8083/eureka
#Feign在新版本中默認是沒有開啓Hystrix的功能
#必須開啓Hystrix才能回調成功(被調用服務異常時回調)
feign:
  hystrix:
    enabled: true

3)編寫服務註冊和發現啓動類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

/**
 * EnableEurekaClient配置被註冊中心發現
 * EnableFeignClients配置爲進行服務調用
 */
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}

4)啓動服務,進入註冊中心頁面再次查看,可查看到該服務,默認是使用主機名進行註冊。

二、Feign實現服務調用和異常回調

1.編寫服務提供方

1)編寫子模塊maven工程(FeignClient2),pom依賴如下,作爲服務提供方時可不導入feign依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2)編寫配置文件application.yml

server:
  port: 8084
spring:
  application:
    name: FeignProvider #註冊在註冊中心的服務名字,需提供給消費方使用
  freemarker:
    prefer-file-system-access: false
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8083/eureka

3)編寫提供給消費方使用的服務,controller類

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 提供給消費方的服務
 */
@RestController
public class FeignProController {
    private Logger log = Logger.getLogger(FeignProController.class);
    @Autowired
    public DiscoveryClient discoveryClient;

    @RequestMapping("/getInfo")
    public String hello(@RequestParam("name") String name){
        ServiceInstance serviceInstance = discoveryClient.getLocalServiceInstance();
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String info = "hello name="+ name + ",host=" + host + ",port=" + port;
        log.info(info);
        return info;
    }
}

4)編寫服務啓動類,被調用的服務也可以在註冊中心註冊

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient
@SpringBootApplication
public class FeignProApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignProApplication.class);
    }
}

5)啓動服務提供方

2.編寫服務消費方

由於在服務註冊和發現時已經建立了子模塊(FeignClient1),這裏繼續往下進行。

1)編寫FeignServiceClient接口,必須爲接口,類是不可以的,代碼如下

import com.dc.wangrt.service.impl.FeignServiceClientFallback;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * FeignProvider爲被調用的服務在註冊中心上註冊的名字
 * fallback配置是當被調用服務掛掉之後所產生的回調,這裏是回調到另一個類
 */
@FeignClient(value = "FeignProvider",fallback = FeignServiceClientFallback.class)
public interface FeignServiceClient {
    //該方法必須和被調用服務的定義一致
    @RequestMapping("/getInfo")
    public String hello(@RequestParam("name") String name);
}

2)編寫1)中接口實現類,即回調類(FeignServiceClientFallback),回調時必須在application.yml中顯示設置feign.hystrix.enabled=true,因爲新版本中Hystris默認是不開啓的

import com.dc.wangrt.service.FeignServiceClient;
import org.springframework.stereotype.Component;

/**
 * 回調內容
 */
@Component
public class FeignServiceClientFallback implements FeignServiceClient {
    @Override
    public String hello(String name) {
        System.out.println("回調成功!!!");
        return "sorry " + name + ", feign client error";
    }
}

3)編寫調用服務類(FeignController)

import com.dc.wangrt.service.FeignServiceClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class FeignController {
    private Logger log = Logger.getLogger(FeignController.class);

    @Autowired
    private FeignServiceClient feignServiceClient;

    @GetMapping("/getInfo")
    public String hello(@RequestParam("name") String name){
        String info = feignServiceClient.hello(name);
        log.info(info);
        return info;
    }
}

4)服務啓動,訪問http://localhost:8082/getInfo?name=wangrt,可以看到服務被正常調用

5)把被調用服務關閉之後,再次調用,可以看到進行回調了,證明異常時服務也可以正常回調,不會拋出異常

三、總結

          至此,使用Eureka實現服務發現、註冊和Feign實現服務的調用和異常時回調就完成了,歡迎大家在評論區多多點評,一起學習,共同進步。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章