为了账号安全,请及时绑定邮箱和手机立即绑定

SpringCloud微服务项目实战入门教程

概述

本文介绍了SpringCloud微服务项目实战入门教程,涵盖了Spring Cloud的核心组件、环境搭建、微服务项目搭建、服务注册与发现、负载均衡与断路器及服务网关配置等内容,帮助开发者轻松搭建和管理微服务架构。

SpringCloud微服务项目实战入门教程
Spring Cloud简介

Spring Cloud是什么

Spring Cloud 是一套基于Spring Boot的微服务开发工具,它提供了开发分布式系统所需的基础设施支持,主要解决的是分布式系统中的配置管理、服务发现、断路器、服务网关、负载均衡、微服务监控等问题。通过使用Spring Cloud,开发者可以轻松地搭建和管理微服务架构下的稳定、可靠的服务集群。

Spring Cloud的核心组件介绍

Spring Cloud包含多个核心组件,每个组件都有其特定的功能,以下是一些核心组件的简要介绍:

  • Eureka:服务注册与发现组件,提供服务注册与服务发现的功能。
  • Ribbon:客户端负载均衡组件,用于在多个服务实例之间实现负载均衡。
  • Feign:声明式服务调用组件,简化HTTP请求的编写。
  • Hystrix:断路器组件,用于实现故障隔离与熔断机制。
  • Zuul:服务网关组件,提供路由和过滤功能。
  • Spring Cloud Config:配置管理组件,提供集中化的配置管理功能。
  • Spring Cloud Gateway:服务网关组件,用于构建微服务网关,实现更复杂的路由策略。
  • Spring Cloud Stream:消息驱动组件,简化消息驱动的微服务开发。
  • Spring Cloud Sleuth:服务追踪组件,提供全链路的请求追踪功能。
  • Spring Cloud Security:安全组件,提供安全认证和授权功能。
环境搭建

搭建开发环境

在开始开发Spring Cloud项目之前,需要搭建一个基本的开发环境,包括Java、Maven、IntelliJ IDEA(或Eclipse)等开发工具。以下是具体步骤:

  1. 安装JDK:下载并安装最新的JDK版本。确保安装完成后,环境变量已正确配置。
  2. 安装Maven:下载并安装Maven,配置好Maven的环境变量。
  3. 安装IntelliJ IDEA:下载安装IntelliJ IDEA,并安装Spring插件。
# 检查JDK是否安装成功
java -version

# 检查Maven是否安装成功
mvn -v

下载和配置Spring Cloud

  1. 下载Spring Cloud Starter:到Spring官方仓库下载所需的Spring Cloud Starter依赖。
  2. 配置Spring Cloud版本:在项目的pom.xml文件中添加Spring Cloud版本信息,确保所有依赖使用相同的版本。
<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Hoxton.SR8</spring-cloud.version>
</properties>

<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>
微服务项目搭建

创建第一个Spring Boot项目

使用IntelliJ IDEA创建一个新的Spring Boot项目:

  1. 选择"File" -> "New" -> "Project"。
  2. 选择"Spring Initializr"。
  3. 选择构建工具为Maven。
  4. 选择语言为Java。
  5. 选择Spring Boot版本(如2.4.0)。
  6. 在Dependencies中选择"Spring Web"和其他所需依赖。
  7. 点击"Next"并填写项目名称(如e-commerce),然后点击"Finish"。
<!-- pom.xml -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

添加Spring Cloud依赖

在创建好的Spring Boot项目中添加Spring Cloud相关的依赖。

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
</dependencies>
服务注册与发现

使用Eureka搭建注册中心

  1. 创建Eureka Server项目:创建一个新的Spring Boot项目,添加Eureka Server依赖。
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
</dependencies>
  1. 配置Eureka Server:在application.yml中配置Eureka Server。
server:
  port: 8761

spring:
  application:
     name: eureka-server

eureka:
    instance:
        hostname: localhost
    client:
        register-with-eureka: false
        fetch-registry: false
        # 注册中心不需要自己注册,所以false
    server:
        enable-self-preservation: false
        # 关闭自我保护机制
  1. 编写启动类:创建启动类以启动Eureka Server。
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 EurekaServerApplication {

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

服务提供者和服务消费者的实现

服务提供者

  1. 创建服务提供者项目:创建一个新的Spring Boot项目,添加Eureka Client依赖。
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
</dependencies>
  1. 配置服务提供者:在application.yml中配置服务提供者。
server:
  port: 8081

spring:
 application:
     name: service-provider

eureka:
    client:
        service-url:
            defaultZone: http://localhost:8761/eureka/
  1. 编写服务提供者代码:创建一个简单的REST服务。
package com.example.serviceprovider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProviderController {
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/hello")
    public String hello() {
        return "Hello World from service-provider";
    }
}
  1. 启动服务提供者:运行服务提供者项目,服务将自动注册到Eureka Server。

服务消费者

  1. 创建服务消费者项目:创建一个新的Spring Boot项目,添加Eureka Client依赖。
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
</dependencies>
  1. 配置服务消费者:在application.yml中配置服务消费者。
server:
  port: 8082

spring:
 application:
     name: service-consumer

eureka:
    client:
        service-url:
            defaultZone: http://localhost:8761/eureka/
  1. 编写服务消费者代码:创建一个服务消费者,调用服务提供者的方法。
package com.example.serviceconsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String callProvider() {
        String url = "http://SERVICE-PROVIDER/hello";
        return restTemplate.getForObject(url, String.class);
    }
}
  1. 启动服务消费者:运行服务消费者项目,服务将自动注册到Eureka Server,并能够调用服务提供者的方法。
负载均衡与断路器

使用Ribbon实现负载均衡

Ribbon是Netflix开源的客户端负载均衡器,用于在多个服务实例之间实现负载均衡。以下是如何在Spring Cloud中使用Ribbon实现负载均衡。

配置服务提供者

在服务提供者项目中,添加Ribbon依赖。

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

application.yml中配置服务提供者。

server:
  port: 8081
  - 8082
spring:
 application:
     name: service-provider
eureka:
    client:
        service-url:
            defaultZone: http://localhost:8761/eureka/

服务提供者项目可以包含多个服务提供者实例,每个实例运行在不同的端口上。

配置服务消费者

在服务消费者项目中,使用Ribbon进行服务调用。

package com.example.serviceconsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer")
    public String callProvider() {
        String serviceUrl = loadBalancerClient.choose("service-provider").getUri().toString();
        String url = serviceUrl + "/hello";
        return restTemplate.getForObject(url, String.class);
    }
}

使用Hystrix实现断路器功能

Hystrix是Netflix开源的断路器组件,用于实现故障隔离与熔断机制。以下是如何在Spring Cloud中使用Hystrix实现断路器功能。

配置服务提供者

在服务提供者项目中,添加Hystrix依赖。

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

在服务提供者的REST方法中,添加Hystrix命令。

package com.example.serviceprovider;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProviderController {
    @GetMapping("/hello")
    @HystrixCommand(fallbackMethod = "fallback")
    public String hello() {
        return "Hello World from service-provider";
    }

    public String fallback() {
        return "Service is down";
    }
}

配置服务消费者

在服务消费者项目中,添加Hystrix依赖。

<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

在服务消费者的REST方法中,添加Hystrix命令。

package com.example.serviceconsumer;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallback")
    @GetMapping("/consumer")
    public String callProvider() {
        String serviceUrl = loadBalancerClient.choose("service-provider").getUri().toString();
        String url = serviceUrl + "/hello";
        return restTemplate.getForObject(url, String.class);
    }

    public String fallback() {
        return "Service is down";
    }
}
服务网关配置

使用Spring Cloud Gateway配置路由规则

Spring Cloud Gateway是Spring Cloud的官方路由网关,提供了一种新的API网关实现。它基于Spring Framework 5.0、Project Reactor以及Spring Boot 2.0开发,旨在简化API网关的开发,提高性能和资源使用率。

创建服务网关项目

  1. 创建一个新的Spring Boot项目。
  2. 添加Spring Cloud Gateway的依赖。
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
</dependencies>

配置路由规则

application.yml中配置路由规则。

server:
  port: 8083

spring:
  application:
     name: service-gateway

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

通过以上配置,Spring Cloud Gateway会将所有匹配/service-provider/**路径的请求路由到service-provider服务,将所有匹配/service-consumer/**路径的请求路由到service-consumer服务。

实现请求的路由和过滤

在Spring Cloud Gateway中,可以通过route配置进行路由,通过filter进行请求的预处理或后处理。

spring.cloud.gateway.routes:
  - id: service-provider
    uri: lb://service-provider
    predicates:
      - Path=/service-provider/**
    filters:
      - name: RewritePath
        args:
          regex: ^/service-provider/(?<path>.*)
          replacement: /${path}
  - id: service-consumer
    uri: lb://service-consumer
    predicates:
      - Path=/service-consumer/**
    filters:
      - name: RewritePath
        args:
          regex: ^/service-consumer/(?<path>.*)
          replacement: /${path}

这里我们使用了RewritePath过滤器来对请求路径进行重写,以便更灵活地处理请求。

创建启动类

创建一个启动类来启动服务网关。

package com.example.servicegateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServiceGatewayApplication {

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

测试路由

启动服务网关项目,然后通过服务网关访问服务提供者和服务消费者。

GET http://localhost:8083/service-provider/hello
GET http://localhost:8083/service-consumer/consumer

以上通过路由和过滤器的配置,实现了请求的路由和处理。

总结

通过以上步骤,我们已经搭建了一个基本的Spring Cloud微服务项目,并实现了服务注册与发现、负载均衡、断路器以及服务网关的配置。这些功能使得微服务架构更加稳定、可靠,同时也为后续的微服务开发提供了良好的基础。希望这个教程能够帮助你更好地理解和使用Spring Cloud。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消
OSZAR »