Home  >  Article  >  Java  >  Build a distributed, highly available Spring Cloud microservice system

Build a distributed, highly available Spring Cloud microservice system

王林
王林Original
2023-06-22 09:06:25992browse

With the continuous development of Internet business, microservice architecture has become the preferred architecture method for more and more enterprises. As a microservice framework based on Spring Boot, Spring Cloud has the characteristics of distribution and high availability. More and more companies are beginning to use it to build their own microservice systems.

This article will introduce how to use Spring Cloud to build a highly available, distributed microservice system.

1. Build the registration center

The registration center is one of the core components of the Spring Cloud microservice architecture. All microservices need to register their own information with the registration center, and then other services can pass Find this service in the registration center. In Spring Cloud, Eureka is a very excellent registration center component. It has high availability, distributed and other characteristics, and can meet the needs of various scenarios. Therefore, we chose to use Eureka to build the registration center.

Before using Eureka to build a registration center, we need to understand some basic concepts of Eureka:

  1. Eureka Server: The server side of Eureka, used to accept registration information from the client and maintain it List of information about service instances.
  2. Eureka Client: Eureka client, used to register its own services with Eureka Server.
  3. Service instance: A running instance of a microservice. The service instance contains the IP address, port number, health status and other information of the service.

The steps to use Eureka to build a registration center are as follows:

  1. Create a new Spring Boot project.
  2. Add dependencies: Add the following dependencies in the pom.xml file:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  1. Add the following configuration in the application.yml file:
server:
  port: 8761    #设置服务端口号

eureka:
  instance:
    hostname: localhost    #设置Eureka Server的主机名
  client:
    register-with-eureka: false    #设置是否注册自身服务,默认为true,这里设置为false
    fetch-registry: false    #设置是否获取注册列表,默认为true,这里设置为false
  server:
    enable-self-preservation: false    #设置是否启用自我保护机制,默认为true,这里设置为false
  1. Create a new Spring Boot startup class and add the @EnableEurekaServer annotation to start the Eureka service:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

Through the above steps, we will succeed A registration center based on Eureka was built. We can enter http://localhost:8761 in the browser to access the Eureka Server console and see that no services are currently registered to Eureka Server.

2. Building a service provider

A service provider is a microservice that implements specific business. It will register its own information with the registration center so that other microservices can discover it and call it. service provided.

We use a simple example here to build an HTTP service provider that can accept HTTP requests and return a string.

The steps to build a service provider using Spring Cloud are as follows:

  1. Create a new Spring Boot project.
  2. Add dependencies: Add the following dependencies in the pom.xml file:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. Add the following configuration in the application.yml file:
server:
  port: 8080    #设置服务端口号

spring:
  application:
    name: test-service    #设置服务名称,用于注册到Eureka Server中

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/    #设置Eureka Server地址
  1. Create a new Controller class and add an interface that returns a string:
@RestController
public class TestController {
    @GetMapping("/test")
    public String test() {
        return "Hello World";
    }
}
  1. Add the @EnableDiscoveryClient annotation to the startup class, using To enable the service discovery function:
@SpringBootApplication
@EnableDiscoveryClient
public class TestServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestServiceApplication.class, args);
    }
}

Through the above steps, we have successfully built a service provider. We can enter http://localhost:8080/test in the browser to access the services it provides. If everything is normal, we can see the return value of Hello World.

3. Building a service consumer

A service consumer is a microservice that calls services provided by other microservices. It will query the registration center for the required microservices and then call the microservices provided. services.

The steps to build a service consumer using Spring Cloud are as follows:

  1. Create a new Spring Boot project.
  2. Add dependencies: Add the following dependencies in the pom.xml file:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. Add the following configuration in the application.yml file:
server:
  port: 8090    #设置服务端口号

spring:
  application:
    name: test-consumer    #设置服务名称

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/    #设置Eureka Server地址
  1. Add a Service class for calling the service provider:
@Service
public class TestService {
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallback")
    public String test() {
        return restTemplate.getForObject("http://test-service/test", String.class);
    }

    public String fallback() {
        return "fallback";
    }
}
  1. Add a Controller class for exposing the service interface:
@RestController
public class TestController {
    @Autowired
    private TestService testService;

    @GetMapping("/test")
    public String test() {
        return testService.test();
    }
}
  1. Add the @EnableDiscoveryClient annotation in the startup class to enable the service discovery function:
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker    #启用熔断器功能
public class TestConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestConsumerApplication.class, args);
    }

    @Bean
    @LoadBalanced    #启用负载均衡功能
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Through the above steps, we successfully built a service consumer , which can call the service provider's services and return the correct results.

4. Build API Gateway

API gateway is the entrance to the microservice system. It plays multiple roles such as routing, load balancing, and security control. In Spring Cloud, Zuul is an excellent API gateway component that can meet our various needs.

The steps to build an API gateway using Spring Cloud are as follows:

  1. Create a new Spring Boot project.
  2. Add dependencies: Add the following dependencies in the pom.xml file:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
  1. Add the following configuration in the application.yml file:
server:
  port: 8888    #设置服务端口号

spring:
  application:
    name: api-gateway    #设置服务名称

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/    #设置Eureka Server地址

zuul:
  routes:
    test-service:
      path: /test/**
      serviceId: test-service    #设置服务提供者名称
  1. Add the @EnableZuulProxy annotation to the startup class to enable the Zuul proxy function:
@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}

Through the above steps, we successfully built an API gateway , it can forward the http://localhost:8888/test request to the service provider and return the correct result.

5. Build a configuration center

The configuration center can centrally manage the configuration information in the microservice system. Through the configuration center, we can configure the system more conveniently.

在Spring Cloud中,Config Server是一个优秀的配置中心组件,它可以与Eureka、Zuul等组件配合使用,构建一个完整的微服务体系。

使用Spring Cloud构建配置中心的步骤如下:

  1. 新建一个Spring Boot项目。
  2. 添加依赖:在pom.xml文件中添加如下依赖:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
  1. 在application.yml文件中添加如下配置:
server:
  port: 8888    #设置服务端口号

spring:
  application:
    name: config-server    #设置服务名称

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/    #设置Eureka Server地址

# 配置中心
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/{username}/{repository}.git    #设置git仓库地址
          username: {username}    #设置git用户名
          password: {password}    #设置git密码
          search-paths: respo1A/config, respo1B/config    #设置配置文件搜索路径
          default-label: main    #设置git分支
  1. 在启动类中添加@EnableConfigServer注解,用于启用Config Server功能:
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

通过以上的步骤,我们就成功构建了一个Config Server。我们可以将配置文件上传到git仓库中,然后通过http://localhost:8888/application-dev.properties的方式获取指定的配置文件。

六、 总结

通过以上的步骤,我们成功地构建了一个高可用、分布式的Spring Cloud微服务体系,包括了注册中心、服务提供者、服务消费者、API网关和配置中心。在实际应用过程中,我们可以通过这些组件自由组合,构建出更加复杂、高效的微服务体系。

The above is the detailed content of Build a distributed, highly available Spring Cloud microservice system. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn