SpringCloud注册中心(Nacos,Ribbon)
在Spring Cloud中使用Nacos作为服务注册中心,并配合Ribbon实现客户端负载均衡的示例代码如下:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Cloud Alibaba Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Spring Cloud LoadBalancer -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
</dependencies>
- 在
application.yml
或application.properties
中配置Nacos服务器地址:
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
- 启用服务注册和发现:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(NacosRibbonApplication.class, args);
}
}
- 使用RestTemplate结合Ribbon实现客户端负载均衡调用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping("/consumer")
public String consumer() {
return restTemplate.getForObject("http://service-provider/provider", String.class);
}
}
在上述代码中,@EnableDiscoveryClient
注解使得应用成为Nacos的服务消费者,@LoadBalanced
注解开启RestTemplate的负载均衡功能。当你调用/consumer
接口时,Ribbon会根据从Nacos获取的服务列表进行负载均衡,并发送请求到后端的服务提供者。
评论已关闭