远程调用使用Ribbon,要注意的是Nacos已经整合了Ribbon,同时Nacos自带负载均衡,所以我们想要使用只需要导入Spring Cloud Alibaba Nacos的依赖就可以直接使用了。
什么是Ribbon 它是一个基于HTTP和TCP客户端负载均衡器。它虽然只是一个工具类库,它却是每一个微服务的基础设施。因为实际上,对于服务间调用、API网关请求转发都需要经过Ribbon负载均衡来实现。总体来说,Ribbon的主要作用是:从注册服务器端拿到对应服务列表后以负载均衡的方式访问对应服务。
创建消费者项目pom.xml
4.0.0 com.jiny MySpringCloudAlibaba 0.0.1-SNAPSHOT com.jiny cloudalibaba-consumer-8083 0.0.1-SNAPSHOT cloudalibaba-consumer-8083 Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
application.yml
# nacos 服务地址
server:
port: 8083
spring:
application:
name: nacos-consumer
cloud:
discovery:
server-addr: 127.0.0.1:8848
management:
endpoint:
web:
exposure:
include:'*'
# 主要永远远程调用可配置化
service-url:
nacos-user-service: http://nacos-provider
添加restTemplate 组件
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
启动类添加
@EnableDiscoveryClient
调用程序
package com.jiny.cloudalibabaconsumer8083.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@EnableDiscoveryClient
public class DemoController {
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.nacos-user-service}")
private String serverURL;
@GetMapping(value = "consumer/nacos")
public String getDiscovery(){
System.err.println(serverURL);
return restTemplate.getForObject(serverURL+"/getServerPort",String.class);
}
}



