当前位置: 首页 > news >正文

简单实验 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 {@AutowiredDiscoveryClient discoveryClient;//@Autowired//FenTest fenTest;@AutowiredRestTemplate 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 运行结果

http://www.lryc.cn/news/294447.html

相关文章:

  • 简单说说redis分布式锁
  • 什么是 Java 中的 IO 和 NIO?它们之间有什么区别?什么是 Java 中的内存管理和垃圾回收?常见的垃圾回收算法有哪些?
  • 【图论】基环树
  • 如何快速捕获和验证用户软件需求,实现快速迭代
  • 爱上算法:每日算法(24-2月4号)
  • 【Node系列】创建第一个服务器应用
  • Linux命令基础学习 (2月4日打卡
  • Python 基础知识概览
  • Adobe Camera Raw for Mac v16.1.0中文激活版
  • zabbix自定义监控项
  • 使用Pycharm在本地调用chatgpt的接口
  • HarmonyOS远程真机调试方法
  • 基于SpringBoot的后端导出Excel文件
  • 2 月 5 日算法练习- 动态规划
  • SpringBoot整合EasyCaptcha图形验证码
  • 学习数据结构和算法的第3天
  • SpringBoot实战第三天
  • mysql学习打卡day22
  • Unity | Spine动画记录
  • 【Flink】FlinkSQL实现数据从MySQL到MySQL
  • python爬虫抓取新闻并且植入自己的mysql远程数据库内
  • netty实现简单的客户端、服务端互相发消息
  • 利用jmeter完成简单的压力测试
  • 【手写数据库toadb】toadb物理存储模型,数据库物理存储原理,物理文件组织关系以及行列混合模型存储结构
  • MySQL-----DDL基础操作
  • 【MySQL】在 Centos7 环境安装 MySQL -- 详细完整教程
  • 理解React中的setState()方法
  • 数据库管理-第144期 深入使用EMCC-01(20240204)
  • flask_django_python五金电商网络营销的可视化分析研究
  • Java并发(二十三)----同步模式之保护性暂停