"In-depth Practice of Spring Boot" Reading Notes II: Distributed Application Development

The last article summarizes the first part of "In-depth Practice of Spring Boot", this article introduces the second part: distributed application development, and how to build a high-performance service platform.

It is mainly summarized from the following aspects:

  • Spring Boot SSO
  • Using a distributed file system
  • Cloud application development
  • Build a high-performance service platform

Spring Boot SSO

The last article mentioned security design, using Spring Security for user authentication and permission authentication, but there may be many application systems in an enterprise-level application system, and each application system needs to design security management, but it is impossible for every application system. Designing a set of security management is not only time-consuming and labor-intensive, but also requires repetitive work, and it is not suitable to establish a unified user center.

A single sign-on (SSO) method can be used to establish a login authentication system and realize unified management of users. This chapter is implemented based on the use of Spring Security security management and combined with the OAuth2 authentication and authorization protocol. It is not only suitable for large-scale distributed management systems, but also for third-party platforms that provide unified user management and authentication.

The author gives a complete example, which is implemented in a modular design. The code of the entire demo can be viewed on github. (https://github.com/chenfromsz/spring-boot-sso

demo description

I ran the demo locally, and viewed the process of jumping between systems through chrome. First, I explained the division of modules, and then looked at the running effect.

project project Types of Function
database management module mysql Program integration database management
Security Configuration Module security Program integration Security Policy Configuration and Rights Management
Login authentication module login web application SSO login authentication (80)
shared resource module resource web application Shared Resources (8083)
Client application 1 web1 web application Client 1 (8081)
Client application 2 web2 web application Client 2 (8082)

When visiting the home page, jump to the login page and enter the correct account number, password, and verification code.
After successful login, jump to the home page:
front page

When accessing the web1 system and web2 system, you do not need to log in again, and you will log in automatically:
web1 system home page

The "Login Authentication Module" mainly includes verifying user accounts and integrating OAuth2 server-side functions.

"Security Configuration Module" is a public module that integrates the security policy configuration and authority management functions of the SSO client for reference by clients.

"Database Management Module" is a public module that mainly provides database access functions for use by other modules.

The "Shared Resource Module" provides a simple public service that two client applications can call directly through spring-cloud-zuul.

The login authentication module will be mainly introduced later. Other modules are relatively simple and will not be introduced too much.

Modular design can improve code reusability and avoid repeated development. The "database management module" and "security configuration module" in the example can be shared by other modules, reducing most of the duplication of work.
The author's design method is worth learning, and should be used for reference in future system design.

Login authentication module

I drew a flowchart to first understand the basic process of user authentication and permission verification:
Basic processing flow

The entire processing process, Spring Security has helped us automatically realize, we only need to configure and expand the account center data source, the authority center data source, in addition, we can expand the login page, configure rights management rules, anti-attack strategies, record stay logged in.

In order to achieve multiple systems with only one login, OAuth2 needs to be integrated. Add spring-cloud-starter-oauth2 dependency, write a configuration class, inherit AuthorizationServerConfigurerAdapter, and declare @EnableAuthrizationServer to enable the authentication server function of OAuth2.

OAuth2 has many authorization mechanisms. In this example, the authorization_code mechanism is used. The specific configuration will not be explained too much. You can refer to the following articles:

[1] Preliminary understanding of Spring Security and practice
[2] Implementation principle of security OAuth2.0 provider
[3] Introduction to jwt token
[4] Example of perfect integration of security OAuth2.0 jwt

Using a distributed file system

There is such a question, if uploading a file, such as uploading a picture, how should it be saved and where should it be saved?

Traditional practices are generally stored in the machine where the Web server is located. However, with the increasing development of the business, more and more files may be uploaded, and a single machine is often overwhelmed. Coupled with some load balancing configurations and services, a distributed file system is needed.

Among many distributed file systems, FastDFS is an excellent distributed file system. FastDFS is a completely open source distributed file system, which is relatively simple and convenient to use, and has excellent performance. The storage capacity and access performance can be scaled linearly and horizontally as required.

The arrangement, configuration, and management of the FastDFS server and client are relatively simple, and the descriptions in the book are also detailed, so I won't repeat them here.

Cloud application development

Spring Cloud is a set of cloud application development tools, providing a set of easy-to-use tools for distributed microservice development. Spring Cloud mainly includes development toolkits for configuration management, service discovery, dynamic routing, load balancing, circuit breakers, security management, event bus, distributed messaging and other components.

Spring Cloud is closely related to Spring Boot and can be used for perfect geometry.

This chapter focuses on configuration services, discovery services, dynamic routing and circuit breakers, and monitoring services.

configuration service

A project always needs some configuration, for example, to configure the port of the server, parameters to access the database, etc. A large distributed system may have many projects that need to be configured. Configuration management is a huge project and requires a separate system to manage the configuration of each project.

Through Spring Cloud's configuration management, you only need to create a simple project to implement distributed configuration management services, and also support online updates.

The first step, the configuration management server
introduces the spring-cloud-config-server dependency and creates a main program:

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

The storage of configuration files currently supports the use of local storage, Git, and Subversion. Take Git as an example to illustrate the local configuration file:

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/chenfromsz/spring-cloud-config-repo
  rabbitmq:
      addresses: ${vcap.services.${PREFIX:}rabbitmq.credentials.uri:amqp://${RABBITMQ_HOST:192.168.1.215}:${RABBITMQ_PORT:5672}}
      username: alan
      password: alan

The server will automatically obtain configuration information from the specified git address. raabitmq's configuration is used to notify client applications of configuration updates.

In the second step, the client of configuration management
needs to introduce the spring-cloud-starter-config dependency into the project. After using the configuration management service, if the local configuration file has the same configuration items as the configuration management server configuration file, it will be used first. Configure the configuration items of the management server.

The client's configuration file bookstrap.yml is as follows:

spring:
  application:
    name: data
  profiles:
    active: development
  cloud:
    config:
      uri: http://localhost:8888
  rabbitmq:
        addresses: amqp://192.168.1.214:5672
        username: alan
        password: alan

Among them, name is used to specify the name of the application and the name of the configuration file, uri sets the address and port of the configuration server, and profiles is the suffix part of the name of the configuration file used to bind different online environments.

The third step, use the configuration
If there is a cloud.config.test configuration item in the configuration file, you can use it like this

@Value("${cloud.config.test:World!}") String msg;

In addition, you can use the spring-cloud-bus-amqp dependency to update the configuration of all clients online through the event bus.

discovery service

In a distributed system, there may be many applications and services, and each service manages its own data autonomously. Services need to share some data with each other. In the traditional way, you need to write some interface programs yourself, and you need to use complex configuration to achieve this. You can easily do this with Spring Cloud.

The first step is to create a discovery server and
introduce the spring-cloud-starter-eureka-server dependency, and create a simple main program:

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

The second step is to create a client to
introduce the spring-cloud-starter-eurake dependency, and add @EnableDiscoveryClient to the main program to enable the client of the discovery service.

The configuration file is as follows:

eureka:
  instance:
    hostname: discovery
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://192.168.1.221:${server.port}/eureka/
Dynamic Routing and Circuit Breakers

How to call each other between services, you can use functions such as dynamic routing, circuit breakers, and fault tolerance.

Introduce spring-cloud-starter-zuul, spring-cloud-starter-hystrix dependencies, and add @EnableZuulProxy and @EnableHystrix annotations.

In order to facilitate testing, the repository class can be directly exposed by sharing Rest resources, which is amazing, as follows:

@RepositoryRestResource(collectionResourceRel="users",path="users")
public interface UserRepository extends GraphRepository<User> {
    User findByName(@Param("name") String name);

    @Query("MATCH (u:User) WHERE u.name =~ ('(?i).*'+{name}+'.*') RETURN u")
    Collection<User> findByNameContaining(@Param("name") String name);

}

It can be accessed through http://localhost/users, http://localhost/users/123 and so on.

The interfaces exposed by other services are called in the following three ways:

  • JavaScript: the front end calls directly
  • RestTemplate: backend call
  • FeignClient: special way

Take RestTemplate as an example to illustrate an example of a service calling the data service:

 @Autowired @LoadBalanced
 RestTemplate restTemplate;
 @HystrixCommand(fallbackMethod = "getUserFallback")
     public User getUserByName(String name) {
         Map<String, Object> params = new HashMap<>();
         params.put("name", name);
         User user = restTemplate.getForObject("http://data/user/findByName?name={name}", User.class, params);

         return user;
 }

In the above example, @HystrixCommand is used to implement a circuit breaker. When a system service suddenly fails, it will automatically block access and invocation of the service, and call the backup method instead.

Monitoring service

There are many services running in the distributed service system, and there must be a management mechanism and method, which can understand the operation status of each service and its health index at a glance.

Using Spring Cloud's monitoring service, you can monitor the running status of your application in real time. It is very simple to use, introduce the spring-cloud-starter-hystrix-dashboard dependency, and create a main program:

@SpringBootApplication
@Controller
@EnableHystrixDashboard
public class HystrixApplication{
    @RequestMapping("/")
    public String home() {
        return "forward:/hystrix";
    }

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

For specific monitoring indicators, please refer to the official website documentation.

Build a high-performance service platform

The independent and relatively isolated characteristics of microservices developed with Spring Cloud are similar to the concept of Docker. Therefore, using Docker to publish microservices can give full play to its greatest advantages, and can easily build a high-performance and Highly available service platform.

Docker makes it easy to create and manage images, as well as manage built and running containers. Mirroring is a file storage method that can make many files into a mirror file. A container is an instance of image operation. When an image is run, a container will be generated. After the container is generated, the application system can be managed in the container.

There is a lot of information on the Internet about Docker's installation and publishing services, so I won't go into details here.

In addition, some other service management tools can be used to build high-performance and high-availability service platforms. The docker-compose tool is a set of Docker container management tools, which can be easily used to create and rebuild containers, perform management operations such as starting and stopping containers, and view the running status and output logs of the entire service system. Using the docker-compose tool, you can start the entire distributed service system with just one command.

Through the introduction of this article, you can feel the convenience provided by Spring Cloud when building distributed applications, reducing a lot of workload. At the same time, we have considered all aspects to enhance the stability and high performance of the system.
The author uploaded all the code to github, and you can directly run the demo to learn more.
[1] Spring Boot SSO: https://github.com/chenfromsz/spring-boot-sso
[2] Cloud application development: https://github.com/chenfromsz/spring-boot-cloud

love story

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324679487&siteId=291194637