SpringCloud微服務架構系列 -- 服務的註冊、發現與調用

簡介

衆所周知,SpringCloud是一個微服務框架,本質上是基於SpringBoot的一整套實現微服務的框架。包含了服務發現、負載均衡、斷路器、服務網關、分佈式配置等組件。其中服務註冊、發現又有Netflix的Eureka,阿里的Dubbo,Apache的Consul等,本篇文章將以Eureka進行講解。git

Eureka

Eureka是Netflix開發的服務發現框架,自己是一個基於REST的服務。由兩個組件組成:github

  • Eureka Server:也被稱做是服務註冊中心,用於提供服務的註冊與發現。
  • Eureka Client:包含服務消費者與服務生產者。

image.png
圖片來源於互聯網,如侵權可聯繫博主web

Eureka的做用就是將咱們定義的API接口註冊到Eureka服務器上,方便管理,調用的時候只須要知道服務名就能夠,再也不經過IP加端口號的方式調用,利於解耦。spring

服務的註冊與發現

1、新建主項目

  1. 選擇Maven,點擊Next
    image.png
  2. 填寫相關信息,點擊Next
    image.png
  3. 肯定信息無誤後,點擊Finish
    image.png
  4. src文件夾刪除(若是有的話)打開pom.xml文件,添加以下代碼。緩存

    <!--必須指定該父模塊,否則後面子模塊啓動會報錯,很麻煩-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <!--父模塊類型必須爲pom-->
        <packaging>pom</packaging>
    
        <!--包含子模塊-->
        <modules>
    
        </modules>
    
        <!--在父模塊添加web依賴,子模塊可繼承該依賴-->
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>

2、新建Eureka Server

  1. 在項目上右鍵新建Module
    image.png
  2. 選擇Spring Initializr,點擊Next,填寫相關信息,Next
    image.png
  3. 選擇導入Eureka Server 依賴,Next,確認信息,點擊Finish
    image.png
  4. 打開Server模塊的pom.xml文件,修改 <parent>標籤服務器

    <parent>
            <groupId>org.sakura</groupId>
            <artifactId>eureka</artifactId>
            <version>1.0-SNAPSHOT</version>
        </parent>
  5. 打開主模塊的pom.xml文件,在<modules>標籤添加相應的子模塊app

    <!--包含子模塊-->
        <modules>
            <module>Server</module>
        </modules>
  6. 將Server模塊中的application.properties重命名爲application.yml,並添加以下信息,也可直接使用properties文件類型(需修改以下代碼)負載均衡

    # Eureka 服務註冊與發現的組件
    server:
      port: 8080
    
    spring:
      application:
        #服務名,很重要
        name: server
    
    eureka:
      instance:
        hostname: localhost
        #將prefer-ip-address設爲開啓時,將默認顯示服務的地址,而非主機名
    #    prefer-ip-address: true  #以IP地址註冊到服務中心,相互註冊使用IP地址
    #    prefer-ip: 127.0.0.1   #顯式設置服務的地址
    
      client:
        # 下面兩個 false 代表本身是 server,而非 client
        register-with-eureka: false     # 不要使用 eureka 服務進行註冊,即在管理界面不可見
        fetch-registry: false           # 不要在本地緩存註冊表信息
        service-url:
          defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
    #      defaultZone: http://127.0.0.1:${server.port}/eureka/
    
      server:
        #開啓自我保護模式
        enable-self-preservation: false
        #清理無效節點,默認60*1000毫秒,即60秒
        eviction-interval-timer-in-ms: 5000
  7. 修改Server模塊的啓動類,添加@EnableEurekaServer註解便可框架

    @EnableEurekaServer
    @SpringBootApplication
    public class ServerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ServerApplication.class, args);
        }
    
    }
  8. 啓動Server服務,打開http://localhost:8080
    image.png

3、新建Eureka Client

  1. 新建Client模塊,前兩步和以前同樣,只有導入依賴那裏不同
    image.png
  2. 修改子父模塊的pom.xml,與Server模塊同樣
  3. 修改application.yml分佈式

    server:
      port: 8081
    
    spring:
      application:
        # 服務名,很重要
        name: client
    
    eureka:
      instance:
        hostname: localhost
       #以IP地址註冊到服務中心,相互註冊使用IP地址
    #    prefer-ip-address: true
    
      client:
        service-url:
          #服務註冊地址
          defaultZone: http://${eureka.instance.hostname}:8080/eureka
  4. 修改啓動類,添加@EnableEurekaClient註解(@EnableDiscoveryClient或不加均可以)

    @EnableEurekaClient
    @SpringBootApplication
    public class Client1Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Client1Application.class, args);
        }
    
    }
  5. 啓動Client服務(啓動Client前,需保證Server正在運行,否則會報錯),打開剛纔的連接
    image.png
    能夠看到,Client服務已經註冊到服務中心了。這裏可能有小夥伴會發現點擊這個服務的連接是會出現404的,這是由於項目沒有使用到Actuator。

服務的調用

SpringCloud有兩種服務調用的方式

  • Ribbon
  • Feign

1、Ribbon

 SpringCloud Ribbon是一個基於HTTP和TCP的客戶端負載均衡工具,它基於Netflix Ribbon實現。幾乎存在於每個SpringCloud構建的微服務和基礎設施中。由於微服務間的調用,API網關的請求轉發等內容,實際上都是經過Ribbon來實現的。
  1. 再建立一個Client2服務,配置文件中除端口與以前的Client不一樣外,其它都一致,服務名也同樣,這是爲了實現負載均衡。

    server:
      port: 8082
    
    spring:
      application:
        name: client
    
    eureka:
      instance:
        hostname: localhost
        #以IP地址註冊到服務中心,相互註冊使用IP地址
      #    prefer-ip-address: true
    
      client:
        service-url:
          #服務註冊地址
          defaultZone: http://${eureka.instance.hostname}:8080/eureka
  2. 爲兩個Client各添加一個API接口

    @RestController
    public class HelloController {
    
        @GetMapping("/hello")
        public String sayHello(@RequestParam(required = true,name = "name") String name){
            return "Hello " + name + ", 8081";
        }
    }
    @RestController
    public class HelloController {
    
        @GetMapping("/hello")
        public String sayHello(@RequestParam(required = true,name = "name") String name){
            return "Hello " + name + ", 8082";
        }
    }
  3. 再新建一個Robbon模塊,前面基本同樣,依賴不一樣
    image.png
  4. 修改配置文件和pom

    server:
      port: 8083
    
    spring:
      application:
        name: ribbon
    
    eureka:
      instance:
        hostname: localhost
        #以IP地址註冊到服務中心,相互註冊使用IP地址
      #    prefer-ip-address: true
    
      client:
        service-url:
          #服務註冊地址
          defaultZone: http://${eureka.instance.hostname}:8080/eureka
  5. 修改啓動類,需添加一個RestTemplate bean

    @EnableDiscoveryClient
    @SpringBootApplication
    
    public class RibbonApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(RibbonApplication.class, args);
        }
    
        /**
         * 負載均衡配置
*/
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
```
  1. 在Ribbon模塊中加入一個Service和一個Controller

    @Service
    public class HelloService {
    
        @Autowired
        RestTemplate restTemplate;
    
        public String helloService(String name){
            return restTemplate.getForObject("http://client/hello?name="+name,String.class);
        }
    }
    @RestController
    public class HelloController {
    
        @Autowired
        HelloService helloService;
    
        @GetMapping("/hello")
        public String hello(String name){
            return helloService.helloService(name);
        }
    }
  2. 依次啓動Server模塊和其它各模塊
    image.png

    能夠看到,兩個Client和一個Ribbon都已經註冊上去了

  3. 打開http://localhost:8083/hello?name=sakura
    image.png
    每次刷新調用的服務都不一樣,證實客戶端負載均衡成功了

2、Feign

Feign是基於Ribbon實現的工具,採用基於接口的註解

  1. 新建Feign模塊,引入依賴
    image.png
  2. 修改配置文件和pom

    server:
      port: 8084
    
    spring:
      application:
        name: feign
    
    eureka:
      instance:
        hostname: localhost
        #以IP地址註冊到服務中心,相互註冊使用IP地址
      #    prefer-ip-address: true
    
      client:
        service-url:
          #服務註冊地址
          defaultZone: http://${eureka.instance.hostname}:8080/eureka
  3. 修改啓動類,添加@EnableEurekaClient@EnableFeignClients

    @EnableFeignClients
    @EnableEurekaClient
    @SpringBootApplication
    public class FeignApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(FeignApplication.class, args);
        }
    
    }
  4. 建立一個Service接口

    @FeignClient(value = "client")  //value值爲須要調用的服務名
    public interface IFeignService {
    
        @GetMapping("/hello")   //這裏的地址爲須要調用的服務裏相應的接口地址
        String hello(@RequestParam(value = "name")String name);
    }
  5. 使用上面的接口(聲明完上面Feign接口後,其餘Spring管理的類,如Service、Controller均可以直接注入使用,IDEA可能會提示不能注入,可忽略)

    @RestController
    public class HelloController {
    
        @Autowired
        private IFeignService iFeignService;
    
        @GetMapping("/feign/hello")
        public String sayHello(String name){
            return iFeignService.hello(name);
        }
    }
  6. 依次啓動Server模塊和Feign模塊和Client模塊
    image.png
  7. 訪問http://localhost:8084/feign/hello?name=sakura
    image.png

以上相對全面簡潔的介紹了SpringCloud中服務的註冊、發現與調用。代碼已上傳至Github

相關文章
相關標籤/搜索