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

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

SpringCloud微服務教程:初學者必備指南

概述

Spring Cloud微服务教程介绍了Spring Cloud作为基于Spring Boot的微服务框架,提供了服务注册、发现、负载均衡、断路器等工具,简化了分布式系统构建。文章详细讲解了Spring Cloud的主要组件及其功能,并提供了环境搭建、服务注册与发现、负载均衡与路由、服务容错与熔断等实用案例。通过这些内容,读者可以快速掌握SpringCloud微服务教程中的关键知识点和实践方法。

SpringCloud简介

Spring Cloud 是基于 Spring Boot 自动配置的微服务框架,它为开发者提供了在分布式系统(如配置中心、服务发现、断路器、智能路由、微代理、控制总线、一次性令牌、全局锁、领导选举、分布式会话、集群状态)中构建服务的一系列工具。Spring Cloud 目标是简化分布式系统中常见模式(例如配置管理、服务发现、断路器、路由、微代理、命令总线等)的实现,从而在分布式系统中快速构建分布式系统中的复杂性。

1. 什么是SpringCloud

Spring Cloud 是一组指南、工具和子项目,用以构建云应用和服务,其主要目标是简化分布式系统中各常见操作(例如配置管理、服务发现、断路器、路由、微代理、集群状态等)。它通过将一些分散的框架、库、配置等整合到一起,为开发者提供了一套完整的微服务解决方案。

2. SpringCloud的主要组件及其作用

2.1 Eureka

Eureka 是一个服务注册和发现的组件,它提供了服务注册和服务发现的功能。Eureka 服务端接收客户端的服务注册与取消注册请求,并将其存储在内存中。客户端从服务端获取服务列表,服务端会周期性地从客户端获取心跳来判断服务是否可用。

2.2 Feign

Feign 是一个声明式的 Web 服务客户端,它使得编写 Web 服务客户端变得更加容易。Feign 结合了 Spring Boot 的配置,可以与 Eureka、Zuul 等组件无缝集成,实现服务之间的调用。

2.3 Ribbon

Ribbon 是一个基于 HTTP 和 TCP 的客户端负载均衡器。Ribbon 会将请求中的服务器名称转换为对应的 IP 地址,并根据一定的负载均衡策略向后端服务器发送请求。

2.4 Zuul

Zuul 是 Netflix 开源的一个 API Gateway,它提供了动态的路由和过滤器,可以实现请求的路由、请求的过滤等功能。

2.5 Hystrix

Hystrix 是 Netflix 开源的一个针对延迟和容错的 Java 库,用于隔离外部服务访问点、故障fallback、请求缓存和请求压缩等功能。Hystrix 可以实现服务熔断和降级策略,提高系统的容错能力。

3. SpringCloud的优势及应用场景

Spring Cloud 作为基于 Spring Boot 的微服务框架,有以下几点优势:

  • 简化开发:Spring Cloud 提供了大量的自动化配置,简化了微服务的开发过程,开发者可以快速实现服务的注册、发现、调用等功能。
  • 服务治理:Spring Cloud 集成了 Eureka、Zuul、Hystrix 等组件,为开发者提供了服务治理的解决方案。
  • 分布式配置:Spring Cloud 提供了服务端和客户端的配置,可以动态更新配置,支持公共配置、环境特定配置等。
  • 灰度发布:Spring Cloud 提供了服务端和客户端的配置,可以动态更新配置,支持公共配置、环境特定配置等。
  • 负载均衡:Spring Cloud 集成了 Ribbon,提供客户端的负载均衡功能。
  • 断路器:Spring Cloud 集成了 Hystrix,提供服务的容错能力。
环境搭建

1. 开发环境的配置

  • JDK:安装 Java 开发工具包(JDK)。
  • IDE:推荐使用 IntelliJ IDEA 或 Eclipse,以方便进行 Java 编程。
  • Maven:安装 Maven 构建工具,用于构建并管理 Java 项目。
  • Git:安装 Git 版本控制系统,用于代码版本控制。
  • Docker:可选,安装 Docker 用于容器化部署。

2. Maven项目的创建与依赖管理

创建一个新的 Maven 项目,使用 Spring Boot 的 Starter 包来简化依赖管理。以下是一个基础的 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>springcloud-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3. Spring Boot与Spring Cloud的快速集成

在 Spring Boot 项目中引入 Spring Cloud 的依赖后,可以通过简单的配置实现服务注册与发现。以下是一个简单的 Spring Boot 服务注册到 Eureka 服务器的示例:

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

@SpringBootApplication
@EnableEurekaClient
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

application.yml 配置文件中添加 Eureka 服务器的地址:

spring:
  application:
    name: eureka-client
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

在 Spring Boot 的主类中添加 @EnableEurekaClient 注解后,服务将会自动注册到 Eureka 服务器。

服务发现与注册

1. Eureka服务注册与发现

Eureka 是一个基于 REST 的服务,它提供了服务注册和服务发现的功能。Eureka 服务端接收客户端的服务注册与取消注册请求,并将其存储在内存中。客户端从服务端获取服务列表,服务端会周期性地从客户端获取心跳来判断服务是否可用。

以下是一个简单的 Eureka 服务注册与发现的实现:

首先,创建一个 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);
    }
}

application.yml 配置文件中添加 Eureka 服务端的配置:

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

然后,创建一个 Eureka 客户端(Eureka Client)项目:

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

@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }

    // 注释掉这个方法,只是为了展示如何使用 Eureka 客户端
    public void demo() {
        // 这里可以调用 Eureka 服务端注册的服务
    }
}

application.yml 配置文件中添加 Eureka 服务端的地址:

spring:
  application:
    name: eureka-client
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

2. 服务注册及心跳检测机制

Eureka 服务端和客户端都使用了心跳机制来保持连接。服务端会周期性地向客户端发送心跳请求,检查服务是否存活。客户端会周期性地向服务端发送心跳请求,报告自己的状态。如果服务端连续几次没有收到客户端的心跳请求,则会将该服务从服务列表中移除。

3. 基于Eureka的服务消费案例

以下是一个简单的服务消费案例,展示了如何使用 Eureka 服务注册与发现功能来实现服务调用:

  1. 创建一个 Eureka 服务端(Eureka Server)项目:
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. application.yml 配置文件中添加 Eureka 服务端的配置:
server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false
  1. 创建一个 Eureka 客户端(Eureka Client)项目:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }

    // 注释掉这个方法,只是为了展示如何使用 Eureka 客户端
    public void demo() {
        // 这里可以调用 Eureka 服务端注册的服务
    }
}
  1. application.yml 配置文件中添加 Eureka 服务端的地址:
spring:
  application:
    name: eureka-client
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  1. 启动 Eureka 服务端和客户端:
  • 启动 Eureka 服务端(Eureka Server),访问 http://localhost:8761,可以看到注册的服务列表。
  • 启动 Eureka 客户端(Eureka Client),它会自动注册到 Eureka 服务端,然后可以在 Eureka 服务端的注册列表中看到。
负载均衡与路由

1. 服务间的负载均衡

负载均衡是指将请求分担到多个服务实例上的过程,这样可以提高系统处理能力,提升系统可用性和稳定性。在微服务架构中,负载均衡可以将请求分担到多个服务实例上,从而实现高可用。

2. Ribbon的工作原理与使用方法

Ribbon 是一个基于 HTTP 和 TCP 的客户端负载均衡器。Ribbon 可以与 Eureka 等服务发现组件配合使用,实现服务间的负载均衡。Ribbon 会将请求中的服务名称转换为对应的 IP 地址,并根据一定的负载均衡策略向后端服务器发送请求。

  • 工作原理:Ribbon 使用客户端负载均衡,它会从服务列表中选取一个服务实例进行请求。Ribbon 会根据一定的策略,如轮询、随机等,对服务实例进行负载均衡。
  • 使用方法:在 Spring Boot 项目中引入 Ribbon 的依赖,然后使用 RestTemplate 来调用服务。

以下是一个简单的使用 Ribbon 进行服务调用的示例:

  1. 创建一个 Eureka 客户端(Eureka Client)项目,并引入 Ribbon 的依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
  1. application.yml 配置文件中添加 Eureka 服务端的地址:
spring:
  application:
    name: eureka-client
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  1. 使用 RestTemplate 调用服务:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}

@Autowired
private RestTemplate restTemplate;

public String callService(String serviceName, String uri) {
    return restTemplate.getForObject("http://" + serviceName + uri, String.class);
}
  1. 在主类中注入 RestTemplate 并调用服务:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public void demo() {
        // 调用服务
        restTemplate().getForObject("http://SERVICE_NAME/uri", String.class);
    }
}

3. Zuul作为API网关的使用方法

Zuul 是一个 API Gateway,它提供了动态的路由和过滤器,可以实现请求的路由、请求的过滤等功能。Zuul 可以与 Eureka、Ribbon 等组件无缝集成,提供服务发现和负载均衡的功能。

以下是一个简单的使用 Zuul 作为 API Gateway 的示例:

  1. 创建一个 Zuul API Gateway 项目,并引入 Zuul 的依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
  1. application.yml 配置文件中添加 Zuul 的配置:
spring:
  application:
    name: zuul-gateway
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
zuul:
  routes:
    service1:
      path: /service1/**
      serviceId: SERVICE_NAME
    service2:
      path: /service2/**
      serviceId: SERVICE_NAME
  1. 在主类中启用 Zuul 的路由功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ZuulGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZuulGatewayApplication.class, args);
    }
}
  1. 启动 Zuul API Gateway,访问 http://localhost:8080/service1/urihttp://localhost:8080/service2/uri,请求会被路由到对应的服务实例。
服务容错与熔断

1. Hystrix实现服务容错

Hystrix 是一个延迟和容错库,用于隔离外部服务访问点、故障fallback、请求缓存和请求压缩等功能。Hystrix 可以实现服务熔断和降级策略,提高系统的容错能力。

2. 断路器的概念及作用

断路器是一个用来监控服务调用状态的组件,当服务调用失败时,断路器会将请求短路,从而避免服务调用失败导致系统崩溃。断路器可以实现服务熔断和降级策略,提高系统的容错能力。

3. 服务熔断与降级策略

当服务调用失败时,断路器会将请求短路,从而避免服务调用失败导致系统崩溃。断路器可以实现服务熔断和降级策略,提高系统的容错能力。以下是一个简单的使用 Hystrix 实现服务熔断的示例:

  1. 创建一个 Eureka 客户端(Eureka Client)项目,并引入 Hystrix 的依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  1. application.yml 配置文件中添加 Hystrix 的配置:
spring:
  application:
    name: eureka-client
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000
  1. 使用 @HystrixCommand 注解实现服务熔断:
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ExecutionException;

@RefreshScope
public class HystrixCommandExample {
    private final RestTemplate restTemplate;

    @Autowired
    public HystrixCommandExample(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String callService(String serviceName, String uri) {
        return new HystrixCommand<String>(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ServiceCall"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("ServiceCall"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(1000))) {
            @Override
            protected String run() {
                return restTemplate.getForObject("http://" + serviceName + uri, String.class);
            }

            @Override
            protected String getFallback() {
                // 返回一个默认值
                return "ServiceCall failed";
            }
        }.execute();
    }
}
  1. 在主类中注入 HystrixCommandExample 并调用服务:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public HystrixCommandExample hystrixCommandExample(RestTemplate restTemplate) {
        return new HystrixCommandExample(restTemplate);
    }

    public void demo() {
        // 调用服务
        hystrixCommandExample().callService("SERVICE_NAME", "/uri");
    }
}
实战案例:构建简单的微服务应用

1. 以SpringCloud搭建的微服务为例

本节将通过 Spring Cloud 搭建一个简单的微服务应用,实现一个简单的 CRUD 操作。该示例将包括服务注册与发现、负载均衡与路由、服务容错与熔断等功能。

2. 整合多个组件,实现一个简单的CRUD操作

我们将使用 Spring Boot 和 Spring Cloud 的多个组件来实现一个简单的 CRUD 操作。具体步骤如下:

  1. 创建一个 Eureka 服务端(Eureka Server)项目,用于服务注册与发现。
  2. 创建一个 Eureka 客户端(Eureka Client)项目,用于服务消费。
  3. 使用 Spring Data JPA 和 Spring Data REST 实现数据持久化和 RESTful API。
  4. 使用 Ribbon 实现负载均衡。
  5. 使用 Hystrix 实现服务容错。

2.1 创建Eureka服务端项目

  1. 创建一个 Spring Boot 项目,并引入 Eureka 服务端的依赖。
  2. 在主类中启用 Eureka 服务端功能。
  3. application.yml 配置文件中添加 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);
    }
}
server:
  port: 8761
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false
    fetch-registry: false

2.2 创建Eureka客户端项目

创建一个 Spring Boot 项目,并引入 Eureka 客户端、Spring Data JPA 和 Spring Data REST 的依赖。

  1. 在主类中启用 Eureka 客户端功能。
  2. application.yml 配置文件中添加 Eureka 服务端的地址。
  3. 使用 Spring Data JPA 和 Spring Data REST 实现数据持久化和 RESTful API。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableJpaRepositories
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public RepositoryRestConfigurer repositoryRestConfigurer() {
        return RepositoryRestConfigurer.withConfig(configurer -> configurer.setBasePath("/api"));
    }
}
spring:
  application:
    name: eureka-client
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
spring:
  data:
    rest:
      base-path: /api
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect

2.3 实现数据持久化和RESTful API

定义一个实体类 Person,并使用 Spring Data JPA 进行数据持久化。然后使用 Spring Data REST 实现 RESTful API。

  1. 创建一个实体类 Person
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Integer age;

    // 省略getter和setter方法
}
  1. 创建一个 Spring Data JPA 仓库 PersonRepository
import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository<Person, Long> {
}
  1. 创建一个控制器 PersonController,使用 PersonRepository 实现 CRUD 操作。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class PersonController {
    @Autowired
    private PersonRepository personRepository;

    @GetMapping("/api/persons")
    public Iterable<Person> getAllPersons() {
        return personRepository.findAll();
    }

    @GetMapping("/api/persons/{id}")
    public Person getPersonById(@PathVariable Long id) {
        return personRepository.findById(id).orElse(null);
    }

    @PostMapping("/api/persons")
    public Person createPerson(@RequestBody Person person) {
        return personRepository.save(person);
    }

    @PutMapping("/api/persons/{id}")
    public Person updatePerson(@PathVariable Long id, @RequestBody Person person) {
        person.setId(id);
        return personRepository.save(person);
    }

    @DeleteMapping("/api/persons/{id}")
    public void deletePerson(@PathVariable Long id) {
        personRepository.deleteById(id);
    }
}

2.4 使用Ribbon实现负载均衡

引入 Ribbon 的依赖,并使用 RestTemplate 调用服务。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}

2.5 使用Hystrix实现服务容错

引入 Hystrix 的依赖,并使用 @HystrixCommand 注解实现服务熔断。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ExecutionException;

@RefreshScope
public class HystrixCommandExample {
    private final RestTemplate restTemplate;

    @Autowired
    public HystrixCommandExample(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String callService(String serviceName, String uri) {
        return new HystrixCommand<String>(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ServiceCall"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("ServiceCall"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(1000))) {
            @Override
            protected String run() {
                return restTemplate.getForObject("http://" + serviceName + uri, String.class);
            }

            @Override
            protected String getFallback() {
                // 返回一个默认值
                return "ServiceCall failed";
            }
        }.execute();
    }
}

3. 微服务的打包与部署

将微服务应用打包成可执行的 JAR 文件并部署到服务器上。可以使用 Maven 或 Gradle 来打包应用。以下是一个使用 Maven 打包的示例:

  1. 在项目的 pom.xml 文件中配置打包插件。
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
  1. 使用 Maven 打包应用。
mvn clean package
  1. 将打包好的 JAR 文件部署到服务器上,并启动服务。
java -jar target/springcloud-demo-0.0.1-SNAPSHOT.jar
點擊查看更多內容
TA 點贊

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

評論

作者其他優質文章

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

100積分直接送

付費專欄免費學

大額優惠券免費領

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

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

幫助反饋 APP下載

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

公眾號

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

舉報

0/150
提交
取消