Introduction to SpringBoot: asynchronous, mail tasks, scheduled tasks, distributed RPC overview, Dubbo and Zookeeper

Asynchronous task

Asynchronous overview

Asynchrony is to start the next request immediately after sending a request, regardless of whether the return value is received or not, or whether the return value is received after a long time. Compared with the system, it has great advantages because it makes great use of resources.

It is opposite to the synchronization task. After the synchronization task starts, it will take the next action only when there is a return value.

It is generally linked to time, such as mail tasks and scheduled tasks

Asynchronous task test

  • Create a springboot project and add web Framework dependencies

  • Asynchronous request to write service layer

    package com.michilay.service;
    
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class AsyncService {
    
        public void hello(){
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Data processing...");
        }
    
    }
    
  • The controller layer invokes asynchronous requests

    package com.michilay.controller;
    
    import com.michilay.service.AsyncService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class AsyncController {
        @Autowired
        AsyncService asyncService;
    
        @RequestMapping("/hello")
        public String hello(){
    //        Stop for three seconds and wait
            asyncService.hello();
            return "ok";
        }
    
    }
    
  • In the test, when we execute the hello request, we will wait three seconds for a response

However, in display development, if you want users to get a data directly, you need to call multithreading to process data in the background. It is very troublesome for us to write these multithreading processes manually.

The good news is that spring can help us handle these things. We can tell spring that this is an asynchronous method through the @ Async annotation. In addition, @ EnableAsync should be added to enable the asynchronous hosting function of spring

  • Add comments to the service

    @Async
    public void hello(){
    
  • Add comments on main

    @EnableAsync
    @SpringBootApplication
    public class Springboot10AsyncApplication {
    
  • When you execute the hello request again, you can find that the direct output is ok, while the information of South is displayed three seconds later, and the asynchronous test passes

Mail task

In Java Web, you need to import javax Mail configuration is cumbersome, and spring also simplifies the function of mail tasks

  • Import dependent

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    
  • Open POP3/SMTP service in mailbox

  • Configure mail related information

    spring.mail.username=1912400157@qq.com
    spring.mail.password=Authorization code
    spring.mail.host=smtp.qq.com
    #Enable encryption verification (qq proprietary)
    spring.mail.properties.mail.smtp.ssl.enable=true
    
  • Writing test classes

    package com.michilay;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    
    @SpringBootTest
    class Springboot10AsyncApplicationTests {
        @Autowired
        JavaMailSenderImpl mailSender;
        @Test
        void contextLoads() {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject("Test message subject name");
            mailMessage.setText("Test message text content");
            mailMessage.setTo("1912400157@qq.com");
            mailMessage.setFrom("1912400157@qq.com");
            mailSender.send(mailMessage);
        }
    
    }
    

    Send yourself a simple email

  • Slightly more complex mail sending

    @Test
    void contextLoads2() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        helper.setSubject("Test message subject 2");
        helper.setText("<p style='color:red'>Test message text content</p>",true);
        helper.addAttachment("1.jpg",new File("C:\\Users\\Michilay\\Desktop\\1.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\Michilay\\Desktop\\2.jpg"));
        helper.setTo("1912400157@qq.com");
        helper.setFrom("1912400157@qq.com");
        mailSender.send(mimeMessage);
    }
    

Timed task

  • Enable annotation support

    @EnableScheduling
    
  • Write the Service for testing, add the @ Scheduled annotation, and add a cron expression

    package com.michilay.service;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ScheduledService {
    
    //    Second minute hour day month week
        @Scheduled(cron = "0 45 10 * * ?")
        public void hello(){
            System.out.println("hello Executed");
        }
    }
    

    The above code indicates that the South statement is executed at 10:45

Cron expression

30 15 10 * * ? Every day at 10:15:30

30 0/5 10,18 * * ? At 10:00 and 18:00 every day, every 5 minutes

0 15 10 ? * 1-6 at 10:15 on the 1st-6th of each month

Distributed

Distributed system overview

A distributed system is a collection of several independent computers, which are a single related system relative to users

For example, to play a game, you need to turn on accelerators. The servers of these accelerators are distributed all over the world, but in the end they all point to the official data servers. In other words, for users, all these server collections look like a single system, which is a distributed system

A distributed system is interconnected internally through http or RPC. They are used as coordination to complete common tasks (started by google)

RPC

At the beginning of system development, it was ORM, and all the contents were put in one container

For the convenience of development, system frameworks have evolved, such as LAMP and MVC

However, when a computer server is not enough, it is necessary to use RPC technology to connect the servers to form a distributed system

If the amount of data is larger, SOA cloud server is used

There is no difference between Rpc and http in nature. They are communication related protocols.

It is a technical idea, not a specification. It allows programs to call procedures or functions in another address space

Two core modules of rpc: communication and serialization

Serialization: data transfer requires conversion

Dubbo

Dubbo is a high-performance, lightweight open source java RPC framework

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-yfjpjd3m-1629953842569) (C: \ users \ michelay \ appdata \ roaming \ typora \ user images \ image-20210826114506847. PNG)]

Provider: provider, the part that performs data access operations, which can correspond to service impl

Consumer: consumer, the item that invokes the service

Container:Dubbo container, which depends on the spring container and starts when the spring container starts

Registry: Registry. When Contanier is started, the provider registers the list of all services available in the registry

Tell comsumer which services are provided and the location of the service provider. zookeeper is often used as the registration center

Operation process

  1. Starting the container is equivalent to starting Dubbo's Provider

  2. After startup, register the list of all services provided in the registry

  3. After the Consumer starts, it will go to the registry to subscribe to the registration list and the address of the Provider

  4. When the registry finds that the Provider has changed, it will push the message to the consumer

  5. According to the obtained Provider address, call the functions in the Provider (proxy mode)

  6. Comsumer and provider send statistics to monitor every minute

Zookeeper

Zookeeper encapsulates those complex and error prone distributed consistency services to form an efficient and reliable primitive set, and provides users with a series of simple and easy-to-use interfaces.

  • download Index of /dist/zookeeper/zookeeper-3.4.14 (apache.org) And decompress
  • Open zkserver.com under the bean directory cmd
    • If you encounter a flash back problem, open it with an editor, add pause after the call statement, check the cause of the error, find and zoo Config related
    • Open the conf directory and copy the zoo_sample.cfg save another copy named zoo cfg
  • Run zkserver CMD, and then run zkcli CMD, enter ls / test on the client after connecting

Dubbo admin test

  • Download the project (because there is something wrong with github, I copied it to gitee)

    git clone -b master-0.2.0 https://gitee.com/michilay/dubbo-admin.git

  • Package the project under the main directory structure

    mvn clean package -Dmaven.test.skip=true

  • Packaging failed (OK), open with idea

  • Open zookeeper

zookeeper is equivalent to a registry, and Dubbo admin is a monitoring and management background, which can be packaged into jar packages

Keywords: Java Dubbo Spring Boot Zookeeper

Added by tzicha on Mon, 20 Dec 2021 00:14:36 +0200