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

了解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)

发布了34 篇原创文章 · 获赞 5 · 访问量 1717

猜你喜欢

转载自blog.csdn.net/zhengliangs/article/details/102900663
今日推荐