简单实验 java spring cloud 自定义负载均衡

1.概要

1.1 说明

这个是在前一个测试上的修改,所以这里只体现修改的内容。前一个测试的地址:检查实验 spring cloud nacos nacos-server-2.3.0-CSDN博客

1.2 记忆要点

1.2.1 引入对象

@Autowired
DiscoveryClient discoveryClient;

1.2.2 获取服务实例 

List serviceInstances = discoveryClient.getInstances("server3");
int index = new Random().nextInt(serviceInstances.size());
ServiceInstance serviceInstance = serviceInstances.get(index);

1.2.3 利用服务实例调用函数 

String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/fun";

2.代码变更

package com.xjc.springcloundtest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;

@RestController
public class TestController2 {

    @Autowired
    DiscoveryClient discoveryClient;
    //@Autowired
    //FenTest fenTest;
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/fun2")
    public String fun2(){

        List serviceInstances = discoveryClient.getInstances("server3");
        int index = new Random().nextInt(serviceInstances.size());
        ServiceInstance serviceInstance = serviceInstances.get(index);
        //String url = "http://localhost:8080/fun";
        //String url = "http://server3/fun";
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/fun";
        //String ret = fenTest.fun();
        String ret = restTemplate.getForObject(url,String.class);
        return "函数2"+ret;
    }
}

3 运行结果

简单实验 java spring cloud 自定义负载均衡_第1张图片

你可能感兴趣的:(spring,cloud,java,spring,cloud,开发语言)