一 API Gateway
在 Spring Cloud API Gateway 中,通過使用 lb://
前綴可以實現基于服務名的負載均衡路由。以下是具體的配置和使用方法:
1.?配置服務注冊與發現
確保你的服務已經注冊到服務注冊中心(如 Nacos 或 Eureka)。API Gateway 會通過服務注冊中心動態獲取服務實例列表。
2.?配置 API Gateway 的路由規則
在 API Gateway 的配置文件中,使用 lb://
前綴指定服務名,Spring Cloud LoadBalancer 會自動解析服務名并選擇合適的服務實例。
示例配置:
yaml
spring:cloud:gateway:routes:- id: user-service-routeuri: lb://user-servicepredicates:- Path=/user/**filters:- StripPrefix=1
-
uri: lb://user-service
:表示使用負載均衡的方式訪問服務名為user-service
的實例。 -
predicates
:定義路由匹配規則,例如Path=/user/**
表示匹配路徑以/user/
開頭的請求。 -
filters
:可以添加過濾器,例如StripPrefix=1
用于去除請求路徑中的前綴。
3.?啟用負載均衡功能
確保在項目中引入了 spring-cloud-starter-loadbalancer
依賴:
xml
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
4.?動態服務發現
如果希望 API Gateway 自動從服務注冊中心動態創建路由規則,可以啟用 discovery.locator.enabled
:
yaml
spring:cloud:gateway:discovery:locator:enabled: true
這樣,API Gateway 會根據服務注冊中心中的服務列表動態生成路由規則。
二 OpenFeign? (name="serviceName")
OpenFeign
是聲明式服務調用工具,通過接口和注解簡化了服務間調用。
配置步驟:
-
添加依賴:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
啟用 Feign 客戶端:
@SpringBootApplication @EnableFeignClients public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);} }
-
定義 Feign 客戶端接口:
注意:這里只用配置服務名,不能給定url屬性(配置url屬性后不再使用服務發現和負載均衡)。@FeignClient("service-name") public interface ServiceClient {@GetMapping("/endpoint")String callService(); }
-
調用服務:
@Service public class ServiceConsumer {@Autowiredprivate ServiceClient serviceClient;public void consumeService() {String result = serviceClient.callService();System.out.println(result);} }
三 RestTemplate/WebClient + @LoadBalanced
1.?使用?RestTemplate
?+?@LoadBalanced
通過 RestTemplate
結合 @LoadBalanced
注解,可以實現基于服務名的負載均衡調用。
配置步驟:
-
添加依賴:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
-
配置
RestTemplate
:@Bean @LoadBalanced public RestTemplate restTemplate() {return new RestTemplate(); }
-
調用服務:
String result = restTemplate.getForObject("http://service-name/endpoint", String.class);
2.?使用?WebClient
?+?@LoadBalanced
WebClient
是響應式編程的 HTTP 客戶端,支持異步調用,也可以結合 @LoadBalanced
實現服務名調用。
配置步驟:
-
添加依賴:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
-
配置
WebClient
:@Bean @LoadBalanced public WebClient.Builder loadBalancedWebClientBuilder() {return WebClient.builder(); }
-
調用服務:
WebClient webClient = loadBalancedWebClientBuilder.build(); String result = webClient.get().uri("http://service-name/endpoint").retrieve().bodyToMono(String.class).block();