Spring Eureka Cloud's.

A micro-Services Overview

1. What is Micro Services

 Simply put, a micro-service design on the system architecture, its purpose is to split the original independent systems into multiple small service, these small services run in separate processes, based on the service between RPC communication collaboration. Each split into a small service revolves around a particular system or some higher degree of coupling business functions to build, and each service maintains its own data storage (designated priorities, each micro-services are has its own database instance), business development, automated test cases and independent deployment mechanism.

2. Characteristics of Micro services

  • Service components of : a plurality of separate system is split into small service.
  • Services to business segments : micro-services business should be to divide, rather than the ability to divide or other factors (such as before to do a project caching capabilities built directly into a micro-service component).
  • Intelligent endpoint and dumb pipes : between RPC service by way of calls, often using two service calls ways:
    first: RESTfl API using HTTP or lightweight messaging protocol, to achieve information transmission and service calls trigger.
    The second: lightweight by passing messages on the message bus, a similar number of asynchronous switching RabbitMQ provide reliable middleware.
  • Decentralization process : different micro-service components can choose different technical solutions can even select a different language. Only by achieving transparent technology platform in order to better take advantage of different languages for different business processing capabilities, in order to create more powerful large-scale systems.
  • Decentralized management data : the use of distributed databases, different micro-service components have their own separate database instance. Although the decentralized data management can make data management more detailed oriented, by adopting a more suitable technology allows data storage and achieve optimal performance. However, since the data is stored in the different database instance, data consistency problem has become one of the micro-service architecture to be solved.
  • Infrastructure automation : automatic test (every shot in the arm before deployment, to get confidence in the software running as much as possible), automated deployment (liberation boring tedious repetitive operations and configuration management for multi-environment) and so on.
  • Fault-tolerant design : the micro-service architecture, rapid detection of fault sources and possible automatic recovery service is designed and must be taken into account.
  • Evolution of design : no need to start off the service thin split addition, it can with the development of business systems, the pressure does not change the service or stable modules do split merge action.

2. The micro-defect services

  1. Operation and maintenance costs increase. This is inevitable, it had only a single stand-alone operation and maintenance of the system, now or in a few tens of micro-management services.
  2. Consistency of the interface. A modified micro-services interface, you need the caller B, C services at the same time to make changes. Unless the development process in strict compliance with the principle of opening and closing (in the context of the development of this agile flow, almost hard to do).
  3. The complexity of distributed. Network latency, distributed transactions, asynchronous messages.

Tips : distributed transaction itself difficult to achieve very large, so the micro-service architecture, we emphasize the call "no transaction" between each service, and for data consistency, data processing requirements only state in the final It can be the same; errors if found in the process, for processing by the compensation mechanism, so that the data can be erroneous to a final consistency.

Two, Spring Cloud Profile

 Spring Cloud is a service-based micro-architecture development tools Spring Boot achieve. Configuration management, service management, circuit breakers, intelligent routing it comes to micro-services architecture, the micro broker, a control bus, a global lock, decision-making campaign, distributed and clustered session state management and other operations provides a simple way of development.

 Spring Cloud appears, can be said that technical support services for the huge support micro-architectures and powerful. It is a solution to a comprehensive framework to address the implementation of micro-services architecture, it integrates many frames are widely practiced and proven components as the basis for implementation, but also created some very good edge components in the system basis. For example Dubbo and Spring Cloud difference: the use of Dubbo development process, a distributed configuration center (Baidu's Disconf, Netflix's Archaius, 360 of QConf, Taobao Diamond, etc.), link tracking (Jingdong Hydra, Twitter's Zipkin, etc.) ... a series of required components, I have to go to a third-party integration, but also consider the version compatibility issues. The Spring Cloud is a micro-service solutions, "family bucket", I need almost all micro-service component, where I can find the "original components": the center of a distributed configuration (Config), link tracking (Sleuth), batch tasks (task), and it can be perfectly compatible.

Three, Eureka Profile

 Service management system can be said to be the most micro-service architecture core and foundation module, which is mainly used to automate various micro-service registration and discovery instance. Service governance system in the three core roles: service registry, service providers and service consumers. The Eureka Server assumed the service registry Spring Cloud's. Next stroked a stroke Eureka Server service governance process were:

  1. Registration service : "Service Provider" at startup will be requested by sending REST registers itself to the Eureka Server, while some bring their own metadata information services (hostName and the like). After REST Eureka Server receives this request, the metadata information is stored in a two-layer structure in the Map, key wherein the first layer is a service name, key of the second layer is a specific instance name services.
  2. Synchronization Services : As registered as a service (Eureka Server availability Scene) service registry with each other, when the service provider transmits a service registration request to the registry, it will forward the request to another register is connected to the center of the cluster, in order to achieve synchronization between the service registry. , Two service providers can obtain service information to the service by these two registration centers Renyiyitai by service synchronization.
  3. Service Renewal : After completion of registration services, "service provider" will continue to maintain a heartbeat to tell Eureka Sever "I'm alive" to prevent "reject task" Eureka Server instance of the service excluded from the list of services .
  4. Consumer Services : When we start "service consumer", it sends a request to the REST service registry, to obtain a list of services registered above. For performance reasons, Eureka Serer maintains a read-only list of service back to the client, while the cache list will be updated once every 30 seconds.
  5. Service call : "service consumer" After obtaining the list of services, you can get the specific instance name to provide services and metadata information that instance through the service name. Details of these services because there are instances, so the client can decide which specific instance of call in the Ribbon will default polling of call, in order to achieve load balancing client according to their needs.
  6. Service off the assembly line : a service instance for normal operation shut down, it will trigger a request to the REST service offline Eureka Server, told the service registry: "I want off the assembly line." After the server receives the request, the service status to offline (DOWN), and to spread out the offline event.
  7. Excluding failure : Sometimes, our service instance does not necessarily normal offline, possibly due to memory overflow, network failures and other reasons that the service does not work, the service center has not received registration request "service off the assembly line" of. In order to eliminate, Eureka Server creates an instance of a scheduled task from the list of services will not provide these services at boot time, the default time to time (the default is 60 seconds) when the current list of Super (default is 90 seconds) is not renewed about removed out of service.
  8. Self-protection : Eureka Server during operation, will be counted whether the proportion of heart failure less than 85% within 15 minutes, if the situation appears less than (it is easy to meet when stand-alone debugging on actual production environment is usually due to lead to network instability), Eureka Server instance of the current registration information will be protected, so that these instances do not expire, protect the registration information as possible.

Four, Eureka combat

SpringBoot version number: 2.1.6.RELEASE
SpringCloud version: Greenwich.RELEASE

1. Service Registry

  • pom.xml
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
  • application.yml
server:
  port: 1111

eureka:
  instance:
    hostname: localhost
    prefer-ip-address: true
  client:
    # 表示不向注册中心注册自己
    register-with-eureka: false
    # 注册中心的职责是维护实例,不需要去检索服务
    fetch-registry: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
   server:
     # 是否要打开自我保护机制
     enable-self-preservation: true

eureka configuration items are mainly three: instance, client, server. "Instance" of the maintenance service instance information including hostname, port Examples of such metadata describing characteristics of the information; "client" is mainly registration service configuration data, such as time-out, the cache service time; "server" is a registered service Center-specific configuration, configuration-related Eureka Server configuration items, such as whether to open above to protect themselves.

  • Application.java
//启动一个服务注册中心
@EnableEurekaServer
@SpringBootApplication
public class Application {

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

At this point, we have a Eureka Server - a service registry build better.

2. Service Provider

  • pom.xml
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
  • application.yml
server:
  port: 2222

spring:
  application:
    name: cloud-eureka-client

eureka:
  # 服务注册相关的配置信息
  client:
    service-url:
      defaultZone: http://localhost:1111/eureka/
  instance:
    # 是否优先使用IP地址作为主机名的标识
    prefer-ip-address: true

In this way, one of our Eureka Client to be registered on the Eureka Server. Next, let us try to find our service information DiscoveryClient:

// 自动化配置, 创建 DiscoveryClient 接口针对 Eureka 客户端的 EurekaDiscoveryClient 实例
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application .class, args);
    }
}
@RestController
public class HelloController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DiscoveryClient discoveryClient;
    @Value("${spring.application.name}")
    private String serviceId;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
        ServiceInstance instance = instances.get(0);
        logger.info("/hello, host:" + instance.getHost() + ", serviceId:" + instance.getServiceId());
        return "Hello World";
    }
}

3. Consumer Services

With the service registry and service providers, we try to use the service once RestTemplate call it!

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/ribbon-consumer")
    public String helloConsumer() {
        // 这里访问的是服务名,而不是一个具体的地址(为了实现负载均衡策略),在服务治理框架中,这是一个非常重要的特性。
        ResponseEntity<String> result = restTemplate.getForEntity("http://cloud-eureka-client/hello", String.class);
        return result.getBody();
    }
}

Five additional

  • By default, Eureka Jersey and used as a communication protocol XStream JSON mating between the Server and the Client.
  • YAML meant in fact: Yet Another Markup Language - is still a markup language (that look a bit like laughing).
  • In SpringBoot property profile, to generate random values ​​by using the int $ {random} configuration, long string or string values.
  • In Spring Boot, the configuration of a multi file names is required to meet application- {profile} .properties format, wherein {profile} identification corresponding to your environment. Start by --spring.profiles.active = test parameters to specify the active environment variable.

Demo source code: https://github.com/JMCuixy/spring-cloud-demo

Content Reference "Spring Cloud service combat micro"

Guess you like

Origin www.cnblogs.com/jmcui/p/11093602.html