Upgrade micro Services Architecture 3: service discovery and service call each other

Original link: http://www.cnblogs.com/townsend/p/9531882.html

  The system architecture of a micro-services, different services are calls to each other, such as a data line service requires the user to take, you need to call the service user, the service instance when there are multiple users, wherein the Eureka will load balancing to a service instance , and the last chapter, we first found by the Java version of the service and service calls to do examples and ported to .net core version.

  Version 1.Java service call

  1.1 Creating Service Order

  Like the previous create an empty Maven project, and transformed into a Eureka client, under the modified configuration file, the service name userservice, the port is set to 6661

  1.2 Ribbon client load balancing to do

  Add dependence of ribbon, ribbon is a client load balancing component, calling each other through it to the load balancing service  

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

  Create a OrderController, likewise create a User entity (if the actual project with multiple invocations of the same entity may be an entity independent module), create a method restTemplate () in the class to start injecting restTemplate, and add annotations to configure @Bean , @LoadBalanced load balancing comment  

@Bean
@LoadBalanced
Template Residual rest template () {
    return new RestTemplate();
}

  Reference Document official website: http://cloud.spring.io/spring-cloud-static/Finchley.SR1/single/spring-cloud.html#_spring_resttemplate_as_a_load_balancer_client

  搜索:Spring RestTemplate as a Load Balancer Client

  

  

  1.3 Orders service call customer service

  Service to create a class to encapsulate calls to other services, to create here a UserService class, package userservice service approach, create a restTemplate variable plus @Autowired annotations to automatically scan injection  

package com.tz.orderservice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private Rest Template rest template;

    public List<User> getAll() {
        ParameterizedTypeReference<List<User>> responseType = new ParameterizedTypeReference<List<User>>(){};
        ResponseEntity<List<User>> resp = restTemplate.exchange("http://userservice/user/getall",
                HttpMethod.GET, null, responseType);
        List<User> list = resp.getBody();
        return list;
    }    
}

   Create a method to obtain user information in order Controller

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

    @Autowired
    private UserService userService;

    @RequestMapping("/getalluser")
    public List<User> getAllUser(){
        return userService.getAll();
    }
}

 

  Start Eureka Server, start two userservice instance, start orderservice, refresh the service registration center, we found that the order has been successfully registered service orderservice

  

  The method of obtaining user information browser to access the service order, you can see the success of the method call customer service

  

  2. .net core version of the service call

   2.1 Creating Service Order

   Create a method in accordance with the last chapter of a .net Core micro service, the port is set to 6660, created a IUserService interface, asynchronous method used here   

public  interface IUserService
{
    Task<List<User>> getAll() ;

    Task<string> getPort();
}

 

   2.2 Orders service call customer service

  UserService create a class that implements the interface to invoke the service IUserService

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

  Json serialization component: Newtonsoft.Json  

public class UserService : IUserService
{
    DiscoveryHttpClientHandler _handler;
    private const string serviceUrl = "http://userservice/user";
    public UserService(IDiscoveryClient client)
    {
        _handler = new DiscoveryHttpClientHandler(client);
    }
    public async Task<List<User>> getAll()
    {
        var client = GetClient();
        var json= await client.GetStringAsync(serviceUrl+"/getall");
        List<User> list= JsonConvert.DeserializeObject<List<User>>(json);
        return list;
    }

    public async Task<string> getPort()
    {
        var client = GetClient();
        return await client.GetStringAsync(serviceUrl + "/getport");
    }
private HttpClient GetClient()
    {
        var client = new HttpClient(_handler, false);
        return client;
    }
}

 

  

  在Startup类的ConfigureServices中配置UserService的依赖注入

public void ConfigureServices(IServiceCollection services)
{
    //添加注入配置
    services.AddScoped<Controllers.IUserService, Controllers.UserService>();
    //判断是否能获取Eureka配置
    if (Configuration.GetSection("eureka").GetChildren().Any())
    {
        //添加Steeltoe服务发现客户端服务配置
        services.AddDiscoveryClient(Configuration);
    }
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

  

  创建一个OrderController,使用IUserService接口来调用,在构造方法中注入实例  

[Route("[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
    private readonly IUserService userService;
    //构造方法来注入实例
    public OrderController(IUserService userService)
    {
        this.userService = userService;
    }

    [Route("getalluser")]
    [HttpGet]
    public async Task<List<User>> getAll()
    {
        List<User> list = await userService.getAll();
        return list;
    }

    [Route("getuserserviceport")]
    [HttpGet]
    public async Task<string> getUserServicePort()
    {
        var port = await userService.getPort();
        return port;
    }

}

 

 

  启动项目,在刷新下Eureka Server,端口为6660的orderservice实例就注册到了服务中心

  

  在浏览器中输入:http://localhost:6660/order/getuserserviceport,来调用userservice的获取端口的方法,多刷新几次就可以看到端口会不断的切换,说明已经实现了负载均衡。

  

  

  .net core版的服务调用完成。

转载于:https://www.cnblogs.com/townsend/p/9531882.html

Guess you like

Origin blog.csdn.net/weixin_30654419/article/details/94785515