前段时间spring boot 2.0发布了,与之对应的spring cloud Finchley版本也随之而来了,两者之间的关系和版本对应详见我这边文章:spring boot和spring cloud对应的版本关系

项目地址:spring-cloud-demo

spring boot 1.x和spring cloud Dalston和Edgware版本搭建的微服务项目现在已经很流行了,现在很多企业都已经在用了,这里就不多说了。

使用版本说明:

spring boot 2.0.x

spring cloud Finchley.RELEASE

jdk 1.8

maven 3.9

Eureka 注册中心

spring cloud Finchley在支持spring 2.0时修改了eureka的jar包,把之前netflix系列的jar引入的时候都加上了netflix

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

新建一个eureka-service注册中心服务,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">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.sunvalley</groupId>
   <artifactId>eureka-service</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>eureka-service</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>com.sunvalley.springcloud</groupId>
      <artifactId>spring-cloud-demo</artifactId>
      <version>0.0.1-SNAPSHOT</version>
   </parent>

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

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

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

eureka-service服务的配置文件,application.yml

spring:
  application:
    name: eureka-service

server:
  port: 5000

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

eureka-service服务的配置文件,EurekaServiceApplication

@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {

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

使用IDEA启动eureka-service服务,本地访问 http://localhost:5000/ 即可看到注册中心内容。

服务消费者consumer和提供者provider

实际工作中大多数一个服务既是其它服务的消费者又有可能是服务的提供者,所以我们也就不用刻意的取区分开。

新建一个order-service服务,pom.xml文件

注意:除了eureka-client,openfeign等jar包外,记得引入spring-boot-starter-web不然会出现启动报错。

<?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">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.sunvalley</groupId>
   <artifactId>order-service</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>order-service</name>
   <description>Demo project for Spring Cloud</description>

   <parent>
      <groupId>com.sunvalley.springcloud</groupId>
      <artifactId>spring-cloud-demo</artifactId>
      <version>0.0.1-SNAPSHOT</version>
   </parent>

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

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>

      <!--  eureka 里面已经包含 ribbon 了, 所以不用单独添加, ribbon依赖, 点击依赖就去看就知道了  -->
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      </dependency>

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

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

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>

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

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

   <repositories>
      <repository>
         <id>spring-snapshots</id>
         <name>Spring Snapshots</name>
         <url>https://repo.spring.io/snapshot</url>
         <snapshots>
            <enabled>true</enabled>
         </snapshots>
      </repository>
      <repository>
         <id>spring-milestones</id>
         <name>Spring Milestones</name>
         <url>https://repo.spring.io/milestone</url>
         <snapshots>
            <enabled>false</enabled>
         </snapshots>
      </repository>
   </repositories>

   <pluginRepositories>
      <pluginRepository>
         <id>spring-snapshots</id>
         <name>Spring Snapshots</name>
         <url>https://repo.spring.io/snapshot</url>
         <snapshots>
            <enabled>true</enabled>
         </snapshots>
      </pluginRepository>
      <pluginRepository>
         <id>spring-milestones</id>
         <name>Spring Milestones</name>
         <url>https://repo.spring.io/milestone</url>
         <snapshots>
            <enabled>false</enabled>
         </snapshots>
      </pluginRepository>
   </pluginRepositories>


</project>

order-service服务的配置文件,application.yml

spring:
  application:
    name: order-service

server:
  port: 5100

eureka:
  client:
    service-url:
      defaultZone: http://localhost:5000/eureka/


feign:
  hystrix:
    enabled: true

order-service服务的启动类,OrderServiceApplication

@EnableCircuitBreaker
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class OrderServiceApplication {

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

order-service服务的接口,OrderController

@RestController
@RequestMapping("/order")
public class OrderController {
    @Value("${server.port}")
    private String port;

    /**
     * 获取服务端口号
     * @return
     */
    @GetMapping("/getOrderPort")
    public String getOrderPort() {
        return "order-service port:" + port;
    }
}

新建一个user-service服务,pom.xml文件跟order-service一样的这里就不列出来了

user-service服务的配置文件,application.yml

spring:
  application:
    name: user-service

server:
  port: 5200

eureka:
  client:
    service-url:
      defaultZone: http://localhost:5000/eureka/

feign:
  hystrix:
    enabled: true

user-service服务的启动类也跟order-service一样的

在user-service工程目录下新建一个package,再新建一个OrderRemote接口使用feign调用order-service的方法

@FeignClient(value = "order-service", fallback = OrderRemoteHystrix.class)
public interface OrderRemote {
    @GetMapping("/order/getOrderPort")
    String getOrderPort();
}

熔断机制提示类

@Component
public class OrderRemoteHystrix implements OrderRemote {
    @Override
    public String getOrderPort() {
        return "order service 调用失败!";
    }
} 

user-service服务的接口,UserController

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    OrderRemote orderRemote;
    @Value("${server.port}")
    String port;

    /**
     * 获取用户服务的端口
     * @return
     */
    @GetMapping("/getUserPort")
    public String getUserPort() {
        return "user-service port:" + port;
    }

    /**
     * 获取订单服务的端口
     * @return
     */
    @GetMapping("/getOrderPort")
    public String getOrderPort() {
        return "user-order-service port:" + orderRemote.getOrderPort();
    }
}

测试,分别启动eureka-service,order-service,user-service就可以在注册中心看到服务

在浏览器访问 http://localhost:5100/order/getOrderPort 调用order-service的接口

 

在浏览器访问 http://localhost:5200/user/getOrderPort 通过user-service使用feign声明式调用order-service的接口

关闭order-service,再次调用就会发现熔断机制起了作用

spring cloud gateway

Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等。

新建一个gateway-service服务,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">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.sunvalley</groupId>
   <artifactId>gateway-service</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>gateway-service</name>
   <description>Demo project for Spring Cloud</description>

   <parent>
      <groupId>com.sunvalley.springcloud</groupId>
      <artifactId>spring-cloud-demo</artifactId>
      <version>0.0.1-SNAPSHOT</version>
   </parent>

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

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-gateway</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>


</project>

gateway-service的配置文件,application.yml

spring:
  application:
    name: gateway-service
  cloud:        # spring cloud gateway 路由配置方式
    gateway:
      discovery:      #是否与服务发现组件进行结合,通过 serviceId(必须设置成大写) 转发到具体的服务实例。默认为false,设为true便开启通过服务中心的自动根据 serviceId 创建路由的功能。
        locator:      #路由访问方式:http://Gateway_HOST:Gateway_PORT/大写的serviceId/**,其中微服务应用名默认大写访问。
          enabled: true
      routes:
      - id: 163                     #网关路由到网易官网
        uri: http://www.163.com/
        predicates:
          - Path=/163/**
#      - id: ORDER-SERVICE           #网关路由到订单服务order-service
#        uri: lb://ORDER-SERVICE
#        predicates:
#          - Path=/ORDER-SERVICE/**
#      - id: USER-SERVICE            #网关路由到用户服务user-service
#        uri: lb://USER-SERVICE
#        predicates:
#          - Pach=/USER-SERVICE/**

server:
  port: 5001


logging:
  level:
    org.springframework.cloud.gateway: trace
    org.springframework.http.server.reactive: debug
    org.springframework.web.reactive: debug
    reactor.ipc.netty: debug


eureka:
  client:
    service-url:
      defaultZone: http://localhost:5000/eureka/

feign:
  hystrix:
    enabled: true


gateway-service的启动类,Application

package com.sunvalley.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class GatewayServiceApplication {

   /**
    * spring cloud gateway 配置方式之一,启动主程序配置,还有一种是配置文件配置
    * @param builder
    * @return
    */
   @Bean
   public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
      return builder.routes()
            .route(r -> r.path("/qq/**")
                     .and()
                     .uri("http://www.qq.com/"))
            .build();
   }

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

通过上面我们可以看到,gateway网关路由配置有两种方式:

1.通过@Bean自定义RouteLocator,在启动主类Application中配置

2.在配置文件yml中配置

这两种方式都可以实现网关路由是等价的,但是通常项目开发中会使用配置文件yml方式。

运行测试:

访问 http://localhost:8080/qq,路由转发到 http://www.qq.com
访问http://localhost:8080/163, 路由转发到 http://www.163.com

 

 

 

 

 

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐