Nacos服务消费者注册和负载均衡
服务消费者
上篇文章我们成功配置了Nacos服务提供者的注册,那么这节课我们将配置服务消费者,同时来验证Nacos自带负载均衡。
具体配置
新建Module
pom
<?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.czing</groupId>
<artifactId>springnacos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.czing</groupId>
<artifactId>nacos_client_9001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>nacos_client_9001</name>
<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>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.czing</groupId>
<artifactId>alibaba_common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
注意父项目要添加标记
<modules>
<module>nacos_server_8089</module>
<module>nacos_server_8091</module>
<module>nacos-client-9001</module>
</modules>
yml
server:
port: 9001
spring:
application:
name: nacos-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-provider #要调用的提供者服务名
主启动
package com.czing.nacosclient9001;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosClient9001Application {
public static void main(String[] args) {
SpringApplication.run(NacosClient9001Application.class, args);
}
@Bean
@LoadBalanced
//启动加载负载均衡
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
测试
注意:要先启动Nacos,然后再来启动服务
远程调用与Ribbon
大家现在肯定很疑惑,这个服务消费者不是要调用具体服务吗?但是现在仅仅是创建出来了,和上篇文章创建的服务者也没有多大的区别啊?这具体怎么用那?
是这样的,我们现在想要让这个服务的消费者去调用服务提供者,我们就需要通过Ribbon来进行调用,那么首先我们先来了解Ribbon。
什么是Ribbon
它是一个基于HTTP和TCP客户端负载均衡器。它虽然只是一个工具类库,它却是每一个微服务的基础设施。因为实际上,对于服务间调用、API网关请求转发都需要经过Ribbon负载均衡来实现。总体来说,Ribbon的主要作用是:从注册服务器端拿到对应服务列表后以负载均衡的方式访问对应服务。
要注意的是Nacos已经整合了Ribbon,所以我们想要使用只需要导入Spring Cloud Alibaba Nacos的依赖就可以直接使用了。
具体使用
现在如果我们需要远程访问那么可以使用RestTemplate,其中getForObject是最常用方法,同时还要在服务消费者中配置RestTemplate:
启动类加RestTemplate
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
Controller具体调用的时候restTemplate.getForObject
package com.czing.nacosclient9001.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.czing.alibaba_common.util.JsonResult;
import com.czing.nacosclient9001.handler.CustomerHandlerBlock;
import com.czing.nacosclient9001.handler.FallBackHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/12 19:37
*/
@RestController
public class NacosClientDemo {
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.nacos-user-service}")
private String serviceURL;
@GetMapping(value = "/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallbackClass = FallBackHandler.class,fallback = "fallBackException",
blockHandlerClass = CustomerHandlerBlock.class,blockHandler = "handlerBlockException"
)//exceptionsToIgnore = {NullPointerException.class} 过滤的异常类型
public JsonResult getNacosClient(@PathVariable Long id){
if(id<=3){
return restTemplate.getForObject(serviceURL+"/czingTest/getData/"+id, JsonResult.class);
}else {
throw new NullPointerException("空指针异常");
}
}
}
第一个参数url表示被调用的目标Rest接口位置
1. url的第一部分是在Nacos中注册的服务提供者名称,如果多个服务提供者注册相同名称,Ribbon会自动寻找其中一个服务提供者,并且调用接口方法。这个就是负载均衡功能。
2. url后半部是控制器的请求路径。
第二个参数是返回值类型
- JavaBean类型或者JavaBean数组类型,如果控制器返回的是List集合,需要使用数组类型接收。
第三个参数是可变参数
- 是传递给url的动态参数,使用参数时候需要在url上需要使用{1}、{2}、{3}进行参数占位,这样传递的参数就会自动替换占位符。
验证Nacos自带负载均衡
我们现在知道了如果我们想要让服务消费者nacos-consumer调用服务提供者nacos_server_8091或者8089,那么必然要使用负载均衡Ribbon和远程调用RestTemplate,所以我们要做的第一件事情就是先让8091或者8089服务对外提供接口,用于访问,
package com.czing.nacos_server_8091.controller;
import com.czing.alibaba_common.util.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/17 17:29
*/
@RestController
@RequestMapping(value = "/czingTest")
public class DataController {
@Value("${server.port}")
private String serverPort;
public static HashMap<Long,String> hashMap = new HashMap<>();
static {
hashMap.put(1l,"鼠标");
hashMap.put(2l,"键盘");
hashMap.put(3l,"手机");
}
@GetMapping(value = "/getData/{id}")
public JsonResult<String> getData(@PathVariable Long id){
JsonResult<String> stringJsonResult = new JsonResult<>(200, "serverPort:" + serverPort + hashMap.get(id));
return stringJsonResult;
}
}
接下来我们就需要通过服务消费9001者来访问8091或者8089,但是在这之前,我们先在nacos-consumer-9001模块中的yml文件里添加一句话
server:
port: 9001
spring:
application:
name: nacos-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-provider
因为我们要远程调用,所以我们还需要在启动类上配置restTemplate
package com.czing.nacosclient9001;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosClient9001Application {
public static void main(String[] args) {
SpringApplication.run(NacosClient9001Application.class, args);
}
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
配置好之后,我们就可以在9001的消费者上来通过Ribbon来自动的负载均衡调用8089或者8091的服务提供者了
package com.czing.nacosclient9001.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.czing.alibaba_common.util.JsonResult;
import com.czing.nacosclient9001.handler.CustomerHandlerBlock;
import com.czing.nacosclient9001.handler.FallBackHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @Description TODO
* @Author wangchengzhi
* @Date 2023/9/12 19:37
*/
@RestController
public class NacosClientDemo {
@Autowired
private RestTemplate restTemplate;
@Value("${service-url.nacos-user-service}")
private String serviceURL;
@GetMapping(value = "/consumer/fallback/{id}")
@SentinelResource(value = "fallback",fallbackClass = FallBackHandler.class,fallback = "fallBackException",
blockHandlerClass = CustomerHandlerBlock.class,blockHandler = "handlerBlockException"
)//exceptionsToIgnore = {NullPointerException.class} 过滤的异常类型
public JsonResult getNacosClient(@PathVariable Long id){
if(id<=3){
return restTemplate.getForObject(serviceURL+"/czingTest/getData/"+id, JsonResult.class);
}else {
throw new NullPointerException("空指针异常");
}
}
}
测试结果:
访问:http://localhost:9001/consumer/fallback/1
结果:{"code":200,"data":"serverPort:8091/8089鼠标"}
总结:因为Nacos中本身就集成了Ribbon所以它本身就自带负载均衡