SpringCloud入门(二):Restful - RestTemplate(Greenwich.SR2)

本文介绍Spring Cloud中RestTemplate的基本概念与使用方法,包括其作为HTTP客户端工具类的功能,以及如何在微服务架构中实现服务间的调用。通过实例演示了在微服务环境中配置与使用RestTemplate的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

了解RestTemplate之前,我们首先了解SpringCloud中服务间两种restful调用方式

  • RestTemplate
  • Feign

本文主要学习RestTemplate在微服务中实现服务之间的调用方式。

1.RestTemplate是什么?

RestTemplate是Spring对Http客户端进行封装的一个模板工具类,对常用的Http客户端例如:HttpClient、OKHttp、JDK原生的URLConnection(默认的)都支持。

2.RestTemplate能做什么?

基于Restful风格可以对远程服务基于http协议进行调用

3.RestTemplate的使用

本文继续使用上一章【服务的注册与发现Eureka(Greenwich.SR2)】的案例来学习

在microservice-provider中新增getProductMsg接口

/**
 * @author hero良
 * @className HelloController
 * @description TODO
 * @date 2019/9/10
 */
@Slf4j
@RestController
@RequestMapping("/appController")
public class AppController {

    @GetMapping("/getProductMsg")
    public String getProductMsg(){
        return "this is app product msg";
    }

创建服务消费者microservice-ribbon
pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

启动类

@SpringBootApplication
public class RibbonController{

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

}

RestTemplate配置类

@Configuration
public class RestTemplateConfiguration {

    /**
     * @description
     * @author hero良
     * @param
     * @date 2019/9/16 15:22
     * @return
     */
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

controller

/**
 * @author hero良
 * @classname RibbonController 
 * @description TODO
 * @date 2019/9/16 15:29
 */
@RestControllerublic class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getProductMsg")
    public String getProductMsg(){
        return ribbonService.getProductMsg();
    }

可以看到正确返回了结果,如果使用httpcliect等,还需要进行大量的封装
在这里插入图片描述
SpringCloud入门(三):服务消费者RestTemplate+Ribbon(Greenwich.SR2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值