远程调用使用Ribbon,要注意的是Nacos已经整合了Ribbon,同时Nacos自带负载均衡,所以我们想要使用只需要导入Spring Cloud Alibaba Nacos的依赖就可以直接使用了。
什么是Ribbon
? 它是一个基于HTTP和TCP客户端负载均衡器。它虽然只是一个工具类库,它却是每一个微服务的基础设施。因为实际上,对于服务间调用、API网关请求转发都需要经过Ribbon负载均衡来实现。总体来说,Ribbon的主要作用是:从注册服务器端拿到对应服务列表后以负载均衡的方式访问对应服务。
创建消费者项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.jiny</groupId>
<artifactId>MySpringCloudAlibaba</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jiny</groupId>
<artifactId>cloudalibaba-consumer-8083</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cloudalibaba-consumer-8083</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
</project>
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);
}
}
|