第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

SpringCloud項目開發(fā)學習教程

概述

本文详细介绍了SpringCloud项目开发学习的全过程,包括SpringCloud的基础概念、核心组件以及与SpringBoot的关系。文章还涵盖了开发环境的搭建、Eureka服务发现与注册、Feign与Ribbon负载均衡的配置与使用,以及SpringCloud Gateway的安装与配置等内容。通过实战项目案例,进一步展示了如何在实际项目中应用SpringCloud的各项功能。

SpringCloud项目开发学习教程

SpringCloud简介

SpringCloud是什么

Spring Cloud 是一个基于 Spring Boot 来实现微服务的框架,它集成了许多子项目,为开发者提供了快速构建分布式系统的一整套技术。Spring Cloud 的核心目标是为开发者提供一套简单易用的编程模型,使得开发者可以方便地将系统分解成多个独立的小服务。它能够很好地与 Spring Boot 结合使用,帮助开发者快速搭建分布式应用系统。

Spring Cloud 并不是一个用来解决具体问题的单一框架,而是一系列框架的集合,这些框架为开发者提供了解决分布式系统中常见问题的工具,如配置管理、服务发现、路由、断路器、负载均衡、服务跟踪、安全等。

SpringCloud的核心组件介绍

Spring Cloud 包含了许多核心组件,下面是一些重要的核心组件:

  • Eureka:服务注册与发现。Eureka 是一个基于 REST 的服务,它主要用于服务治理,它的目标是提供服务注册与发现的机制。
  • Ribbon:客户端负载均衡组件。Ribbon 是一个基于客户端的负载均衡器,它可以通过多种负载均衡算法来实现服务调用。
  • Feign:声明式的 HTTP 客户端。Feign 是一个基于 Java 的轻量级 HTTP 客户端,它提供了多种注解来简化 HTTP 请求的编程。
  • Hystrix:断路器组件。Hystrix 是一个旨在提高分布式系统的容错性和控制资源访问的工具,它通过微服务之间的隔离来防止级联失效。
  • Zuul:API Gateway。Zuul 是一个基于 Java 的路由服务,它提供了一种简单的路由规则配置,可以将不同服务之间的请求路由到相应的微服务。
  • Config:配置中心。Spring Cloud Config 为 Spring Boot 应用提供集中化的外部配置支持,它包含服务器端和客户端,支持多种存储方式。
  • Spring Cloud Stream:消息驱动的微服务。Spring Cloud Stream 是一个构建消息驱动微服务的应用框架,它可以简化消息传递。

SpringBoot与SpringCloud的关系

Spring Boot 和 Spring Cloud 是紧密相关的。Spring Boot 是 Spring 生态系统中的一个框架,它简化了使用 Spring 时的配置,能够快速创建独立、生产级别的应用。Spring Boot 提供了丰富的功能来简化配置,例如自动配置、嵌入式的 HTTP 服务器、应用监控等。

Spring Cloud 则是建立在 Spring Boot 之上的,它利用 Spring Boot 的能力来构建微服务。Spring Cloud 为开发者提供了微服务框架,它扩展了 Spring Boot 的功能,提供了服务发现、负载均衡、断路器、配置中心等微服务相关的特性。Spring Cloud 可以使用 Spring Boot 自动配置功能来简化配置,使得开发者可以专注于业务逻辑的开发。

开发环境搭建

JDK与IDE环境搭建

在开始搭建 Spring Cloud 项目的开发环境之前,首先需要确保已经安装了 JDK 和 IDE(如 IntelliJ IDEA 或 Eclipse)。以下是具体步骤:

  1. 下载并安装 JDK

    访问 Oracle 官方网站或者阿里云等其他下载源下载 JDK 安装包。根据操作系统选择对应的安装包,比如 Windows 版本或 Linux 版本。安装过程中,选择合适的安装路径,安装完成后设置环境变量。

  2. 下载并安装 IDE

    IntelliJ IDEA 和 Eclipse 是两个常用的 Java 开发环境,这里以 IntelliJ IDEA 为例:

    • 访问 IntelliJ IDEA 官网下载安装包。
    • 运行安装包开始安装,按照提示完成安装过程。
    • 在安装完成后,打开 IntelliJ IDEA 并创建一个新的 Java 项目。

Maven配置与SpringBoot项目创建

在 IntelliJ IDEA 中创建一个 Spring Boot 项目,可以通过以下步骤:

  1. 创建 Spring Boot 项目

    在 IntelliJ IDEA 中打开 "File" -> "New" -> "Project",选择 "Maven" 项目,点击 "Next" 输入项目的 GroupId 和 ArtifactId,选择 "Use default values" 并点击 "Next",在 "Maven Settings" 里选择 "Add as Maven project",点击 "Finish"。

  2. 添加 Spring Boot 依赖

    pom.xml 文件中,添加 Spring Boot 的依赖,如下所示:

    <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.5.4</version>
    </parent>
    
    <dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <!-- 添加其他必要的依赖 -->
    </dependencies>

快速入门示例

创建一个简单的 Spring Boot 应用程序,演示如何使用 Spring Boot 创建一个 RESTful API。按照以下步骤操作:

  1. 创建主应用程序类

    src/main/java 目录下创建一个新的 Java 类,例如名为 Application,并添加 @SpringBootApplication 注解:

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application {
       public static void main(String[] args) {
           SpringApplication.run(Application.class, args);
       }
    }
  2. 创建一个简单的 REST 控制器

    在同一个包下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.demo;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @GetMapping("/hello")
       public String hello() {
           return "Hello Spring Boot!";
       }
    }
  3. 运行应用程序

    右键点击 Application.java 文件,选择 "Run",在浏览器中访问 http://localhost:8080/api/hello,应该看到输出 "Hello Spring Boot!"。

SpringCloud Eureka服务发现与注册

Eureka服务注册中心搭建

Eureka 是一个基于 REST 的服务,它主要用于服务治理,它的目标是提供服务注册与发现的机制。以下是搭建 Eureka 服务注册中心的具体步骤:

  1. 创建 Eureka 服务注册中心项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 依赖:

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
  2. 配置 Eureka 服务注册中心

    application.yml 文件中配置 Eureka 服务注册中心:

    server:
       port: 8761
    
    eureka:
       instance:
           hostname: localhost
       client:
           register-with-eureka: false
           fetch-registry: false
       server:
           enable-self-preservation: false

    上面配置中,server.port 设置了 Eureka 服务端口为 8761,eureka.instance.hostname 设置了 Eureka 服务的注册主机名为 localhost,eureka.client.register-with-eurekaeureka.client.fetch-registry 设置为 false 表示不注册 Eureka 服务,eureka.server.enable-self-preservation 设置为 false 表示禁用自我保护模式。

  3. 运行 Eureka 服务注册中心

    src/main/java 目录下创建一个新的 Java 类,例如名为 EurekaApplication,并添加 @SpringBootApplication@EnableEurekaServer 注解:

    package com.example.eureka;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaApplication {
       public static void main(String[] args) {
           SpringApplication.run(EurekaApplication.class, args);
       }
    }
  4. 启动服务

    右键点击 EurekaApplication.java 文件,选择 "Run",然后在浏览器中访问 http://localhost:8761,应该可以看到 Eureka 服务注册中心的界面。

服务提供者与服务消费者配置

在 Spring Cloud 中,服务提供者和消费者是两个重要的概念,服务提供者负责提供服务,服务消费者负责调用服务。以下是配置服务提供者和服务消费者的步骤:

  1. 创建服务提供者项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 依赖:

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

    application.yml 文件中配置服务提供者的 Eureka 注册信息:

    server:
       port: 8081
    
    spring:
       application:
           name: service-provider
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/

    上面配置中,server.port 设置了服务提供者的端口为 8081,spring.application.name 设置了服务提供者的名称为 service-providereureka.client.register-with-eurekaeureka.client.fetch-registry 设置为 true 表示注册和获取 Eureka 服务,eureka.client.service-url.defaultZone 设置了 Eureka 服务注册中心的地址为 http://localhost:8761/eureka/

  2. 创建服务消费者项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 依赖:

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

    application.yml 文件中配置服务消费者的 Eureka 注册信息:

    server:
       port: 8082
    
    spring:
       application:
           name: service-consumer
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/

    上面配置中,server.port 设置了服务消费者的端口为 8082,spring.application.name 设置了服务消费者的名称为 service-consumereureka.client.register-with-eurekaeureka.client.fetch-registry 设置为 true 表示注册和获取 Eureka 服务,eureka.client.service-url.defaultZone 设置了 Eureka 服务注册中心的地址为 http://localhost:8761/eureka/

  3. 运行服务提供者和服务消费者

    src/main/java 目录下创建一个新的 Java 类,例如名为 ServiceProviderApplication,并添加 @SpringBootApplication@EnableDiscoveryClient 注解:

    package com.example.serviceprovider;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    public class ServiceProviderApplication {
       public static void main(String[] args) {
           SpringApplication.run(ServiceProviderApplication.class, args);
       }
    }

    src/main/java 目录下创建一个新的 Java 类,例如名为 ServiceConsumerApplication,并添加 @SpringBootApplication@EnableDiscoveryClient 注解:

    package com.example.serviceconsumer;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    public class ServiceConsumerApplication {
       public static void main(String[] args) {
           SpringApplication.run(ServiceConsumerApplication.class, args);
       }
    }
  4. 创建服务提供者的 REST 控制器

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.serviceprovider.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @GetMapping("/hello")
       public String hello() {
           return "Hello from Service Provider!";
       }
    }
  5. 创建服务消费者的 REST 控制器

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.serviceconsumer.controller;
    
    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.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @Autowired
       private DiscoveryClient discoveryClient;
    
       @GetMapping("/hello")
       public String hello() {
           ServiceInstance serviceInstance = discoveryClient.getInstances("service-provider").get(0);
           String serviceUrl = serviceInstance.getUri().toString();
           RestTemplate restTemplate = new RestTemplate();
           return restTemplate.getForObject(serviceUrl + "/api/hello", String.class);
       }
    }
  6. 启动服务

    分别右键点击 ServiceProviderApplication.javaServiceConsumerApplication.java 文件,选择 "Run",然后在浏览器中访问 http://localhost:8081/api/hellohttp://localhost:8082/api/hello,应该可以看到服务提供者和消费者之间的服务调用。

SpringCloud Feign与Ribbon负载均衡

Feign接口定义与调用

Feign 是一个基于 Java 的轻量级 HTTP 客户端,它提供了多种注解来简化 HTTP 请求的编程。下面是使用 Feign 的具体步骤:

  1. 创建服务提供者项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 和 Feign 依赖:

    <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>

    application.yml 文件中配置服务提供者的 Eureka 注册信息:

    server:
       port: 8083
    
    spring:
       application:
           name: service-provider
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/
  2. 创建服务消费者项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 和 Feign 依赖:

    <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>

    application.yml 文件中配置服务消费者的 Eureka 注册信息:

    server:
       port: 8084
    
    spring:
       application:
           name: service-consumer
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/
  3. 创建服务提供者的 REST 控制器

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.serviceprovider.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @GetMapping("/hello")
       public String hello() {
           return "Hello from Service Provider!";
       }
    }
  4. 创建服务消费者的 Feign 客户端

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloClient,并添加 @FeignClient@RequestMapping 注解:

    package com.example.serviceconsumer.feign;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @FeignClient(value = "service-provider", url = "http://localhost:8083")
    public interface HelloClient {
    
       @GetMapping("/api/hello")
       String hello();
    }
  5. 创建服务消费者的 REST 控制器

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.serviceconsumer.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @Autowired
       private HelloClient helloClient;
    
       @GetMapping("/hello")
       public String hello() {
           return helloClient.hello();
       }
    }
  6. 运行服务

    分别右键点击 ServiceProviderApplication.javaServiceConsumerApplication.java 文件,选择 "Run",然后在浏览器中访问 http://localhost:8084/api/hello,应该可以看到服务提供者和消费者之间的服务调用。

Ribbon负载均衡配置与使用

Ribbon 是一个基于客户端的负载均衡器,它可以通过多种负载均衡算法来实现服务调用。下面是使用 Ribbon 的具体步骤:

  1. 创建服务提供者项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 和 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-netflix-ribbon</artifactId>
    </dependency>

    application.yml 文件中配置服务提供者的 Eureka 注册信息:

    server:
       port: 8085
    
    spring:
       application:
           name: service-provider
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/
  2. 创建服务消费者项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Eureka 和 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-netflix-ribbon</artifactId>
    </dependency>

    application.yml 文件中配置服务消费者的 Eureka 注册信息:

    server:
       port: 8086
    
    spring:
       application:
           name: service-consumer
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/
  3. 创建服务提供者的 REST 控制器

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.serviceprovider.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @GetMapping("/hello")
       public String hello() {
           return "Hello from Service Provider!";
       }
    }
  4. 创建服务消费者的 REST 控制器

    src/main/java 目录下创建一个新的 Java 类,例如名为 HelloController,并添加 @RestController@RequestMapping 注解:

    package com.example.serviceconsumer.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.client.RestTemplate;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class HelloController {
    
       @Autowired
       @LoadBalanced
       private RestTemplate restTemplate;
    
       @Autowired
       private LoadBalancerClient loadBalancerClient;
    
       @GetMapping("/hello")
       public String hello() {
           return restTemplate.getForObject("http://service-provider/api/hello", String.class);
       }
    }
  5. 运行服务

    分别右键点击 ServiceProviderApplication.javaServiceConsumerApplication.java 文件,选择 "Run",然后在浏览器中访问 http://localhost:8086/api/hello,应该可以看到服务提供者和消费者之间的服务调用,并且会根据 Ribbon 的负载均衡算法进行服务调用。

SpringCloud Gateway API网关

Gateway的安装与配置

Spring Cloud Gateway 是一个基于 Spring Cloud 的 API Gateway 实现,它提供了一系列强大的路由功能以及过滤器支持,可以方便地实现请求路由、请求过滤等功能。下面是安装和配置 Spring Cloud Gateway 的具体步骤:

  1. 创建 API Gateway 项目

    在 IntelliJ IDEA 中创建一个新的 Spring Boot 项目,添加 Gateway 依赖:

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
  2. 配置 Gateway

    application.yml 文件中配置 Gateway:

    server:
       port: 8087
    
    spring:
       application:
           name: gateway
    
    spring.cloud.gateway.routes:
       - id: service-provider
         uri: lb://service-provider
         predicates:
             - Path=/api/hello-service-provider/**

    上面配置中,server.port 设置了 Gateway 的端口为 8087,spring.application.name 设置了 Gateway 的名称为 gatewayspring.cloud.gateway.routes 设置了 Gateway 的路由规则,其中 id 设置了路由的唯一标识为 service-provideruri 设置了路由的目标服务为 service-providerpredicates 设置了路由的路径匹配条件为 /api/hello-service-provider/**

  3. 创建 Gateway 应用程序

    src/main/java 目录下创建一个新的 Java 类,例如名为 GatewayApplication,并添加 @SpringBootApplication@EnableDiscoveryClient 注解:

    package com.example.gateway;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    public class GatewayApplication {
       public static void main(String[] args) {
           SpringApplication.run(GatewayApplication.class, args);
       }
    }
  4. 运行 Gateway

    右键点击 GatewayApplication.java 文件,选择 "Run",然后在浏览器中访问 http://localhost:8087/api/hello-service-provider/hello,应该可以看到通过 Gateway 对服务提供者进行请求转发。

路由规则与过滤器配置

Spring Cloud Gateway 提供了丰富的路由规则和过滤器配置,下面是一些常见的路由规则和过滤器配置:

  1. 路由规则

    application.yml 文件中配置路由规则:

    spring.cloud.gateway.routes:
       - id: service-consumer
         uri: lb://service-consumer
         predicates:
             - Path=/api/hello-service-consumer/**

    上面配置中,id 设置了路由的唯一标识为 service-consumeruri 设置了路由的目标服务为 service-consumerpredicates 设置了路由的路径匹配条件为 /api/hello-service-consumer/**

  2. 过滤器配置

    application.yml 文件中配置过滤器:

    spring.cloud.gateway.routes:
       - id: service-consumer
         uri: lb://service-consumer
         predicates:
             - Path=/api/hello-service-consumer/**
         filters:
             - name: RequestRateLimiter
               args:
                   key-by: username
                   redis-rate-limiter.burst-size: 20
                   redis-rate-limiter.replenish-rate: 1

    上面配置中,id 设置了路由的唯一标识为 service-consumeruri 设置了路由的目标服务为 service-consumerpredicates 设置了路由的路径匹配条件为 /api/hello-service-consumer/**filters 设置了过滤器为 RequestRateLimiter,其中 args 设置了过滤器的参数为 key-by: usernameredis-rate-limiter.burst-size: 20redis-rate-limiter.replenish-rate: 1

  3. 运行服务

    右键点击 GatewayApplication.java 文件,选择 "Run",然后在浏览器中访问 http://localhost:8087/api/hello-service-consumer/hello,应该可以看到通过 Gateway 对服务消费者进行请求转发,并且会根据过滤器的配置进行请求过滤。

实战项目案例

实战项目需求分析

本节将以一个简单的电商系统为例,展示如何使用 Spring Cloud 构建微服务架构的电商系统。该系统的功能包括商品管理、订单管理和用户管理等模块,具体需求如下:

  • 商品管理模块

    • 用户可以浏览商品信息。
    • 用户可以搜索商品。
    • 管理员可以添加、修改、删除商品。
  • 订单管理模块

    • 用户可以查看订单信息。
    • 用户可以取消订单。
    • 管理员可以处理订单。
  • 用户管理模块

    • 用户可以注册账号。
    • 用户可以登录账号。
    • 用户可以修改个人信息。

项目结构设计与实现

根据上述需求,项目的整体结构可以分为以下几个部分:

  • 商品服务

    • 提供商品的 CRUD 操作。
  • 订单服务

    • 提供订单的 CRUD 操作。
  • 用户服务

    • 提供用户注册、登录、修改个人信息的操作。
  • 网关服务

    • 作为系统的统一入口,负责请求的路由和过滤。
  • 注册中心

    • 作为服务的注册和发现中心。

下面将详细介绍各个模块的实现:

  1. 商品服务

    创建一个新的 Spring Boot 项目,添加 Eureka 和 Spring Web 依赖:

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    application.yml 文件中配置商品服务的 Eureka 注册信息:

    server:
       port: 8088
    
    spring:
       application:
           name: product-service
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/

    创建商品服务的 REST 控制器:

    package com.example.productservice.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api/products")
    public class ProductController {
    
       @GetMapping("/list")
       public String list() {
           return "Product List";
       }
    }

    创建商品的实体类:

    package com.example.productservice.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Product {
    
       @Id
       @GeneratedValue(strategy = GenerationType.AUTO)
       private Long id;
       private String name;
       private String description;
       private double price;
    
       public Long getId() {
           return id;
       }
    
       public void setId(Long id) {
           this.id = id;
       }
    
       public String getName() {
           return name;
       }
    
       public void setName(String name) {
           this.name = name;
       }
    
       public String getDescription() {
           return description;
       }
    
       public void setDescription(String description) {
           this.description = description;
       }
    
       public double getPrice() {
           return price;
       }
    
       public void setPrice(double price) {
           this.price = price;
       }
    }

    创建商品的数据访问层:

    package com.example.productservice.repository;
    
    import com.example.productservice.model.Product;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface ProductRepository extends JpaRepository<Product, Long> {
    }
  2. 订单服务

    创建一个新的 Spring Boot 项目,添加 Eureka 和 Spring Web 依赖:

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    application.yml 文件中配置订单服务的 Eureka 注册信息:

    server:
       port: 8089
    
    spring:
       application:
           name: order-service
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/

    创建订单服务的 REST 控制器:

    package com.example.orderservice.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api/orders")
    public class OrderController {
    
       @GetMapping("/list")
       public String list() {
           return "Order List";
       }
    }

    创建订单的实体类:

    package com.example.orderservice.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Order {
    
       @Id
       @GeneratedValue(strategy = GenerationType.AUTO)
       private Long id;
       private Long productId;
       private Long userId;
       private int quantity;
       private double totalPrice;
    
       public Long getId() {
           return id;
       }
    
       public void setId(Long id) {
           this.id = id;
       }
    
       public Long getProductId() {
           return productId;
       }
    
       public void setProductId(Long productId) {
           this.productId = productId;
       }
    
       public Long getUserId() {
           return userId;
       }
    
       public void setUserId(Long userId) {
           this.userId = userId;
       }
    
       public int getQuantity() {
           return quantity;
       }
    
       public void setQuantity(int quantity) {
           this.quantity = quantity;
       }
    
       public double getTotalPrice() {
           return totalPrice;
       }
    
       public void setTotalPrice(double totalPrice) {
           this.totalPrice = totalPrice;
       }
    }

    创建订单的数据访问层:

    package com.example.orderservice.repository;
    
    import com.example.orderservice.model.Order;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface OrderRepository extends JpaRepository<Order, Long> {
    }
  3. 用户服务

    创建一个新的 Spring Boot 项目,添加 Eureka 和 Spring Web 依赖:

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    application.yml 文件中配置用户服务的 Eureka 注册信息:

    server:
       port: 8090
    
    spring:
       application:
           name: user-service
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/

    创建用户服务的 REST 控制器:

    package com.example.userservice.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api/users")
    public class UserController {
    
       @GetMapping("/list")
       public String list() {
           return "User List";
       }
    }

    创建用户的实体类:

    package com.example.userservice.model;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class User {
    
       @Id
       @GeneratedValue(strategy = GenerationType.AUTO)
       private Long id;
       private String username;
       private String password;
    
       public Long getId() {
           return id;
       }
    
       public void setId(Long id) {
           this.id = id;
       }
    
       public String getUsername() {
           return username;
       }
    
       public void setUsername(String username) {
           this.username = username;
       }
    
       public String getPassword() {
           return password;
       }
    
       public void setPassword(String password) {
           this.password = password;
       }
    }

    创建用户的数据访问层:

    package com.example.userservice.repository;
    
    import com.example.userservice.model.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserRepository extends JpaRepository<User, Long> {
    }
  4. 网关服务

    创建一个新的 Spring Boot 项目,添加 Gateway 和 Eureka 依赖:

    <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>

    application.yml 文件中配置网关服务的 Eureka 注册信息:

    server:
       port: 8091
    
    spring:
       application:
           name: gateway-service
    
    eureka:
       client:
           register-with-eureka: true
           fetch-registry: true
           service-url:
               defaultZone: http://localhost:8761/eureka/

    application.yml 文件中配置网关服务的路由规则:

    spring.cloud.gateway.routes:
       - id: product-service
         uri: lb://product-service
         predicates:
             - Path=/api/products/**
       - id: order-service
         uri: lb://order-service
         predicates:
             - Path=/api/orders/**
       - id: user-service
         uri: lb://user-service
         predicates:
             - Path=/api/users/**
  5. 注册中心

    创建一个新的 Spring Boot 项目,添加 Eureka 依赖:

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

    application.yml 文件中配置注册中心的 Eureka 服务信息:

    server:
       port: 8761
    
    eureka:
       instance:
           hostname: localhost
       client:
           register-with-eureka: false
           fetch-registry: false
       server:
           enable-self-preservation: false

项目部署与测试

  1. 启动所有服务

    分别右键点击每个服务的主应用程序类文件(例如 ProductServiceApplication.javaOrderServiceApplication.javaUserServiceApplication.javaGatewayServiceApplication.javaEurekaApplication.java),选择 "Run",确保所有服务都启动成功。

  2. 访问服务

    在浏览器中访问 http://localhost:8091/api/products/list,应该可以看到商品服务返回的 "Product List"。

    在浏览器中访问 http://localhost:8091/api/orders/list,应该可以看到订单服务返回的 "Order List"。

    在浏览器中访问 http://localhost:8091/api/users/list,应该可以看到用户服务返回的 "User List"。

通过这些步骤,可以验证整个电商系统的微服务架构是否搭建成功。

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優(yōu)惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消