负载均衡API测试

1.引入负载均衡依赖(services模块)

html 复制代码
<!--负载均衡-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

2,测试类

java 复制代码
package com.order;

import com.cx.order.OrderMainApplication;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

/**
 * @author Jiang
 * @date 2025/11/15
 */
@SpringBootTest(classes = {OrderMainApplication.class})
public class OrderApplicationTest {

    @Resource
    LoadBalancerClient loadBalancerClient;

    @Test
    public void test() {
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        System.out.println("choose.getHost()+choose.getPort() = " + choose.getHost() + ":" + choose.getPort());
        choose = loadBalancerClient.choose("service-product");
        System.out.println("choose.getHost()+choose.getPort() = " + choose.getHost() + ":" + choose.getPort());
        choose = loadBalancerClient.choose("service-product");
        System.out.println("choose.getHost()+choose.getPort() = " + choose.getHost() + ":" + choose.getPort());
        choose = loadBalancerClient.choose("service-product");
        System.out.println("choose.getHost()+choose.getPort() = " + choose.getHost() + ":" + choose.getPort());
        choose = loadBalancerClient.choose("service-product");
        System.out.println("choose.getHost()+choose.getPort() = " + choose.getHost() + ":" + choose.getPort());
    }

}

3.使用负载均衡的方式进行远程调用

java 复制代码
package com.cx.order.service.impl;

import com.cx.Order;
import com.cx.Product;
import com.cx.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author Jiang
 * @date 2025/11/7
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Override
    public Order createOrder(Long userId, Long productId) {
        Product product = getProductFromRemote(productId);

        Order order = new Order();
        order.setId(1L);
        // 总金额=价格*数量
        BigDecimal price = product.getPrice();//价格
        int num = product.getNum();//数量
        order.setTotalAmount(price.multiply(new BigDecimal(num)));//总价
        order.setUserId(userId);
        order.setNickName("张三");
        order.setAddress("火星");
        // 远程查询商品列表
        order.setProductList(Arrays.asList(product));
        return order;
    }

    //远程调用获取商品信息
    public Product getProductFromRemote(Long productId) {
        //1、获取到商品服务所在的所有机器IP+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        //远程URL
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/productId/" + productId;
        //2、给远程发送请求
        return restTemplate.getForObject(url, Product.class);
    }

    //负载均衡
    public Product getProductFromRemoteWithLoadBalance(Long productId) {
        //1、获取到商品服务所在的所有机器IP+port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //远程URL
        String url = "http://" + choose.getHost() + ":" + choose.getPort() + "/productId/" + productId;
        //2、给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

}

**总结:**discoveryClient返回的是服务列表,loadBalancerClient返回的是单个实例它会根据配置的负载均衡算法从可用实例中挑选一个合适的实例以达到负载均衡的目的

相关推荐
马士兵教育2 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
snow@li2 小时前
Java:理解 Gradle / 后端项目的管家 / 打包SpringBoot 应用 / 完成编译、下载依赖、运行测试、打包 JAR/WAR / 速查表
java
云烟成雨TD3 小时前
Spring AI 1.x 系列【57】动态工具发现:Tool Search Tool
java·人工智能·spring
zfoo-framework3 小时前
[修改代码使用]codex官方app中使用中转(不需要cc-switch) 1.config.toml 2.sk方式登录
java
逍遥德3 小时前
MQTT教程详解-05.SpringBoot集成mqtt client 性能分析
java·spring boot·spring·mt
云烟成雨TD3 小时前
Spring AI 1.x 系列【54】Retry 机制分析
java·人工智能·spring
weixin_523185323 小时前
Collections.unmodifiableMap详解:真的不可修改吗?
java·linux·前端
点燃大海3 小时前
SpringAI构建智能体
java·spring boot·spring·springai智能体
xier_ran3 小时前
【infra之路】02_RadixAttention与KV_Cache管理
java·spring boot·spring
黑马师兄4 小时前
RAG混合检索深度解析:让AI真正找到你要的内容
java·人工智能·ai·agent·rag·ai-native