简介
spring cloud loadbalancer是spring自家推出的负载均衡器,可以平替ribbon。
spring cloud loadbalancer + RestClient
RestClient
是spring framework 6.1(对应spring boot 3.2)里内置的一个http rest api调用器。相比RestTemplate
,RestClient
的链式写法使用起来十分流畅丝滑。spring cloud loadbalancer自然也可以与RestClient/RestTemplate进行集成。
使用步骤
1、启动一个服务注册中心(兼容Eureka/Nacos/Consul/K8s等服务注册中心),此处以Eureka为例
依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
配置:
server:
port: 8761
eureka:
client:
registerWithEureka: false
fetchRegistry: false
server:
waitTimeInMsWhenSyncEmpty: 0
dashboard:
enabled: true
代码:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApp {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApp.class, args);
}
}
2、服务提供端(provider)
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置:
server:
port: 8001
spring:
application:
name: spring-httpexchange-server
cloud:
loadbalancer:
enabled: true
eureka:
client:
enabled: true
service-url:
defaultZone: http://127.0.0.1:8761/eureka
2、调用端(client)
依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置:
server:
port: 8002
spring:
application:
name: spring-httpexchange-client
cloud:
loadbalancer:
enabled: true
eureka:
client:
enabled: true
service-url:
defaultZone: http://127.0.0.1:8761/eureka
配置类代码:
@Configuration
public class HttpClientConfig {
@LoadBalanced
@Bean
RestClient.Builder restClientBuilder() {
return RestClient.builder();
}
@Bean
public HelloClient helloClient(RestClient.Builder restClientBuilder) {
return HttpServiceProxyFactory
.builder()
.exchangeAdapter(
RestClientAdapter.create(
restClientBuilder.baseUrl("http://spring-httpexchange-server").build()
)
)
.build().createClient(HelloClient.class);
}
}
client调用provider提供的远程http服务的代码无需做任何变化。
标签:spring,server,client,cloud,eureka,loadbalancer From: https://www.cnblogs.com/jiayuan2006/p/18156964