Home Java javaTutorial Build a distributed and secure Spring Cloud microservice flight system

Build a distributed and secure Spring Cloud microservice flight system

Jun 22, 2023 am 08:06 AM
spring cloud Safety distributed

With the development of cloud computing and the continuous expansion of enterprise business, microservice architecture has become a very popular system architecture. Among them, Spring Boot and Spring Cloud are currently the most commonly used microservice frameworks. Spring Cloud provides a wealth of components to support the development and management of microservices, including service registration and discovery, routing, load balancing, configuration management, circuit breakers, etc.

In this article, we will build a distributed and secure Spring Cloud microservice flying system as a case to demonstrate the powerful functions of Spring Cloud.

  1. Service registration and discovery

First, we need to register and discover services. Spring Cloud provides Eureka to help us realize service registration and discovery. We will complete the registration and discovery of services through Eureka Server.

Create Eureka Server application:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

Configure in application.properties:

server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
Copy after login

In the service provider and service consumer applications, we need to register it to Eureka Server.

Configured in the application.properties of the service provider:

spring.application.name=flight-service-provider
server.port=8080

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Copy after login

Configured in the application.properties of the service consumer:

spring.application.name=flight-service-consumer
server.port=8081

eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
Copy after login
  1. Inter-service communication

The service provider creates a RESTful interface through Spring MVC:

@RestController
@RequestMapping("/flights")
public class FlightController {

    @GetMapping("/{flightId}")
    public ResponseEntity<Flight> getFlight(@PathVariable Integer flightId) {
        Flight flight = new Flight(flightId, "Shanghai", "Beijing", new Date());
        return new ResponseEntity<>(flight, HttpStatus.OK);
    }
}
Copy after login

The service consumer calls the service through Spring RestTemplate:

@Service
public class FlightService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service.provider.url}")
    private String serviceProviderUrl;

    public Flight getFlight(Integer flightId) {
        return restTemplate.getForObject(serviceProviderUrl + "/flights/{flightId}", Flight.class, flightId);
    }
}
Copy after login

Among them, service.provider.url is in the application Configure in application.properties of the program.

  1. Load Balancing

In actual applications, service providers are likely to be deployed on multiple instances. At this time, we need to perform load balancing to improve the system's performance. Performance and availability. Spring Cloud provides Ribbon to support load balancing.

Configure in the application.properties of the service consumer:

service.provider.url=http://flight-service-provider/
spring.cloud.loadbalancer.ribbon.enabled=true
Copy after login

Use the load-balanced RestTemplate in FlightService:

@Service
public class FlightService {

    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate;

    @Value("${service.provider.name}")
    private String serviceProviderName;

    public Flight getFlight(Integer flightId) {
        return restTemplate.getForObject("http://" + serviceProviderName + "/flights/{flightId}", Flight.class, flightId);
    }
}
Copy after login

Among them, service.provider.name is in the application Configure in application.properties of the program.

  1. Configuration Management

Spring Cloud provides Config to easily manage application configuration. We can store the application configuration in a Git repository and distribute it through Config Server.

Create Config Server application:

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

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

Configure in application.properties:

server.port=8888

spring.cloud.config.server.git.uri=https://github.com/xxx/xxx.git
spring.cloud.config.server.git.search-paths=config-repo
Copy after login

In service providers and service consumers, we can obtain it through Config Server Application configuration.

Configure in the service provider's application.yml:

spring:
  application:
    name: flight-service-provider
  cloud:
    config:
      uri: http://localhost:8888
      label: master
      profile: dev
Copy after login

Configure in the service consumer's application.yml:

spring:
  application:
    name: flight-service-consumer
  cloud:
    config:
      uri: http://localhost:8888
      label: master
      profile: dev
Copy after login
  1. Circuit breaker

In a microservice architecture, because the dependencies between services are very complex, downtime or problems in some services may cause the entire system to collapse. To deal with this situation, we can use circuit breakers to handle service degradation.

Spring Cloud provides Hystrix to support the circuit breaker function.

Configure in the application.yml of the service consumer:

spring:
  application:
    name: flight-service-consumer
  cloud:
    config:
      uri: http://localhost:8888
      label: master
      profile: dev
  loadbalancer:
    ribbon:
      enabled: true
  circuitbreaker:
    enabled: true
    resilience4j:
      enabled: false
      circuitBreaker:
        backend: flight-service-provider
        failureRateThreshold: 50
Copy after login

Add @HystrixCommand annotation in FlightController:

@RestController
@RequestMapping("/flights")
public class FlightController {

    @Autowired
    private FlightService flightService;

    @GetMapping("/{flightId}")
    @HystrixCommand(fallbackMethod = "defaultGetFlight")
    public ResponseEntity<Flight> getFlight(@PathVariable Integer flightId) {
        Flight flight = flightService.getFlight(flightId);
        if (flight != null) {
            return new ResponseEntity<>(flight, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    public ResponseEntity<Flight> defaultGetFlight(Integer flightId) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Copy after login

Among them, defaultGetFlight is the downgrade function.

  1. Security

In distributed systems, security issues are very important. Spring Cloud provides Security to support security management.

Add in the pom.xml of the service provider and service consumer applications:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-security</artifactId>
</dependency>
Copy after login

Configure in the application.yml of the service provider and service consumer applications:

security:
  basic:
    enabled: true

spring:
  security:
    user:
      name: user
      password: password
Copy after login

Among them, name and password are the user's name and password respectively. It should be noted that in actual applications, more secure methods must be used for user authentication and authorization management.

Add the @PreAuthorize annotation at the class level of FlightController:

@RestController
@RequestMapping("/flights")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class FlightController {

    @Autowired
    private FlightService flightService;

    @GetMapping("/{flightId}")
    public ResponseEntity<Flight> getFlight(@PathVariable Integer flightId) {
        Flight flight = flightService.getFlight(flightId);
        if (flight != null) {
            return new ResponseEntity<>(flight, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
Copy after login

Among them, the @PreAuthorize annotation is used to perform security verification on FlightController. In actual applications, different security verifications can be performed on each method.

In this way, we have completed the construction of a distributed and secure Spring Cloud microservice flight system. Through the cases in this article, we can see that Spring Cloud provides a wealth of components to help us build microservices. At the same time, we also need to pay attention to some challenges brought by microservice architecture, such as service registration and discovery, inter-service communication, load balancing, configuration management, circuit breakers, security and other issues. In actual applications, we need to make technology selection and configuration based on specific scenarios.

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

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of how to turn off Windows 11 Security Center Detailed explanation of how to turn off Windows 11 Security Center Mar 27, 2024 pm 03:27 PM

In the Windows 11 operating system, the Security Center is an important function that helps users monitor the system security status, defend against malware, and protect personal privacy. However, sometimes users may need to temporarily turn off Security Center, such as when installing certain software or performing system tuning. This article will introduce in detail how to turn off the Windows 11 Security Center to help you operate the system correctly and safely. 1. How to turn off Windows 11 Security Center In Windows 11, turning off the Security Center does not

Tips for turning off real-time protection in Windows Security Center Tips for turning off real-time protection in Windows Security Center Mar 27, 2024 pm 10:09 PM

In today's digital society, computers have become an indispensable part of our lives. As one of the most popular operating systems, Windows is widely used around the world. However, as network attack methods continue to escalate, protecting personal computer security has become particularly important. The Windows operating system provides a series of security functions, of which "Windows Security Center" is one of its important components. In Windows systems, "Windows Security Center" can help us

How should the Java framework security architecture design be balanced with business needs? How should the Java framework security architecture design be balanced with business needs? Jun 04, 2024 pm 02:53 PM

Java framework design enables security by balancing security needs with business needs: identifying key business needs and prioritizing relevant security requirements. Develop flexible security strategies, respond to threats in layers, and make regular adjustments. Consider architectural flexibility, support business evolution, and abstract security functions. Prioritize efficiency and availability, optimize security measures, and improve visibility.

PHP Microframework: Security Discussion of Slim and Phalcon PHP Microframework: Security Discussion of Slim and Phalcon Jun 04, 2024 am 09:28 AM

In the security comparison between Slim and Phalcon in PHP micro-frameworks, Phalcon has built-in security features such as CSRF and XSS protection, form validation, etc., while Slim lacks out-of-the-box security features and requires manual implementation of security measures. For security-critical applications, Phalcon offers more comprehensive protection and is the better choice.

Security configuration and hardening of Struts 2 framework Security configuration and hardening of Struts 2 framework May 31, 2024 pm 10:53 PM

To protect your Struts2 application, you can use the following security configurations: Disable unused features Enable content type checking Validate input Enable security tokens Prevent CSRF attacks Use RBAC to restrict role-based access

AI's new world challenges: What happened to security and privacy? AI's new world challenges: What happened to security and privacy? Mar 31, 2024 pm 06:46 PM

The rapid development of generative AI has created unprecedented challenges in privacy and security, triggering urgent calls for regulatory intervention. Last week, I had the opportunity to discuss the security-related impacts of AI with some members of Congress and their staff in Washington, D.C. Today's generative AI reminds me of the Internet in the late 1980s, with basic research, latent potential, and academic uses, but it's not yet ready for the public. This time, unchecked vendor ambition, fueled by minor league venture capital and inspired by Twitter echo chambers, is rapidly advancing AI’s “brave new world.” The "public" base model is flawed and unsuitable for consumer and commercial use; privacy abstractions, if present, leak like a sieve; security structures are important because of the attack surface

Implementing Machine Learning Algorithms in C++: Security Considerations and Best Practices Implementing Machine Learning Algorithms in C++: Security Considerations and Best Practices Jun 01, 2024 am 09:26 AM

When implementing machine learning algorithms in C++, security considerations are critical, including data privacy, model tampering, and input validation. Best practices include adopting secure libraries, minimizing permissions, using sandboxes, and continuous monitoring. The practical case demonstrates the use of the Botan library to encrypt and decrypt the CNN model to ensure safe training and prediction.

Which wallet is safer for SHIB coins? (Must read for newbies) Which wallet is safer for SHIB coins? (Must read for newbies) Jun 05, 2024 pm 01:30 PM

SHIB coin is no longer unfamiliar to investors. It is a conceptual token of the same type as Dogecoin. With the development of the market, SHIB’s current market value has ranked 12th. It can be seen that the SHIB market is hot and attracts countless investments. investors participate in investment. In the past, there have been frequent transactions and wallet security incidents in the market. Many investors have been worried about the storage problem of SHIB. They wonder which wallet is safer for SHIB coins at the moment? According to market data analysis, the relatively safe wallets are mainly OKXWeb3Wallet, imToken, and MetaMask wallets, which will be relatively safe. Next, the editor will talk about them in detail. Which wallet is safer for SHIB coins? At present, SHIB coins are placed on OKXWe

See all articles