Spring Cloud Alibaba 使用restTemplate进行服务调用

在前面的学习我们成功的实现了服务注册和服务发现 现在我们需要实现服务调用

编写服务接口

在生产者编写一个简单的接口功能 这里我们实现一个返回端口的接口

@RestController
public class ProviderController {
    @Value("${server.port}")
    private String port;
    @GetMapping("/getPort")
    public String getPort(){
        return this.port;
    }
}

分别运行端口为8081 8082的两个服务
在nacos查看

在消费者调用服务功能

调用功能我们通过resttemplate来实现
要想使用该类需要我们去编写配置类

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

编写消费者类

package com.jie.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@RestController
public class ConsumerController {
    //通过discoveryClient连接nacos
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/instances")
    public List<ServiceInstance> instances(){
        List<ServiceInstance> instances = this.discoveryClient.getInstances("provider");
        return instances;
    }
    @GetMapping("/getPort")
    public String getPort(){
        //获取实例集合
        List<ServiceInstance> list = this.discoveryClient.getInstances("provider");
        //我们随机拿取其中的一个实例
        int index = ThreadLocalRandom.current().nextInt(list.size());
        ServiceInstance instance = list.get(index);
        //主机名加端口即为URI 如localhost:8080 加上/getPort 就是完整路径url
        String url = instance.getUri() + "/getPort";
        //调用 第二个参数为调用接口的返回类型
        return "调用了 "+restTemplate.getForObject(url,String.class);
    }
}

访问消费者接口 多次访问可以出现两个生产者服务都被消费的结果

posted @ 2021-10-04 20:00  一个经常掉线的人  阅读(245)  评论(0编辑  收藏  举报