一、默认负载均衡策略
Spring Cloud LoadBalancer 默认的负载均衡策略是轮询。
轮询效果示例
我们需要示例一个请求分发到不同的模块上,所以我们需要创建多模块项目。
新建 Spring Boot (3.0.2)的 Maven 项目(JDK 17)(父模块),添加依赖 Spring Web、Nacos Service Discovery、OpenFeign、Cloud LoadBalancer,然后删除 src 与 HELP.md 文档,修改 pom.xml (如删除模块运行)
创建子模块,然后在子模块的 pom.xml 中配置父类,再删除父 pom.xml 包含的声明,最后在父模块中配置子类声明。此时就可以在子模块的配置文件中配置配置中心。
我们先在子模块写一个服务UserController。
package org.example.provider.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private ServletWebServerApplicationContext context;
@RequestMapping("/getname")
public String getName(@RequestParam("id") Integer id) {
return "Provider-name-" + id +
" | port: " + context.getWebServer().getPort();
}
}
由于Loadbalancer默认是轮询的所以我们创建两个实例运行。
接着我们用同样的方式新建consumer子模块,然后在运行类中添加 OpenFeign 的注解(开启OpenFeign),再写声明服务(Service)与调用服务(Controller),然后我们就可以访问对应的服务,可以看到它的轮询效果。
package org.example.consumer.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Service
@FeignClient("loadbalancer-service")
public interface UserService {
@RequestMapping("/user/getname")
String getName(@RequestParam("id") Integer id);
}
package org.example.consumer.controller;
import org.example.consumer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CallController {
@Autowired
private UserService userService;
@RequestMapping("/getname")
public String getName(@Reque