搭建微服務步驟


1 搭建注冊中心eureka


  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>2.0.0.RELEASE</version>
   </dependency>
 
 
 配置 yml文件
 server:
  port: 7001

eureka:
  instance:
    hostname: localhost
  client:
  #聲明自己是個服務端
    registerWithEureka: false    #false表示不向注冊中心注冊自己
    fetchRegistry: false         #false表示自己就是注冊中心,職責是維護實例,不參加檢索
    serviceUrl:                  #設置eureka server的交互地址,即對外暴露的地址
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

 

2  注冊服務到服務中心

   server: port: 8001 #指定注冊中心地址 eureka: client: serviceUrl: defaultZone: http://localhost:7001/eureka/ #服務的名稱 spring: application: name: product-service

  

 

 3   微服務要引入接口調用jar 實現注解式編程

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

 

   

在使用Feign的時候,要注意使用requestBody,應該使用@PostMapping

 

    1、執行流程

 

    總到來說,Feign的源碼實現的過程如下:

 

   (1)首先通過@EnableFeignCleints注解開啟FeignCleint

 

   (2)根據Feign的規則實現接口,並加@FeignCleint注解

 

   (3)程序啟動后,會進行包掃描,掃描所有的@ FeignCleint的注解的類,並將這些信息注入到ioc容器中。

 

   (4)當接口的方法被調用,通過jdk的代理,來生成具體的RequesTemplate

 

   (5)RequesTemplate在生成Request

 

   (6)Request交給Client去處理,其中Client可以是HttpUrlConnection、HttpClient也可以是Okhttp

 

   (7)最后Client被封裝到LoadBalanceClient類,這個類結合類Ribbon做到了負載均衡。

 

2、Feign和Ribbon比較優點

 

  (1) feign本身里面就包含有了ribbon,只是對於ribbon進行進一步封裝

 

  (2) feign自身是一個聲明式的偽http客戶端,寫起來更加思路清晰和方便

 

  (3) fegin是一個采用基於接口的注解的編程方式,更加簡便

4、網關搭建

       導入網關jar

   <!--客戶端jar包,這個在訂單微服務,商品微服務都要添加-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- zuuljar包 網關 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

server:
port: 6001


#服務的名稱
spring:
application:
name: zuul-gateway



#指定注冊中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:7001/eureka/

#/order-service/api/v1/order/save?user_id=2&product_id=1
#自定義路由映射
zuul:
routes:
order-service: /apigateway/order/**
product-service: /apigateway/product/**
#統一入口為上面的配置,其他入口忽略
ignored-patterns: /*-service/**
#忽略整個服務,對外提供接口
ignored-services: order-service

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM