所有的资料都来源官网,首先先打开Spring的官网https://spring.io/,然后进入Projects分类,进入SpringCloud的官网https://spring.io/projects/spring-cloud,再点击Spring Cloud Alibaba,选择learn,选择版本进入Reference Doc. 然后选择Spring Cloud Alibaba Nacos Discovery.
下面附上直达目录:https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html#_spring_cloud_alibaba_nacos_discovery
下面开始演示构建基于Nacos注册中心的83服务消费者案例
1、构建项目modul,cloudalibaba-nacos-consumer-order83
2、添加pom依赖,因为上一篇已经在父pom中引入了,所以这篇不再添加父pom依赖
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
3、构建application.yml文件
server:
port: 83
spring:
application:
name: nacos-consumer-order
cloud:
nacos:
discovery:
server-addr: localhost:8848
#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
nacos-user-service: http://nacos-provider-payment
4、构建主启动类
@SpringBootApplication
@Slf4j
public class NacosConsumerOrderMain83 {
public static void main(String[] args) {
SpringApplication.run(NacosConsumerOrderMain83.class, args);
}
}
5、因为nacos默认整合了ribbon,所以可以实现负载均衡,能使用restTemplate,所以构建restTemplate配置
package com.king.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* created by king on 2020/5/8 4:03 下午
*/
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
6、构建controller业务类,进行调用服务提供者
package com.king.springcloud.controller;
import lombok.extern.slf4j.Slf4j;
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;
import javax.annotation.Resource;
/**
* created by king on 2020/5/8 4:07 下午
*/
@RestController
@Slf4j
public class OrderController {
@Resource
private RestTemplate restTemplate;
@Value("${service-url.nacos-user-service}")
private String serverUrl;
@GetMapping("consumer/nacos/payment/{id}")
public String getNacosPayment(@PathVariable("id") Integer id){
return restTemplate.getForObject(serverUrl+"/nacos/payment/"+id,String.class);
}
}
7、查看Nacos控制台,观察服务消费者服务是否注册进注册中心
8、调用服务消费者接口,http://localhost:83/consumer/nacos/payment/{id},查看结果是9002和9001端口号轮询出现,说明实现了负载均衡的轮询功能,达到了通过微服务名的微服务调用