SpringCloud micro Services Architecture upgrade summary

One, background

1.1 application system architecture history

1.2 What is a micro-service?

Origins: The concept of micro-services from March 2014 Martin Fowler wrote an article "Microservices". Text content mentioned: micro-services architecture is an architectural pattern, it advocates a single application into a set of smaller services, co-ordination between services, complement each other, providing the ultimate value for the user.

Communication: Each service runs in its separate process, the inter-service and service lightweight communication mechanism to communicate with each other (usually HTTP-based RESTful API) used.

Conventional definition of micro services: Micro service is an architectural style, a large and complex software applications by one or more micro-service. Each micro service system may be independently deployed between the respective micro-services are loosely coupled. Each micro serve only to focus on the completion of a task.

The original process of a complete service, split into two or more service processes, and there is a call relationship between each other, compared with the original single process services, is the "micro-services." (Micro Services is a comparative concept, rather than a single concept)

1.3 micro-services architecture advantages

  • Scalability: increased business functions in a single application architecture needs to be done relatively large adjustment in the code on the basis of the original architecture, while the micro-services architecture requires only the addition of new micro-services node, and micro adjustment with associated service node It can be. While increasing business responsiveness, the need for a single architecture overall expansion, while the micro-services architecture requires only a lack of capacity expansion in response to the micro-service node.
  • Resilience: when a system failure, a single application architecture of the system needs to be fixed, and changes related to the start-stop application code, while the micro-services architecture requires only start and stop the service and change the code for the service in question . Other services can implement application-level fault tolerance by retrying, fusing mechanisms.
  • Flexible Technology Selection: under micro Services Architecture, each micro-service node according to the different needs of complete functions, the freedom to choose the most suitable technology stack, even if the reconstruction of a single micro-node service, the cost is very low.
  • Development of higher operation and maintenance efficiency: Each node is a single micro-service process, focused on a single function, and through well-defined interfaces to articulate service boundary. Due to the small size, low complexity, each micro-services can be a small team or individual in complete control, easy to maintain high maintainability and development efficiency.

Spring Cloud as the most popular microblogging service development framework, instead of using the Spring Cloud framework to achieve the micro-service architecture, with the advantages of micro-services architecture. Correct understanding is that the use of Spring Cloud service framework for the development of micro-based systems, the systems have the advantage of micro Services Architecture (Spring Cloud like tools, but also need to "do" process).

1.4 What is Spring Boot? What is Spring Cloud?

Spring Boot Framework is a new framework provided by Pivotal team, which is designed to simplify the development process and initial set up Spring-based applications. SpringBoot framework uses a specific way to configure applications so that developers no longer need to spend a lot of effort to define a template configuration file.

Spring Cloud is a cloud-based application development tool Spring Boot achieve, and it is cloud-based application development in the JVM configuration management, service registration, service discovery, circuit breakers, intelligent routing, micro broker, a control bus, a global lock, decision-election , distributed and clustered session state management and other operations provides a simple way of development.

1.5 micro-services, the relationship between the Spring Boot, Spring Cloud three

  • Idea: Micro service is an architectural concept, the design principle of micro services, specific technical guidelines from the floor to provide a theory.
  • Scaffolding: Spring Boot is a fast configuration scaffolding, based on Spring Boot quickly develop a single micro-services.
  • A collection of multiple components: Spring Cloud is a service-based management tools Spring Boot achieve package; Spring Boot focus on fast, easy integration of a single individual micro services; Spring Cloud services focus on overall governance framework.

Second, technical analysis

2.1 Everything is jar, Everything is http

Spring Boot by @SpringBootApplication notes identified as Spring Boot application. All applications are to compile the package by way jar, deployment and operation.

@SpringBootApplication 
public class Application {     
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);     
    public static void main(String[] args) {         
        SpringApplication.run(Application.class, args);         
        LOGGER.info(”启动成功!");     
    } 
}

Each Spring Boot application can provide services through the embedded web container http way, only need to rely on spring-boot-start-web in the pom file can, in principle, micro Services Architecture expect each individual node provides service http .

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

2.2 Spring boot Task scheduled task and the task starts

When Spring Boot need to start the task, as long as the inheritance CommandLineRunner interface that can be run method.

@SpringBootApplication 
public class ClientDataListener implements CommandLineRunner
    public void run(String... strings) throws Exception {     
        clientInfoListenerHandler(); 
    }
}

When Spring Boot need to perform regular tasks, just add @Scheduled method on regular tasks (cron = "0 15 0 ?") Notes (support standard cron expression), and an increase in notes @EnableScheduling startup class service that is can.

@SpringBootApplication
@EnableScheduling
public class Application {     
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);     
    public static void main(String[] args) {         
        SpringApplication.run(Application.class, args);         
        LOGGER.info(”启动成功!");     
    } 
}
// some class
@Scheduled(cron = "0 15 0 * * ?")
public void someTimeTask() {
    ***
}

2.3 Spring boot Actuator monitored

Actuator system itself is a component for monitoring the application of spring boot provided, the introduction of spring-boot-starter-actuator can be incorporated in a spring-boot-start-web basis.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

2.4 Spring cloud Config distribution center

When we realize micro-service architecture, each micro-services node requires its own configuration data items, when many nodes, it becomes very difficult to maintain, requiring the establishment of a central configuration service.

Spring Cloud Config is divided into two parts. Spring Cloud Config server as a service process, Spring Cloud Config File storage location for the configuration file.

2.5 Spring cloud Eureka service registry

The concept of service registration long before the emergence of micro-services architecture, micro-architecture service has even split the original single node application into a very large number of micro-services node. Call the relationship between each other will be very complicated, Spring Cloud Eureka as a registration center, all services can be micro-register itself to Spring Cloud Eureka unified management and access (Eureka and different Zookeeper, select the OP AOP in principle, more emphasis on the effectiveness of services)

2.6 Spring cloud Zuul end intelligent routing service

When we put all the services are registered to Eureka (service registry) in the future, it involves the issue of how to call. Spring Cloud Zuul is a server-side proxy component Spring Cloud provides, can be seen as a gateway, Zuul by Eureka to obtain the services available through the mapping configuration, the client needs to access the services actually need to access by visiting Zuul. All service done by spring.application.name logo,

IP addresses are different, the same spring.application.name is a service cluster. When we add a spring.application.name same node, Zuul intelligent routing through information and communication Eureka obtain new nodes, increase the response capacity of the type of service.

2.7 Spring cloud Ribbon client intelligent routing

And Spring Cloud Zuul corresponding server-side proxy, Spring Cloud Ribbon provides a client agent. In the proxy server, the client does not need to know the final which micro-service node to provide them with services, and client agent node to obtain the substance of the provision of services and select a service call. Ribbon and Zuul similar, and also through Eureka (service registry) to communicate with the client to achieve intelligent routing.

2.8 Spring cloud Sleuth distributed track

2.9 Spring cloud Zipkin call chain

2.10 Spring cloud Feign http client

Spring Cloud Feign is a declarative, template-based http client. The same can be like calling a local method that allows developers feel that it is a remote method (Feign integrated Ribbon load balancing) when using Spring Cloud Feign request remote services.

The remote services and local services do mapping

@FeignClient(name = "rabbitmq-http", url = "${SKYTRAIN_RABBITMQ_HTTP}") 
public interface TaskService {     
    @RequestMapping(value = "/api/queues", method = RequestMethod.GET)     
    public String query(@RequestHeader("Authorization") String token); 
}

To call the local service invoke remote service

@Autowired 
private TaskService taskService; 
private String queryRabbitmqStringInfo() {     
    byte[] credentials = Base64 .encodeBase64((rabbitmqHttpUserName + ":" + rabbitmqHttpPassword).getBytes(StandardCharsets.UTF_8));     
    String token = "Basic " + new String(credentials, StandardCharsets.UTF_8);     
    return taskService.query(token); 
}

2.11 Spring cloud Hystrix breaker

Third, micro-services practice

3.1 We have developed several micro service components - Application Center Management

Application of micro-management center can be registered for each service node stopping, compile, package, deploy, complete the on-line operation started.

3.2 We have developed several micro data query service components -zookeeper center

According to data query zookeeper zookeeper center address, port, zookeeper command to obtain data information.

3.3 We have developed several micro service components - micro-service health testing center

Health Center periodically check the status of each detected micro service, when the service state is found to have a micro DOWN or connection timeout alarm is triggered.

3.4 We have developed several micro service components - regular tasks ICC

// 在BeanPostProcessor子类中拦截
@Component
public class SkytrainBeanPostProcessor implements BeanPostProcessor, Ordered {
    ***
    /**
     * Bean 实例化之后进行的处理
     */
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        beanPostProcessor.postProcessAfter(bean, beanName);
        return bean;
    }
    ***
}
// 拦截后获取定时任务注解
***
public Object postProcessAfter(Object bean, String beanName) {
    Class targetClass = AopUtils.getTargetClass(bean);
    Map annotatedMethods = MethodIntrospector.selectMethods(targetClass,
            new MethodIntrospector.MetadataLookup() {
 
                public Set inspect(Method method) {
 
                    Set scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(method,
                            Scheduled.class, Schedules.class);
                    return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
                }
            });
    if (!annotatedMethods.isEmpty()) {
        String className = targetClass.getName();
        for (Map.Entry entry : annotatedMethods.entrySet()) {
            Method method = entry.getKey();
            for (Scheduled scheduled : entry.getValue()) {
                String key = className + ":" + method.getName();
                String value = scheduled.toString();
                taskInfos.put(key, value);
            }
        }
    }
    return null;
}
***
 
// 获取定时任务后注册
***
public void taskRegister() {
    String nodeInfo = ipAddress + ":" + serverPort + ":";
    try {
        /**
         * 定时任务
         */
        Map infos = taskInfos;
        for (Entry item : infos.entrySet()) {
            String taskId = nodeInfo + item.getKey();
            String taskParameter = item.getValue();
            JSONObject info = new JSONObject();
            info.put("taskId", taskId);
            info.put("taskParameter", taskParameter);
            info.put("applicationName", applicationName);
            info.put("taskType", "schedule");
            LOGGER.info(info.toString());
            zooKeeperExecutor.createZKNode(SKYTRAIN_TASK_ZKNODE_PREFIX + taskId, info.toString());
        }
    }
    catch (Exception ex) {
        LOGGER.error("", ex);
    }
}
***

3.5 micro-classification services

  • Micro Services Platform Components
  • Public service component
  • Basic service components / business service components

Figure 3.6 overall micro Services Architecture

Author: Liang Xin

Source: CreditEase Institute of Technology

Guess you like

Origin yq.aliyun.com/articles/706535