Spring-cloud Micro-service Road (III): Service registration and discovery of Eureka, Consul

Source: Internet
Author: User

On the road to Spring-cloud MicroServices (ii): Spring boot We showed you how to quickly build a microservices project using spring boot, which demonstrates how to use spring cloud Eureka and Spring Cloud C respectively Onsul complete the implementation of service registration and discovery.

One: Service governance

Service governance can be said to be the most core and basic module in MicroServices architecture, which is mainly used to realize the automatic registration and discovery of each micro-service instance. Why do we need such a feature, such as two microservices A and B, where a needs to call service B to complete a business need, in order to achieve high availability of service B, whether using server-side load balancing or client load balancing, you need to manually maintain service B's instance manifest. However, with the development of the business, the system functions more and more complex, the response of the micro-service is also increasing, our static configuration will become more and more difficult to maintain. And in the face of continuous development of business, our cluster size, service location, service naming are likely to change, if still manual maintenance, it is easy to cause a lot of unpredictable errors, consumes a lot of manpower.

This time the advantages of service governance is reflected in the service governance structure, there will usually be a registry, each micro-service to register their services to the registry, the host number, version number, communication protocol and other information to inform the registry, such as we have two services of a and B, when they are registered to the registration center after the completion of the The registry will appear with two services and will detect the availability of the two services through heartbeat, eliminating them if they are not available, and achieving troubleshooting. At the same time, because of the service governance framework, the invocation of the service is no longer implemented by specifying the specific instance address, but rather through the service name initiating the request invocation implementation, so the service caller needs to consult the service registry and should obtain an instance list of all the services to implement the invocation of the specific service instance. For example a service corresponding to the address is 192.168.0.1:8080, the application named Spring-cloud-providera, B service corresponding address is 192.168.0.1:8081, the application named Spring-cloud-providerb, service C SPRING-CLOUD-PROVIDERC first registers with the registry and then discovers two instances of service delivery, which are called directly through the service application name and no longer care about what IP and PORT the service is on.

Second: Use Eureka to build Service registration center

1. First, create a basic Spring Boot project and add the following dependencies to the Pom.xml:

<!--add Eureka Service Registration Dependency--
<dependency>
    <groupid>org.springframework.cloud</groupid >
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>

Add @EnableEurekaServer annotations on the application startup class to open the Service governance server implementation,

@EnableEurekaServer
@SpringBootApplication Public
class Springbootapplication {public

static void main (    String[] args) {
	springapplication.run (springbootapplication.class, args);
}
}

2, by default, the service registry will also try to register itself as a client, so we need to disable its client registration behavior, only need to add the following configuration in the Application.properties file:

#在默认设置下, the service registry will also try to register itself as a client, so we need to disable its client registration behavior,
Spring.application.name=spring-cloud-eureka
server.port=8080
#表示是否将自己注册到Eureka Server, default is True
eureka.client.register-with-eureka=false
# Indicates whether the service is retrieved from Eureka Server, which defaults to true because it is an instance of the maintenance service, does not need to retrieve the service, and is set to False
Eureka.client.fetch-registry=false
# Set the address that interacts with Eureka Server, which is dependent on the query service and the registration service. Default is Http://localhost:8761/eureka, multiple addresses can be used, separate
eureka.client.serviceurl.defaultzone=http://localhost:${ server.port}/eureka/

3, after completing the above configuration, launch the application and access http://localhost:8080 can see the Eureka Information Panel, you can see that there is no service registered to the registry.



II: Registered service provider

1. After the completion of the Service registration center, we then try to add a Spring Boot application to the Eureka service governance system. Create a new spring Boot project eureka-provider , modify the Pom.xml, and increase the dependency of the Spring Cloud Eureka module:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId> Spring-cloud-starter-eureka</artifactid>
</dependency>

2, then create the Providercontroller, add the index interface, receive the name parameter, output ' Hello ' + name + ' This is first message '

@RestController public
class Providercontroller {

    @RequestMapping (value = "/hello", method = Requestmethod.get Public
    String Index (@RequestParam (value = "name") string name) {
        return ' Hello ' + name + ', this is the first Mes Sage ";
    }
}

3. Add @EnableDiscoveryClient annotations on the main startup class to open the Discoveryclient implementation in Eureka, note: This piece can also be used @EnableEurekaClient /c10> Note, the difference between the two refer to the difference between the @EnableDiscoveryClient and @enableeurekaclient

Spring-cloud-starter-eureka and Spring-cloud-starter-consul-discovery
//Both include sub-annotations
@EnableDiscoveryClient
@SpringBootApplication Public
class Eurekaproviderapplication {public

    static void Main (string[] args) { C5/>springapplication.run (Eurekaproviderapplication.class, args);
    }
}

4, finally we need in the Application.properties configuration file, through the spring.application.name property to name the service, such as named Spring-cloud-producer, and then through Eureka.client.service-url.defaultzone property to specify the address of the service registry, which is the address we applied above:

Spring.application.name=spring-cloud-producer
server.port=8081
eureka.client.service-url.defaultzone =http://localhost:8080/eureka/

5. Next we start the Service Registry app and service registration provider application that we just started to create, and the browser input http://localhost:8080/can see that the service is already registered to the service center.

Three: Service discovery and consumption

Through the above, we have built the service registry and service registration, the service Discovery task is implemented by the Eureka client, while the consumption of the task is implemented by the Ribbon, the Ribbon is a client load balancer.

1, first, we will create the above eureka-provider into a jar package After the use of the command to start two different ports to run:

Java-jar Eureka-provider-0.0.1-snapshot.jar--server.port=8081

Java-jar Eureka-provider-0.0.1-snapshot.jar--server.port=8082

2, after the successful start, as shown in the following figure, from the Eureka information Panel we see the service of the name Spring-cloud-producer two instance units, the ports are 8081 and 8082, respectively:


3, create a Spring Boot project to implement the service consumer, named Ribbon-consumer, and introduce the following dependencies in Pom.xml, compared to the previous eureka-provider, we have added the Ribbon module dependent Spring -cloud-starter-ribbon:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId> spring-cloud-starter-eureka</artifactid>
</dependency>

<!--Add Client Load Balancer component Ribbon Ribbon invocation Mode-
<dependency>
<groupId>org.springframework.cloud</groupId>
< Artifactid>spring-cloud-starter-ribbon</artifactid>
</dependency>

4. Add @EnableDiscoveryClient annotations in the application Master startup class to have the app register as a Eureka client app while creating resttemplate Spring bean< in the class /c10> instances and enable client-side load balancing through @LoadBalanced annotations.

Enable service registration and Discovery
@EnableDiscoveryClient
//Note: @springcloudapplication annotations can be used here,
// This note contains three annotations of @enablediscoveryclient/@SpringBootApplication/@EnableCircuitBreaker
@SpringBootApplication
public class Ribbonconsumerapplication {public

static void Main (string[] args) {
	Springapplication.run (Ribbon    Consumerapplication.class, args);

/**
* Add Ribbon Client Load Balancer component
* @return resttemplate instance */
@Bean
@LoadBalan    CED
resttemplate resttemplate () {
	return new resttemplate ();
}
}

5. Create the Consumercontroller class to provide a/ribbon-consumer interface in which the/hello interfaces provided by the Spring-cloud-producer service are invoked through the resttemplate created above. It is a very important feature to see that we are visiting the service name Spring-cloud-producer instead of an address .

@RestController public
class Consumercontroller {

    @Autowired
    resttemplate resttemplate;

    @RequestMapping (value = "/ribbon-consumer", method = requestmethod.get) public
    String Index (@RequestParam (name = " MyName ") String myname) {
        //resttemplate.getforobject (" Http://spring-cloud-producer/hello?name={1} ", String.class,myname); The first form of
        writing//The following is the second way to write, pay attention to this notation, can not be written like this: Getforobject ("http://spring-cloud-producer/hello?name={ XM} ", String.class,new hashmap<> (). Put (" XM ", MyName));
        map<string,string> params = new hashmap<> ();
        Params.put ("XM", myname);
        String result = Resttemplate.getforobject ("Http://spring-cloud-producer/hello?name={xm}", string.class,params);
        return result;
    }
}

6. Register this app with the Eureka registry in the configuration file:

Spring.application.name=spring-ribbon-consumer
server.port=2222
eureka.client.service-url.defaultzone= http://localhost:8080/eureka/

7, launch the application, found that this consumer application has been successfully registered:


8. A GET request was initiated by accessing the Http://localhost:2222/ribbon-consumer?myname= test, successfully returning the Hello test, this is first message information, and the request polling was implemented. Load balancing is achieved (you can print the output statements of two providers differently, so it's more intuitive).


Four: Consul realization of Service registration and Discovery

Cond...



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.