Upgrading MicroServices Architecture 3: Service Discovery and service invocation

Source: Internet
Author: User

A microservices architecture system, the different services will be called each other, such as an order service needs to fetch user data, you need to invoke user services, there are multiple User Service instances, Eureka load balanced to one of the service instances, and the previous chapter, We first use the Java version of the service discovery and invocation service to do examples and porting to the. NET Core version.

  Version 1.Java Service call

  1.1 Create order Service

  Create an empty Maven project as before, and transform it into a Eureka client, modify the next configuration file, the service name is UserService, the port is set to 6661

  1.2 Client load Balancing using the Ribbon

To add the ribbon dependency, the Ribbon is a client-side load-balancing component, and the service calls each other through it to load balance

 <  dependency  >  <  groupid  >  org.springframework.cloud</  GroupId  >  <  artifactid  >  spring-cloud-starter-netflix-ribbon</ artifactid  >  </ dependency  >  

Create a Ordercontroller, also create a user entity (in the actual project if there are multiple calls to the same entity can be independent of an entity module), in the startup class to create a method resttemplate () to inject resttemplate, Plus @bean configuration annotations, @LoadBalanced load Balancing annotations

@Bean @loadbalancedresttemplate resttemplate () {    returnnew  resttemplate ();}

Reference official documents: Http://cloud.spring.io/spring-cloud-static/Finchley.SR1/single/spring-cloud.html#_spring_resttemplate_ As_a_load_balancer_client

Search: Spring resttemplate as a Load Balancer Client

  

  

  1.3 Order service Call User Service

Create a service class to encapsulate calls to other services, create a UserService class, encapsulate the UserService service method, create a resttemplate variable plus @autowired annotation for automatic scan injection

 PackageCom.tz.orderservice;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.core.ParameterizedTypeReference;ImportOrg.springframework.http.HttpMethod;Importorg.springframework.http.ResponseEntity;Importorg.springframework.web.client.RestTemplate;Importjava.util.ArrayList;Importjava.util.List; @Service Public classUserService {@AutowiredPrivateresttemplate resttemplate;  PublicList<user>GetAll () {parameterizedtypereference<List<User>> Responsetype =NewParameterizedtypereference<list<user>>(){}; Responseentity<List<User>> resp = resttemplate.exchange ("Http://userservice/user/getall", Httpmethod.get,NULL, Responsetype); List<User> list =Resp.getbody (); returnlist; }    }

Create a method for obtaining user information in the order controller

@RestController @requestmapping ("/order")  Public class Ordercontroller {    @Autowired    private  userservice userservice;    @RequestMapping ("/getalluser")    public list<user> getalluser () {         return  userservice.getall ();    }}

Start Eureka Server, launch two UserService instances, start OrderService, refresh the service registry, discover that the order service OrderService has been registered successfully

  

The method of obtaining user information from the browser to access the order service can see how the user Service was successfully invoked

  

  2.. NET Core Service invocation

2.1 Create order service

Follow the methods in the previous chapter to create a. NET core microservices, Port set to 6660, create an Iuserservice interface, where asynchronous methods are used

 Public Interface iuserservice{    Task<List<User>> getAll ();    Task<string> getport ();}

2.2 Order Service call User Service

Create a UserService class that implements the Iuserservice interface to invoke the service

Reference: http://steeltoe.io/docs/steeltoe-discovery/#1 -2-6-discovering-services

Json Serialization Component: Newtonsoft.json

 Public classuserservice:iuserservice{Discoveryhttpclienthandler _handler; Private Const stringserviceurl ="Http://userservice/user";  PublicUserService (idiscoveryclient client) {_handler=Newdiscoveryhttpclienthandler (client); }     Public AsyncTask<list<user>>GetAll () {varClient =getclient (); varjson=awaitClient. Getstringasync (serviceurl+"/getall"); List<User> list= jsonconvert.deserializeobject<list<user>>(JSON); returnlist; }     Public Asynctask<string>Getport () {varClient =getclient (); return awaitClient. Getstringasync (serviceurl +"/getport"); }PrivateHttpClient getclient () {varClient =NewHttpClient (_handler,false); returnclient; }}

  

Configuring UserService Dependency Injection in the configureservices of the startup class

 Public voidconfigureservices (iservicecollection services) {//Add injection configurationServices. Addscoped<controllers.iuserservice, controllers.userservice>(); //determine if a Eureka configuration can be obtained    if(Configuration.getsection ("Eureka"). GetChildren (). Any ()) {//Add Steeltoe Service Discovery Client Service configurationServices.    Adddiscoveryclient (Configuration); } services. Addmvc (). Setcompatibilityversion (compatibilityversion.version_2_1);}

  

Create a Ordercontroller, use the Iuserservice interface to invoke, inject an instance into the constructor method

[Route ("[Controller]")][apicontroller] Public classordercontroller:controllerbase{Private ReadOnlyIuserservice UserService; //constructing methods to inject instances     PublicOrdercontroller (Iuserservice userservice) { This. UserService =UserService; } [Route ("Getalluser")] [HttpGet] Public AsyncTask<list<user>>GetAll () {List<User> list =awaitUserservice.getall (); returnlist; } [Route ("Getuserserviceport")] [HttpGet] Public Asynctask<string>Getuserserviceport () {varPort =awaitUserservice.getport (); returnPort; }}

Start the project, under Refresh Eureka Server, the OrderService instance with Port 6660 is registered to the service center

  

Enter in the browser: Http://localhost:6660/order/getuserserviceport, to call the UserService method of obtaining the port, a few more refreshes can see the port will continue to switch, indicating that the load balance has been achieved.

  

  

The. NET core version of the service call is complete.

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.