Mind mapping

Star: github.com/yehongzhi/l…

One, foreword

With the maintenance of Eurka2.0 discontinued, a new generation of open source registries for microservices is being considered as an alternative to Eureka.

As far as I know, Consul and Nacos are two popular alternatives. This article will introduce the simple use of these two registries in microservices and hopefully help readers.

Second, the role of the registry

The registry acts as an “address book of services” in the microservices architecture. When a service is started, the service needs to be registered with the registry, which holds the mapping between the service name and the service address of all the services. When service A wants to invoke service D, it gets the service address of service D from the registry and invokes it.

Let me draw a picture to make it a little clearer. It looks something like this:

One might ask, why not invoke service D directly from the service address instead of getting the service address of service D from the registry. Because a service is supported by more than one machine, for example, service D may be supported by three machines in real production, exposing only one service name to the outside world, thus avoiding the dead IP address of the service in the code (written in the configuration file), which is very convenient when the service is extended.

In addition to service registrations, the registry also provides service subscriptions, which are pushed to each service in real time as new services are registered.

There is also service health monitoring, which allows you to see the status of services in the registry in the administration interface.

Third, Consul

Developed by the Go language, it supports distributed and highly available service publishing and service registration in multiple DCS, uses the RALT algorithm to ensure service consistency, and supports health check.

3.1 Installation (Windows 10)

Step 1: Download the installation package from the official website.

Step 2 Decompress the ZIP package and configure environment variables.

Step 3: Rap Basketball CTRL +R, CMD, enter consul:

There you have it, super simple! Enter y-version to verify the consul version number:

Step 4: Start. Enter the command consul.exe agent-dev local boot:

Step 5: Enter http://localhost:8500 in the browser to open the management page.

3.2 Service Registration

The next step is to create two services, order and user, to register with Consul. Let me demonstrate one of these user services.

Create a SpringBoot project with Maven configuration as follows:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1. RELEASE</version>
</parent>
<groupId>io.github.yehongzhi</groupId>
<artifactId>user</artifactId>
<version>0.0.1 - the SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency><! -- Health monitoring package -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency><! -- Spring-cloud-Consul jar package -->
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        <version>2.0.1. RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.SR1</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Copy the code

Then the yML configuration file looks like this:

server:
  port: 8601
spring:
  application:
    name: user
  cloud:
    consul:
      port: 8500
      host: 127.0. 01.
      discovery:
        service-name: user
        instance-id: ${spring.application.name}:${spring.cloud.consul.host}:${server.port}
        health-check-path: /actuator/health
        health-check-interval: 10s
        prefer-ip-address: true
        heartbeat:
          enabled: true
Copy the code

Add a comment to the startup class to enable service registration:

@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
    public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); }}Copy the code

Finally, I can start the project. Here I start two users, the port number is 8601,8602 respectively:

3.3 Service Invocation

Create an order entry similar to the user configuration and register the service into Consul.

To demonstrate how to invoke the user service with the order service, first define the user interface:

@RestController
@RequestMapping("/mall/user")
public class UserController {
    @RequestMapping("/list")
    public Map<String, Object> list(a) throws Exception {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("Miss Number One"."Michelle Reis");
        userMap.put("Miss 2"."Wing Yee Yuen");
        userMap.put("Miss 3"."Zhang");
        userMap.put("Miss 4".Maggie Cheung);
        returnuserMap; }}Copy the code

Then call the user service from the Order service, using the RestTemplate method:

@RestController
@RequestMapping("/mall/order")
public class OrderController {

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/callUser")
    public String list(a) throws Exception {
        // Obtain the user service instance from the registry, including the service IP address, port number, and other information
        ServiceInstance instance = loadBalancerClient.choose("user");
        // Invoke the user service
        String userList = new RestTemplate().getForObject(instance.getUri().toString() + "/mall/user/list", String.class);
        return "Call" + instance.getServiceId() + "Service, port number:" + instance.getPort() + ", return result:"+ userList; }}Copy the code

Start two user services, one order service, invoke the interface of order, and see the result:

Load balancing is polling access by default, so user services 8601 and 8602 are called alternately.

So much for getting started, consul can also be used as a configuration hub in addition to service governance, for those interested in exploring consul for themselves. I use dev mode here, which is equivalent to single machine mode. It is only used for learning, but it must be cluster mode in actual production. If I have time later, I will write a special article to demonstrate the establishment of Consul cluster.

Here’s another registry, Nacos by Ali.

Four, Nacos

The following introduction is from the official website:

Nacos is dedicated to helping you discover, configure, and manage microservices. Nacos provides an easy-to-use feature set that helps you quickly implement dynamic service discovery, service configuration, service metadata, and traffic management.

Nacos helps you build, deliver, and manage microservices platforms more agile and easily. Nacos is the service infrastructure for building modern “service” centric application architectures (e.g., microservices paradigm, cloud native paradigm).

In summary, Nacos provides three functions: service discovery and management, dynamic configuration services, and dynamic DNS services.

I’m going to focus on service discovery, which is the function of a registry.

4.1 installation

First, download the installation package. The current stable version is 1.3.1. It is recommended to use it on Linux or Mac system.

CMD file to start the startup.

In fact, an error will be reported.

This error, I noticed on Github, is just a parameter.

However, some people say that the later version has been optimized without this error. Anyway, if encountered, add a parameter to start it. The full command is startup. cd-m standalone.

If you do not want to add parameters to the start command, you can configure mysql(version required: 5.6.5+), initialize mysql database, database initialization file: nacos-mysql.sql.

Modify the conf/application. The properties file configuration:

db.num=1
db.url.0=JDBC :mysql:// mysql: characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTime zone=UTC
db.user=account
db.password=password
Copy the code

If the startup succeeds, the following message is displayed in the CLI:

After the success of the start, in your browser open http://localhost:8848/nacos/, enter the management interface. The default account password is nacOS.

4.2 Service Registration

Again, create two services to register with NACOS, adding the suffix “nacos” to the project name to distinguish it from the previous one. First add the Maven configuration as follows:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0. 5.RELEASE</version> <relativePath/> <! -- lookup parent from repository --> </parent> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR1</version> <type>pom</type> <scope>import</scope>
    	</dependency>
    	<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>0.22..RELEASE</version>
            <type>pom</type>
            <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency><! GroupId >org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><! Dependence - SpringCloud nacos service discovery - > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>Copy the code

The start class is annotated @enableDiscoveryClient.

@SpringBootApplication
@EnableDiscoveryClient
public class UsernacosApplication {
    public static void main(String[] args) { SpringApplication.run(UsernacosApplication.class, args); }}Copy the code

Configuration file application.properties file plus configuration.

server.port=8070
spring.application.name=usernacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
Copy the code

Create a UserController interface for other microservice calls.

@RestController
@RequestMapping("/mall/userNacos")
public class UserController {
    @RequestMapping("/list")
    public Map<String, Object> list(a) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("Jay Chou"."Love before THE Dawn.");
        userMap.put(Jacky Cheung."I just want to be with you forever.");
        userMap.put("Andy Lau"."Water of Ecstasy");
        userMap.put(Eason Chan."King of Karaoke.");
        userMap.put("Morning"."Even if there were no fairy tales.");
        returnuserMap; }}Copy the code

Run the main method of the startup class, and you can see that the registry has an additional usernacOS service.

4.3 Service Invocation

With the same configuration and method, create an OrdernacOS service as the consumer.

@RestController
@RequestMapping("/mall/orderNacos")
public class OrderController {
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/callUser")
    public String callUser(a) {
        ServiceInstance instance = loadBalancerClient.choose("usernacos");
        String url = instance.getUri().toString() + "/mall/userNacos/list";
        RestTemplate restTemplate = new RestTemplate();
        // Invoke the usernacOS service
        String result = restTemplate.getForObject(url, String.class);
        return "Call" + instance.getServiceId() + "Service, port number:" + instance.getPort() + ", return result:"+ result; }}Copy the code

Start two usernacOS services and one OrdernacOS service.

Test interface at http://localhost:8170/mall/orderNacos/callUser, the order can smoothly calls to the user, the default load balancing strategy is also a polling mechanism.

Five, the summary

Nacos is widely used in China. I think there are several reasons:

  • Because Ali is currently using Nacos and has experienced verification of high concurrency scenarios such as Singles’ Day and various seckill events.
  • The document is quite complete, the key is Chinese documents, for many domestic English level is not very good developers look really cool.
  • Many programmers from Ali have brought ali’s technology to various small and medium-sized Internet companies, and the general technology selection must be familiar with them.
  • The management interface is available in Chinese and English for easy operation.
  • There is also a more active community, many problems can be found online solutions.

This article focuses on two popular implementations of SpringCloud microservices for registries, and will continue to cover other components of microservices.

The code for all of the above examples is uploaded to Github:

Github.com/yehongzhi/m…

Please give me a thumbs-up if you think it is useful. Your thumbs-up is the biggest motivation for my creation

Refusing to be a salt fish, I’m a programmer trying to be remembered. See you next time!!

Ability is limited, if there is any mistake or improper place, please criticize and correct, study together!