简单实验 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<ServiceInstance> 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<ServiceInstance> 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 运行结果

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值