Spring Cloud中实现负载均衡,可以使用Ribbon和Feign两种方式。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
spring:
application:
name: my-service
cloud:
ribbon:
listOfServers: server1:port, server2:port, ...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
@EnableFeignClients
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@FeignClient("my-service")
public interface MyServiceClient {
@GetMapping("/api/my-service")
String getData();
}
通过以上的方式,Spring Cloud可以实现负载均衡,将请求分发到多个服务实例上。