Consul first experience in. Net Core

Source: Internet
Author: User

Brief introduction

Before reading this article I think you should have a basic or vague understanding of the microservices architecture

Consul is a service management software, it actually has many components, including service discovery configuration shared key value pair storage etc.

This paper mainly explains the discovery of Service registration service of consul and the configuration of cluster.

Resources:

79462530

Https://www.cnblogs.com/shanyou/p/6286207.html

Service discovery

Suppose there is a service a,b,c. Service a needs to invoke services B and C, in the traditional way we need to record the IP and port numbers of service B and C in service A. These configurations are generally written in places such as configuration files.

There are two obvious drawbacks to this approach: 1. If the IP of B is changed in the future, the IP configuration of all callers needs to be modified. 2. Difficult to do load balancing

and service discovery is used to solve this problem, how to solve it? Take a look at the picture below

This diagram adds a service registry module between the service consumer and the service producer, using the server ABC above for example, service B will be registered in the registry at the time of release, and the registry will record the name and IP address of service B. When service a requests service B, you only need to register the central query with the name of service B. In the case of clustering, the registry will have multiple service B. At the same time, the registry periodically checks to see if each service is properly accessible and removes inaccessible services. (Health Check)

In general, service discovery is the use of a flag to obtain a list of services, and the list of services can be changed dynamically with each service's on-line or offline

Consul Terminology and explanations

The following are some of the more frequently occurring terms in consul

    • Agent, agent is the daemon that runs on each consul cluster member node for a long time. Start with the Command Consul agent. Agent has both client and server two modes. Because each node must run the agent, all nodes are either client or server. All agents can invoke DNS or HTTP APIs and are responsible for checking and maintaining service synchronization.
    • The client runs the agent of the client mode and forwards all the RPCs to the server. The client is relatively stateless. The only thing the client does is to participate in the LAN gossip pool in the background. Consumes only a small amount of resources, a small amount of network bandwidth.
    • The server runs the server mode agent, participates in the Raft quorum, maintains the state of the cluster, responds to RPC queries, interacts with other data centers wan gossip, and forwards queries to leader or remote datacenters.
    • The definition of the Datacenter data center seems obvious, and there are some details that must be considered. For example, in EC2, are multiple availability zones considered to form a single data center? We define the data center in the same network environment-private, low latency, high bandwidth. This does not include a public Internet-based environment, but for us, multiple availability zones in the same EC2 are considered to be a data center.

    • About client and server I've been doing this for a while. In fact, the client does not store data, and the client sends a request to the client, which is forwarded to the server it binds to, meaning that the client must bind to the server. The server stores the data, and if there is only one server and a service is registered on it, the server hangs up and you restart again, then the registration information for the service is still on the server.
    • If you are running a server on one of the servers, it will have a client bound to the server by default, and the address is 127.0.0.1

Consul installation

Consul:https://www.consul.io/downloads.html

I use the WIN10 system, so download the last windows64 bit, download down there is an EXE file, casually put a folder under it can be.

Go to cmd, go to Consul's storage directory, and hit the command.

Alternatively, you can add the Consul directory path to the PATH environment variable without having to command the directory every time.

Start consul

As stated above, Consul can be started as client and server.

Server:consul Agent-server-bootstrap-expect 1-data-dir=c:\consul-node=n1-bind=192.168.3.233-ui-dir=c:\consul\ dist-client=0.0.0.0

Client:consul Agent-bootstrap-expect 1-data-dir=c:\consul-node=n1-bind=192.168.3.233-ui-dir=c:\consul\dist

Removing the -server is the client mode.

  • Consul Agent: Command to start Consul, either server or client
  • -bootstrap-expect: The expected number of server nodes, if the server node in the cluster is smaller than this data, the cluster will fail, and the server will fail, until the number of clusters to reach the corresponding number in order to take effect, if it is 1, On behalf of a server can be
  • -data-dir:data stored directory, the server will save some configuration cache information, such as the existence of this directory
  • -node: The name of the node, the urgent crowd name must be unique
  • -client: The client address representing the external burst of the server, 0.0.0.0 means I can access by: 127.0.0.1 and 192.168.3.233, not set the words default is: 127.0.0.1
  • -bind: This is the address that sets up communication between servers in the cluster and must be accessible to each other
  • -ui-dir: Set the interface of WebUI, theoretically can view any information we need through the command, but through the UI to see more intuitive
Build a cluster

I turned on two virtual machines and this machine was three machines, so I built three server nodes

Ser1:consul agent-server-bootstrap-expect=3-data-dir=c:\consul-node=node1-bind=192.168.3.233-client=0.0.0.0

Ser2:consul agent-server-bootstrap-expect=3-data-dir=c:\consul-node=node2-join=192.168.3.233-bind=192.168.3.201 -client=0.0.0.0

Ser3:consul agent-server-bootstrap-expect=3-data-dir=c:\consul-node=node3-join=192.168.3.233-bind=192.168.3.243 -client=0.0.0.0

-join: Indicates which cluster to join, Ser2 we specify to join the Ser1, when Ser1 and Ser2 formed a cluster, ser3 we can specify to join Ser1 and Ser2, Regardless of which end of the three servers were added to a cluster, eventually three servers consulted and elected a leader

Service Registration

The service can be registered through a command because it is ultimately used on the. NET core, so I paste the relevant code directly into. NET Core

 public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iapplicationlifetime applifetime) {str        ing IP = configuration["IP"];        String port = configuration["Port"];        String serviceName = "Msgservice";        String serviceId = ServiceName + Guid.NewGuid (); action<consulclientconfiguration> consulconfig = (config) + = {Config. Address = new Uri ("http://192.168.3.201:8500"); The address of the service registration, any one of the address config in the cluster.         Datacenter = "DC1";        }; using (var consulclient = new Consulclient (consulconfig)) {agentserviceregistration ASR = new Agentserv  iceregistration {address = IP, port = Convert.ToInt32 (port), ID =                    ServiceId, Name = serviceName, Check = new Agentservicecheck { Deregistercriticalserviceafter = Timespan.fromseconds (5), HTTP = $ "Http://{ip}:{port}/api/health ",//Health Check access address Interval = Timespan.fromseconds (10),//Health check interval time Timeout            = Timespan.fromseconds (5),//How long to represent timeout},}; ConsulClient.Agent.ServiceRegister (ASR).        Wait ();  }//Logoff Consul appLifeTime.ApplicationStopped.Register (() = {using (var consulclient = New Consulclient (Consulconfig)) {ConsulClient.Agent.ServiceDeregister (serviceId).  Wait ();        Remove the service from the Consul Cluster}}); if (env. Isdevelopment ()) {app.        Usedeveloperexceptionpage (); } else {app.        Usehsts (); } app.        Usehttpsredirection (); App.    Usemvc (); }

After running the program, a service is registered to the consul cluster, and any IP that accesses the cluster is preferable to the IP of the service. The code for the client query service is as follows:

 static void Main(string[] args)    {        using (var consul = new Consul.ConsulClient(c =>        {            c.Address = new Uri("http://192.168.3.233:8500"); //Consul地址        }))        {            var services = consul.Catalog.Service("MsgService").Result.Response;            foreach (var s1 in services)            {                Console.WriteLine($"ID={s1.ServiceID},Service={s1.ServiceName},Addr={s1.Address},Port={s1.ServicePort}");            }        }    }

So that our basic consul cluster can be used normally.

For consul and service discovery is still just beginning to touch. There are still a lot of problems for the time being not understood.

How do I switch to another server, such as a client-connected server suddenly hangs up? and a service downline how to notify the client to delete the cache and so on. And please enlighten us.

Consul first experience in. Net Core

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.