Alibaba Nacos实现微服务远程调用

1. 概述

Nacos用于发现、配置和管理微服务,提供一组简单易用的特性集,可以快速实现动态服务发现、服务配置、服务元数据及流量管理,Nacos实现服务远程调用,常用的方法是RestTemplate结合@LoadBalanced和Feign
版本说明
2021.x 分支对应的是 Spring Cloud 2021 与 Spring Boot 2.6.x,最低支持 JDK 1.8
2020.0 分支对应的是 Spring Cloud 2020 与 Spring Boot 2.4.x,最低支持 JDK 1.8
2.2.x 分支对应的是 Spring Cloud Hoxton 与 Spring Boot 2.2.x,最低支持 JDK 1.8
更多版本说明请参阅官网
特别说明:需要提前安装好nacos服务器

2. 服务生产端实现

2.1. 引入核心依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-actuatorartifactId>
    dependency>
dependencies>

2.2. application.yml文件

server:
  port: 8100
spring:
  application:
    name: alibaba-service-provider
  cloud:
    nacos:
      discovery:
        server-addr: XX.XX.XX.XX:8848
        enabled: true
      username: nacos
      password: nacos
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

2.3. 主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}

2.4. 生产端controller

@RestController
@RequestMapping("/service")
public class ServiceProviderController {

    private static final Logger logger = LoggerFactory.getLogger(ServiceProducerController.class);

    @GetMapping("/getServiceInfo")
    private String getServiceInfo() {
        logger.info("远程接口调用提供方,当前时间为:{}", LocalDateTime.now());
        return "This is service provider,now is:" + LocalDateTime.now();
    }
}

3. 使用RestTemplate实现远程调用

3.1. 引入核心依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-actuatorartifactId>
    dependency>
dependencies>

3.2. application.yml文件

server:
  port: 8101
spring:
  application:
    name: alibaba-ribbon-consumer
  cloud:
    nacos:
      discovery:
        server-addr: xx.xx.xx.xx:8848
        fail-fast: true
      username: nacos
      password: nacos

management:
  endpoints:
    web:
      exposure:
        include: '*'

3.3. 主启动类

@SpringBootApplication
@EnableDiscoveryClient
public class RibbonConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(RibbonConsumerApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

3.4. 消费端controller

@RestController
@RequestMapping("/ribbon")
public class RibbonConsumerController {

    private static final Logger logger = LoggerFactory.getLogger(RibbonConsumerController.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/getServiceInfoForUrl")
    public String getServiceInfoForUrl() {
        List<ServiceInstance> instances = discoveryClient.getInstances("alibaba-service-provider");
        int index = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);
        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
        logger.info("从nacos中获取到的微服务地址为:", url);
        return restTemplate.getForObject("http://" + url + "/service/getServiceInfo", String.class);
    }
}

3.5. 验证RestTemplate调用

在浏览器输入http://localhost:8101/ribbon/getServiceInfoForUrl
restTemplate调用

4. 实现RestTemplate服务调用负载均衡

4.1. 引入核心依赖

<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>

注意:新版本中必须要引入spring-cloud-starter-loadbalancer依赖,否则会报java.net.UnknownHostException异常

4.2. 添加@LoadBalanced注解

在主启动类中的restTemplate()方法上添加@LoadBalanced注解

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}

4.3. 负载均衡调用方法

@GetMapping("/getServiceInfo")
public String getServiceInfo() {
    return restTemplate.getForObject("http://alibaba-service-provider/service/getServiceInfo", String.class);
}

4.4. 验证负载均衡调用

在浏览器输入地址http://localhost:8101/ribbon/getServiceInfo
负载均衡调用

5. 使用openfeign实现远程调用

5.1. 引入核心依赖

新建一个springboot项目,引入核心依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-openfeignartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-loadbalancerartifactId>
    dependency>
dependencies>

5.2. application.yml文件

server:
  port: 8102
spring:
  application:
    name: alibaba-openfeign-consumer
  cloud:
    nacos:
      discovery:
        server-addr: xx.xx.xx.xx:8848
        fail-fast: true
      username: nacos
      password: nacos

management:
  endpoints:
    web:
      exposure:
        include: '*'
logging:
  level:
    com.xlhj.cloud.alibaba.service.ProviderService: debug

5.3. openfeign配置文件

@Configuration
public class OpenFeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

配置日志等级

5.4. 容错处理类

public class ProviderServiceFallback implements ProviderService {

    @Override
    public String getServiceInfo() {
        return "get service info fallback!";
    }
}

5.5. Feign调用接口

@FeignClient(value = "alibaba-service-provider", fallback = ProviderServiceFallback.class, configuration = OpenFeignConfig.class)
public interface ProviderService {

    @GetMapping(value = "/service/getServiceInfo")
    String getServiceInfo();
}

5.6. Feign调用controller

@RestController
@RequestMapping("/openfeign")
public class OpenFeignConsumerController {

    private static final Logger logger = LoggerFactory.getLogger(OpenFeignConsumerApplication.class);

    @Autowired
    private ProviderService providerService;

    @GetMapping("/getServiceInfo")
    public String getServiceInfo() {
        String serviceInfo = providerService.getServiceInfo();
        logger.info("openfeign调用远程接口返回为:{}", serviceInfo);
        return serviceInfo;
    }
}

5.7. 验证OpenFeign调用

在浏览器输入http://localhost:8102/openfeign/getServiceInfo
openfeign调用

你可能感兴趣的:(SpringCloud,Alibaba,nacos,feign,restTemplate)