亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

SpringCloud微服務資料入門教程

概述

本文深入介绍了Spring Cloud微服务的相关内容,包括Spring Cloud框架的简介、核心概念、安装与配置、以及实战案例。通过详细步骤,帮助开发者快速搭建和部署基于Spring Cloud的微服务架构。

Spring Cloud微服务资料入门教程
Spring Cloud简介

Spring Cloud是什么

Spring Cloud是一套基于Spring Boot实现的微服务框架,它为微服务架构中的基础设施提供了多种开箱即用的解决方案。通过Spring Cloud,开发者可以方便地实现服务发现、配置管理、断路器、路由、过滤器、负载均衡等功能。

为什么使用Spring Cloud

  1. 简化微服务开发:Spring Cloud提供了一系列工具和库,使得开发人员可以快速搭建和部署微服务架构的应用,无需从头实现这些基础设施。
  2. 标准化架构:Spring Cloud遵循一套标准化的微服务架构模式,使得不同团队开发的服务可以更好地协同工作。
  3. 丰富的功能模块:Spring Cloud包含了多个功能模块,如服务发现、配置管理、服务网关等,可以帮助微服务架构实现更复杂的功能。
  4. 社区活跃:Spring Cloud拥有庞大的社区支持,持续更新,不断引入新的功能和改进,使得开发者可以不断从社区中获得帮助和反馈。

Spring Cloud的核心概念

  1. 服务注册与发现:Spring Cloud通过Eureka或Consul等组件来实现服务注册与发现机制,使得服务之间可以自动地发现和调用。
  2. 配置管理:Spring Cloud Config提供了一个集中的配置服务,支持从git等远程仓库读取配置,并动态更新客户端配置。
  3. 服务网关:Spring Cloud Gateway提供了服务网关,可以进行路由、过滤和限流等操作,增强了服务间的通信安全性与效率。
  4. 断路器:Spring Cloud Hystrix为服务调用提供了断路器机制,可以在服务调用失败时快速熔断以防止级联故障。
  5. 负载均衡:Spring Cloud Ribbon提供了一种客户端负载均衡的方式,可以将请求均匀地分发到多个服务实例。
Spring Cloud的安装与配置

开发环境搭建

首先,你需要安装Java环境并设置环境变量。建议使用JDK 8或以上版本。

Maven配置

在你的Spring Boot项目中,需要在pom.xml文件中引入Spring Cloud的依赖。以下是一个基础的pom.xml配置示例:

<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.example</groupId>
    <artifactId>spring-cloud-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR9</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-web</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服务端的启动示例代码:

package com.example.eurekaserver;

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);
    }
}

创建一个服务提供者的示例代码:

package com.example.serviceprovider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class ServiceProviderApplication {

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

创建一个服务消费者的示例代码:

package com.example.serviceconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class ServiceConsumerApplication {

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

服务提供者和消费者在启动后会自动注册到Eureka服务端,实现服务发现。

Spring Cloud Eureka服务注册与发现

Eureka服务端与客户端介绍

Eureka服务端是注册中心,客户端可以向注册中心注册自己的服务信息,也可以从注册中心获取其他服务的信息。Eureka服务端提供了一个REST接口,服务端之间可以互相通信,实现服务实例的状态同步。

Eureka服务端配置

服务端的配置文件application.yml示例如下:

spring:
  application:
    name: eureka-service
  cloud:
    eureka:
      client:
        register-with-eureka: false
        fetch-registry: false
        service-url:
          defaultZone: http://localhost:8761/eureka/
      instance:
        hostname: localhost
      server:
        enable-self-preservation: false
        wait-time-in-ms-between-cycles: 5

启动服务端后,服务端会监听端口8761,并启动Eureka服务。

创建服务提供者与消费者

服务提供者的配置文件application.yml示例如下:

spring:
  application:
    name: service-provider
  cloud:
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
      instance:
        hostname: localhost
        prefer-ip-address: true

服务消费者的配置文件application.yml示例如下:

spring:
  application:
    name: service-consumer
  cloud:
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
      instance:
        hostname: localhost
        prefer-ip-address: true

高可用部署

为了实现服务的高可用性,可以搭建一个Eureka集群。配置如下:

  1. 服务端配置:在每个服务端的配置文件中设置eureka.client.register-with-eurekaeureka.client.fetch-registryfalse,禁用自动注册和获取服务实例的功能。
  2. 服务端间通信:在每个服务端的配置文件中指定其他服务端的地址,例如:
spring:
  cloud:
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
  1. 服务端启动:启动多个服务端实例,形成一个服务注册和发现的集群。
Spring Cloud Feign与Ribbon负载均衡

Feign与Ribbon的基本概念

Feign是一个声明式的Web服务客户端,它使得编写Web服务客户端更加容易。Ribbon是一个基于HTTP和TCP的客户端负载均衡器,它可以管理请求的服务列表,实现对服务实例的负载均衡。

使用Feign进行服务调用

  1. 引入依赖:在pom.xml中添加spring-cloud-starter-openfeign依赖。
  2. 配置启用Feign:在服务消费者的application.yml文件中开启Feign:
spring:
  cloud:
    openfeign:
      enabled: true
  1. 定义Feign接口:在服务消费者中定义一个Feign客户端接口,用于调用服务提供者的方法。
package com.example.serviceconsumer;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "service-provider")
public interface ServiceClient {
    @GetMapping("/service-provided/{name}")
    String getProvider(@PathVariable String name);
}
  1. 调用服务:在服务消费者中通过创建ServiceClient接口的实例来调用服务提供者的方法。
package com.example.serviceconsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConsumerController {
    @Autowired
    private ServiceClient serviceClient;

    @GetMapping("/call-service-provider")
    public String callServiceProvider(@RequestParam String name) {
        return serviceClient.getProvider(name);
    }
}

结合Ribbon实现负载均衡

  1. 引入依赖:在pom.xml中添加spring-cloud-starter-netflix-ribbon依赖。
  2. 配置负载均衡:在服务消费者的配置文件中配置负载均衡策略。
spring:
  cloud:
    loadbalancer:
      discovery:
        enabled: true
        service-id: service-provider
  1. 使用Ribbon进行调用:在代码中通过RestTemplate等工具实现负载均衡的请求。
package com.example.serviceconsumer;

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

@RestController
@LoadBalancerClient(name = "service-provider")
public class ConsumerController {
    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;

    @GetMapping("/call-service-provider")
    public String callServiceProvider(@RequestParam String name) {
        return restTemplate.getForObject("http://SERVICE-PROVIDER/service-provided/{name}", String.class, name);
    }
}
Spring Cloud Config集中配置管理

Config Server与Config Client介绍

Config Server是一个配置服务器,它能够从git等远程仓库读取配置信息。Config Client是配置文件的客户端,可以通过远程仓库获取配置信息。

配置中心的搭建与使用

  1. 搭建Config Server:创建一个新的Spring Boot项目作为配置服务端,并在pom.xml文件中添加spring-cloud-starter-config依赖。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  1. 配置Config Server:在配置服务端的application.yml文件中配置git仓库地址。
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/config-repo
  1. 启动Config Server:启动服务端后,它将从git仓库中读取配置文件并供客户端使用。
package com.example.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {

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

使用git进行配置管理

  1. 创建git仓库:在GitHub或GitLab等托管服务上创建一个git仓库,用于存储配置信息。
  2. 添加配置文件:在git仓库中添加配置文件,例如application.ymlapplication-dev.yml等文件。
  3. 指定配置文件名:在Config Client的配置文件中指定配置文件的名称。
spring:
  cloud:
    config:
      name: application
      profile: dev
  1. 从Config Server获取配置:Config Client可以使用Environment对象来获取配置信息。
package com.example.configclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.env.Environment;

@Configuration
@EnableConfigServer
@SpringBootApplication
public class ConfigClientApplication {

    @RestController
    public class ConfigController {
        @Autowired
        private Environment env;

        @GetMapping("/config")
        public String getConfig() {
            return env.getProperty("message");
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }
}
实战案例:构建简单微服务应用

项目需求分析

项目需求:

  1. 创建一个服务注册中心(Eureka Server)。
  2. 创建多个服务提供者(例如service-provider-aservice-provider-b),提供不同的接口服务。
  3. 创建一个服务消费者(service-consumer),通过Feign调用服务提供者的服务。
  4. 使用Ribbon进行负载均衡。
  5. 使用Config Server管理配置信息。

项目搭建与各模块实现

  1. 搭建Eureka Server
    • 创建一个新的Spring Boot项目。
    • pom.xml中添加spring-cloud-starter-netflix-eureka-server依赖。
    • 配置文件application.yml中设置端口和服务名称。
spring:
  application:
    name: eureka-server
  cloud:
    eureka:
      client:
        register-with-eureka: false
        fetch-registry: false
        service-url:
          defaultZone: http://localhost:8761/eureka/
      instance:
        hostname: localhost
        prefer-ip-address: true
  1. 搭建服务提供者
    • 创建一个新的Spring Boot项目。
    • pom.xml中添加spring-cloud-starter-netflix-eureka-client依赖。
    • 配置文件application.yml设置Eureka服务地址和服务名称。
spring:
  application:
    name: service-provider
  cloud:
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
      instance:
        hostname: localhost
        prefer-ip-address: true
  1. 搭建服务消费者
    • 创建一个新的Spring Boot项目。
    • pom.xml中添加spring-cloud-starter-netflix-eureka-clientspring-cloud-starter-openfeign依赖。
    • 配置文件application.yml设置Eureka服务地址和服务名称。
spring:
  application:
    name: service-consumer
  cloud:
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
      instance:
        hostname: localhost
        prefer-ip-address: true
    openfeign:
      enabled: true
  1. 服务提供者接口实现
    • 实现一个简单的REST接口,提供服务。
package com.example.serviceprovider;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProviderController {

    @GetMapping("/service-provided/{name}")
    public String getProvider(@PathVariable String name) {
        return "Hello, " + name;
    }
}
  1. 服务消费者调用服务
    • 定义一个Feign客户端接口,用于调用服务提供者的接口。
package com.example.serviceconsumer;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "service-provider")
public interface ServiceClient {
    @GetMapping("/service-provided/{name}")
    String getProvider(@PathVariable String name);
}
  • 在服务消费者中使用Feign客户端调用服务提供者的接口。
package com.example.serviceconsumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConsumerController {
    @Autowired
    private ServiceClient serviceClient;

    @GetMapping("/call-service-provider")
    public String callServiceProvider(@RequestParam String name) {
        return serviceClient.getProvider(name);
    }
}

调试与部署

  1. 启动服务:先启动Eureka Server,然后启动服务提供者和消费者。
  2. 访问服务:在浏览器或Postman等工具中访问http://localhost:8080/call-service-provider?name=world,可以看到服务消费者调用服务提供者的接口并返回结果。
  3. 负载均衡测试:可以启动多个服务提供者实例,并使用Ribbon进行负载均衡调用。
  4. 配置中心管理:启动Config Server和Config Client,确保配置信息可以从远程仓库中获取。
點擊查看更多內容
TA 點贊

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

評論

作者其他優質文章

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

100積分直接送

付費專欄免費學

大額優惠券免費領

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

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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

舉報

0/150
提交
取消