前面我们已经将客户端作为提供者和消费者注册到注册中心,下面我们进行调用。
我们采用RestTemplate方式调用。
1.首先我们在提供者端建立一个Controller
package com.nacos.nacostest;
import com.sun.org.apache.xml.internal.utils.URI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
@RestController
@RefreshScope
public class Controller {
@GetMapping("/hello")
public String getHello() {
return "hello,1......";
}
}
2.1在消费端创建一个RestTemplateConfig类,初始化 RestTemplate。
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
2.2在消费端创建一个Controller,引入RestTemplate
package com.nacos.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class Controller {
@Autowired
RestTemplate restTemplate;
@GetMapping("/hello")
public String getHello(){
final String forObject = restTemplate.getForObject("http://127.0.0.1:8080/hello", String.class);
return forObject;
}
}
RestTemplate的API可以自己去看,很简单。
我们用的getForObject()方法第一个参数是URL,第二个参数是返回值类型。
启动起来访问http://127.0.0.1:8081/hello
我们看到可以成功调用。
负载均衡策略
Nacos中集成了Ribbon,当我们使用RestTemplate+Ribbon进行负载均衡时,不需要额外引入依赖。
首先我们再创建一个客户端作为提供者
为了体现出区别,将方法返回值改变一下:
package com.nacos.nacostest2;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class Controller {
@GetMapping("/hello")
public String getHello() {
return "hello,2......";
}
}
配置和第一个提供者完全一样,只是改变端口
服务的名字spring.application.name=alibaba-nacos-config-client是相同的,我们将两个服务起来,发现注册中心的一个提供者下出现了两个实例。
接下来我们需要再消费端初始化RestTemplate时,添加注解:@LoadBalanced
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced// 开启负载均衡 Ribbon, 发送的请求都会被Ribbon拦截。必须使用应用名代替ip,否则报错
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
因为出现了两个provider,端口不同,所以进行调用的时候,不能使用ip,必须使用应用名代替:
package com.nacos.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class Controller {
@Autowired
RestTemplate restTemplate;
@GetMapping("/hello")
public String getHello(){
final String forObject = restTemplate.getForObject("http://alibaba-nacos-config-client/hello", String.class);
return forObject;
}
}
我们访问 http://127.0.0.1:8081/hello 会发现对两个provider轮询调用。
注:也可以改变配置,对多个provider进行随机等方式调用,可自行学习。