Spring Cloud services Discovery service provider and service consumer

Source: Internet
Author: User
Tags log4j
Spring Cloud services Discovery service provider and service consumer

1. Service Providers

2. Service Providers

3. Start run

4. Comprehensive 1. Service Provider

According to the Eureka Registry of service registration described in the previous section, this section describes service providers and service consumers, first creating a new project named Microservice-provider-user, where the Pom.xml file is as follows:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:s
        chemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <parent> <artifactId>micorservice-study</artifactId> <groupId>cn.com</groupId> <vers ion>1.0-snapshot</version> </parent> <modelVersion>4.0.0</modelVersion> <artifa Ctid>microservice:: Provider:: User</artifactid> <packaging>jar</packaging> <name>mi
        Croservice:: Provider:: User</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <depen Dencies> <dependency> <groupId>org.springframework.boot</groupId> ; Artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <depe Ndency> <groupId>org.springframework.cloud</groupId> <artifactid>spring-cloud
 -starter-eureka</artifactid> </dependency> </dependencies> </project>

Providerapplication is:

Package cn.com.provider;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * Created by Xiaxuan on 17/2/26.
 */
@SpringBootApplication
@EnableDiscoveryClient public
class Providerapplication {public

    static void Main (string[] args) {
        springapplication.run (providerapplication.class, args);
    }
}

Entity class User:

Package cn.com.provider.domain;

Import Lombok. Allargsconstructor;
Import Lombok. Data;
Import Lombok. Noargsconstructor;

/**
 * Created by Xiaxuan on 17/2/26.
 * *
@Data
@AllArgsConstructor @NoArgsConstructor public
class User {

    private Long ID;

    Private String username;

    Private Integer age;
}

Provides a service that provides a simple access to the user object, with the following code:
UserService:

Package cn.com.provider.service;

Import Cn.com.provider.domain.User;
Import Org.springframework.stereotype.Service;

Import Java.util.HashMap;
Import Java.util.Map;

/**
 * Created by Xiaxuan on 17/2/26.
 * *
@Service public
class UserService {

    private static Map<long, user> users = new hashmap<> (); c10/>static {
        users.put (1L, New User (1L, "Xiaxuan",));
        Users.put (2L, New User (2L, "Bingwen",);
    }

    Public User Finduserbyid (Long ID) {return
        users.get (ID);
    }
}

Provide controller as Usercontroller, code as follows:

Package cn.com.provider.controllers;
Import Cn.com.provider.domain.User;
Import Cn.com.provider.service.UserService;
Import Org.apache.log4j.BasicConfigurator;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.web.bind.annotation.GetMapping;
Import org.springframework.web.bind.annotation.PathVariable;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RestController;
 /** * Created by Xiaxuan on 17/2/26. * * @RestController @RequestMapping ("/user") public class Usercontroller {private static final Logger Logger = Logger

    Factory.getlogger (Usercontroller.class);

    @Autowired private UserService UserService;
    /** * The current diagram is simple, with the default configuration of the */static {basicconfigurator.configure (); @GetMapping ("/{id}") Private user FindByID (@PathVariable Long ID) {User user = Userservice.finduserbyiD (ID);
        Logger.info ("Get user with User ID {}, details are {}", id, user);
    return user;
 }
}

Start class Providerapplication:

Package cn.com.provider;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * Created by Xiaxuan on 17/2/26.
 */
@SpringBootApplication
@EnableDiscoveryClient public
class Providerapplication {public

    static void Main (string[] args) {
        springapplication.run (providerapplication.class, args);
    }
}

Start class with annotation @enablediscoveryclient, turn on service discovery capability.

The configuration file is:

Server:
  port:8011
Spring:
  application:
    name:microservice-provider-user

Eureka:
  Client:
    serviceurl:
      defaultzone:http://eureka:8000/eureka/
  instance:
    preferipaddress:true

Marked application name, running port, registry address, specifically no longer detailed. 2. Service Providers

Create a new module again, named Microservice-consumer-user, and the pom file is no longer posted as the consumer provider above.
Start class Consumerapplication:

Package Cn.com.consumer;

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
Import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
Import org.springframework.cloud.client.loadbalancer.LoadBalanced;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.web.client.RestTemplate;

/**
 * Created by Xiaxuan on 17/2/26.
 * *
@SpringBootApplication
@EnableDiscoveryClient public
class Consumerapplication {

    @Bean
    @LoadBalanced public
    resttemplate resttemplate () {return
        new resttemplate ();
    }

    public static void Main (string[] args) {
        springapplication.run (consumerapplication.class, args);
    }

Also, add @enablediscoveryclient, turn on service discovery, and provide a resttemplate bean, because in spring cloud calls between services are implemented through rest. Wait to use Resttemplate to invoke the service provided by the service provider, in which there is an annotation @loadbalanced, which is used to open load balancing, using the Ribbon technology, which is put behind.

The entity class is no longer posted, where the service Consumerservice is:

Package cn.com.consumer.services;

Import Cn.com.consumer.domain.User;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import org.springframework.web.client.RestTemplate;

/**
 * Created by Xiaxuan on 17/2/26.
 * *
@Service public
class Consumerservice

    {@Autowired
    private resttemplate resttemplate;

    Public User FindByID (Long ID) {return
        resttemplate.getforobject ("http://MICROSERVICE-PROVIDER-USER/user/" + ID, User.class);
    }

In the above, we call the address of the service provider not localhost:8011, but microservice-provider-user, This is because we have opened the service discovery can be directly through the service name to invoke the service, without the need to write IP port, the advantage is that if the service provider is a cluster mode, there is no need to invoke the IP and port mode, but also to achieve load balancing capabilities.

Controller for Consumercontroller:

Package cn.com.consumer.controllers;
Import Cn.com.consumer.domain.User;
Import Cn.com.consumer.services.ConsumerService;
Import Org.apache.log4j.BasicConfigurator;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.web.bind.annotation.GetMapping;
Import org.springframework.web.bind.annotation.PathVariable;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RestController;
 /** * Created by Xiaxuan on 17/2/26. * * @RestController @RequestMapping ("/consumer") public class Consumercontroller {private static final Logger Logger

    = Loggerfactory.getlogger (Consumercontroller.class);

    @Autowired private Consumerservice Consumerservice;
    /** * uses the default configuration */static {basicconfigurator.configure (); @GetMapping ("/{id}") Public User FindByID (@PathVariable Long ID) {User user = ConsuMerservice.findbyid (ID);
        Logger.info ("Get user ID is {}, user is {}", id, user);
    return user;
 }
}

Relatively simple, is simply to obtain the user Service. 3. Start Run

Starting a run requires three modules, respectively:

Microservice-eureka Registration Center

Microservice-provider-user Service Provider

Microservice-consumer-user Service Consumer

Sequentially start the above three services in order, enter http://eureka:8000on the browser, as shown below:


The above two services are registered.

Now enter on the browser:HTTP://LOCALHOST:8012/CONSUMER/1, as follows:

The call succeeded. 4. On the comprehensive

We again through the service registration and consumption, in fact, the internal or the use of ribbon related technology, this put to the back and fegin together.

The call between spring cloud services is done through rest, which is nearly as efficient as using RPC, followed by how Dubbo and Dubbox are combined.

The next issue is about how Eureka is called and how it is invoked between service providers and service consumer clusters.

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.