使用RestTemplate调用SpringCloud注册中心内的服务

使用RestTemplate调用SpringCloud注册中心内的服务

本案例使用Eureka作为注册中心演示,其他注册中心调用方式一致。只需保证调用方和服务提供方必须在同一个注册中心内注册即可。

启动类上加入注解

这里演示的是Eureka的形式,其他的注册中心根据实际情况添加即可。EnableEurekaClient其实也是可以不用加的。

@SpringBootApplication
@EnableEurekaClient

配置RestTemplate

在SpringBoot启动类所在包的同级或子包内加入如下配置,如果调用的服务不是唯一的,必须加上@LoadBalanced注解

package cn.vantee.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;

/**
 * @author :rayfoo@qq.com
 * @date :Created in 2021/12/25 4:28 下午
 * @description:RestTemplatep配置类
 * @modified By:
 * @version: 1.0.0
 */
@Configuration
public class ApplicationContextConfig {

    /**
     * 如果是集群方式调用需要加上LoadBalanced 否则会502
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

使用RestTemplate调用服务

resttemplate不仅支持ip+端口的形式调用接口,还支持根据调用服务注册中心中的应用名称调用。

package cn.vantee.proxy;

import cn.vantee.entity.AjaxResult;
import cn.vantee.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.client.RestTemplate;

/**
 * @author :rayfoo@qq.com
 * @date :Created in 2021/12/25 4:28 下午
 * @description:订单模块的控制层
 * @modified By:
 * @version: 1.0.0
 */
@RestController
@RequestMapping("/order")
public class OrderProxy {

    /**
     * 支付服务的地址,支持ip+端口和服务名
     */
    public static final String PAYENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 通过RestTemplate远程调用支付服务
     * @param id
     * @return
     */
    @GetMapping("/payment/findOne/{id}")
    public AjaxResult<Payment> findPaymentById(@PathVariable("id") long id) {
        return restTemplate.getForObject(PAYENT_URL+"/payment/findOne/"+id,AjaxResult.class);
    }

}

原文地址:https://www.cnblogs.com/zhangruifeng/p/15730979.html