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可以實現負載均衡,將請求分發到多個服務實例上。