1. 程式人生 > >SpringCloud從入門到進階(三)——路由接入Zuul

SpringCloud從入門到進階(三)——路由接入Zuul

comm aml header main text nco 整合 utf8 json

內容

  SpringBoot整合SpringCloud的Eureka、Zuul等組件,快速實現簡單易懂且具有服務熔斷、負載均衡的分布式架構1.0,體驗微服務的魅力。

版本

  IDE:IDEA 2017.2.2 x64

  JDK:1.8.0_171

  manve:3.3.3

  SpringBoot:1.5.9.RELEASE

  SpringCloud:Dalston.SR1

適合人群

  ?Java開發人員

說明

  轉載請說明出處:SpringCloud從入門到進階(三)——路由接入Zuul

參考

Linux入門實踐筆記(二)--Jar包運行與關閉

SpringCloud從入門到進階(二)——註冊中心Eureka

步驟

項目路徑

技術分享圖片

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId
>springcloud</artifactId> <groupId>com.leo</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>gateway-service-7081-7082</artifactId> ? <dependencies> <!--
zuul組件實現網關的路由轉發和負載均衡--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <!--eureka client--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!--actuator監控--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <!-- Spring Boot的Maven插件,使用Maven插件的方式來啟動Spring Boot工程 如果不添加該插件在使用mvn命令打包的jar有問題,執行時會報錯:xxx.jar中沒有主清單屬性--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
yaml

?   本示例暫不配置Zuul的高可用,peer2的配置註釋掉。

spring:
  application:
   name: application-gatewayservice
  profiles:
   active: peer1
?
#Zuul的配置
zuul:
  prefix: /jms  #通過zuul.prefix的配置,所有請求統一增加前綴,可以實現API接口的版本號控制,註意前綴要加/
  #如果某服務存在多個實例,Zuul結合Ribbon會做負載均衡,將請求均分的部分路由到不同的服務實例。
  routes:
   culturalService:  #此處的名稱是用戶自定義的,需要指定它的path和serviceld,兩者配合使用,就可以將指定類型的請求Uri路由到指定的Serviceld
     path: /cultural/**    #以/cultural/** 開頭的請求都轉發給springcloud-culturalService
     serviceId: application-culturalService  #此處是spring的applicationname,即Eureka的服務名,而非instance-id 實例名。
   idleTimeService:
     path: /idleTime/**
     serviceId: application-idleTimeService
   idleGoodService:
     path: /idleGood/**
     serviceId: application-idleGoodService
   topicService:
     path: /topic/**
     serviceId: application-topicService
   publicWelfareService:
     path: /publicWelfare/**
     serviceId: application-publicWelfareService
   commonService:
     path: /common/**
     serviceId: application-commonService
#指明日誌存放位置
logging:
  file: logs/application-gatewayservice-${server.port}.logs
?
eureka:
  client:
   service-url:
     defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
---
spring:
  profiles: peer1
server:
  port: 7081
?
?
eureka:
  instance:
   instance-id: springcloud-gatewayservice-7081
?
management:
  port: 7181
  security:
   enabled: false
#---
#spring:
#  profiles: peer2
#server:
#  port: 7082
#
#management:
#  port: 7182
#  security:
#   enabled: false
#
#eureka:
#  instance:
#   instance-id: springcloud-gatewayservice-7082
SpringApplication
@EnableZuulProxy //開啟Zuul的功能
@SpringBootApplication
@EnableEurekaClient
public class GatewayServiceApplicaton {
    public static void main(String[] args) {
        SpringApplication.run(GatewayServiceApplicaton.class,args);
   }
}
logback-spring.xml
<!-- 加載日誌文件 -->
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include  resource="org/springframework/boot/logging/logback/base.xml"/>
    <jmxConfigurator/>
</configuration>
Zuul斷路器
@Component
public class MyFallbackProvider implements ZuulFallbackProvider {
?
    /**
     * getRoute()方法,用於指定熔斷功能應用於哪些路由的服務。
     * 如果需要所有的路由服務都加熔斷功能,只需要在getRoute()方法上返回"*"的匹配符,
     */
    @Override
    public String getRoute() {
        return "*"; //所有路由服務都增加熔斷。
   }
?
    /**
     * fallbackResponse()為進入熔斷功能時執行的邏輯
     */
    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.SERVICE_UNAVAILABLE;
           }
?
            @Override
            public int getRawStatusCode() throws IOException {
                return 503;
           }
?
            @Override
            public String getStatusText() throws IOException {
                return "Service_Fallbcak";
           }
?
            @Override
            public void close() {
?
           }
?
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("您好,服務出現故障,請重試。".getBytes("utf-8"));
           }
?
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
           }
       };
   }
}
項目打包

  在命令行工具中進入項目pom文件所在路徑,然後執行mvn clean package打包。

  過程可參考:SpringCloud從入門到進階(二)——註冊中心Eureka

拷貝

  使用Bitvise SFTP或WinSCP等工具將jar包上傳到有公網的服務器,再使用scp命令將jar包拷貝到路由接入服務器普通用戶的~/jars路徑下。

技術分享圖片

  過程可參考:SpringCloud從入門到進階(二)——註冊中心Eureka

修改hosts文件

  將內部域名eureka7001.com、eureka7002.com、eureka7003.com綁定到局域網IP 172.26.125.118,將gateway7081.com綁定到局域網IP 172.26.125.117。並將微服務的主機名綁定到對應的局域網IP(不加會出現無法路由的問題,詳見第4節)。

?  修改/etc/hosts,添加hostname對應的ip地址

#IP     域名      別名
[jms@iz8vb62snc6e5cage5yvzcz jars]$ sudo vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
172.26.125.118   eureka7001.com 
172.26.125.118   eureka7002.com 
172.26.125.118   eureka7003.com
127.0.0.1   gateway7081.com
#不加會出現無法路由的問題,詳見系列文章第(四)節
172.26.125.113  iz8vb6a56ld0vy6vuaijriz  
172.26.125.111  iz8vb6a56ld0vy6vuaijrjz

  重啟網卡

[jms@iz8vb62snc6e5cage5yvzcz jars]$ sudo /etc/rc.d/init.d/network restart
Restarting network (via systemctl):                       [  OK  ]

  進行ping測試

[jms@iz8vb62snc6e5cage5yvzcz jars]$  ping eureka7001.com
PING eureka7001.com (172.26.125.118) 56(84) bytes of data.
64 bytes from eureka7001.com (172.26.125.118): icmp_seq=1 ttl=64 time=0.143 ms
64 bytes from eureka7001.com (172.26.125.118): icmp_seq=2 ttl=64 time=0.149 ms
[jms@iz8vb62snc6e5cage5yvzcz jars]$ ping gateway7081.com
PING gateway7081.com (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.015 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.023 ms
#可見訪問本機和訪問局域網的網絡延遲差1個數量級。
啟動與測試
[jms@iz8vb62snc6e5cage5yvzcz jars]$ java -jar gateway-service-7081-7082-1.0-SNAPSHOT.jar  --spring.profiles.active=peer1 &

  訪問eureka服務器

技術分享圖片

  使用postman請求API,由於微服務還未部署,因此請求對應接口會報503錯誤(服務熔斷)。

技術分享圖片

關閉

  關閉java程序請參考:Linux入門實踐筆記(二)--Jar包運行與關閉

SpringCloud從入門到進階(三)——路由接入Zuul