search
HomeJavajavaTutorialBuild a distributed, highly available Spring Cloud microservice system

Build a distributed, highly available Spring Cloud microservice system

Jun 22, 2023 am 09:06 AM
High availabilityDistributed Systemsspring cloud microservices

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.