Spring Cloud_06_微服务间通信_03_使用“RestTemplate”对象

6.3.1 创建服务调用工程

使用IDEA创建服务调用工程:
创建服务调用工程

6.3.2 编写配置入口类文件

在入口类配置文件中添加“@EnableEurekaClient”注解:

package com.marshal.springcloud.resttemplate;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ResttemplateApplication {

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

}

6.3.3 编写控制器类

使用“Spring Cloud”内置的RestTemplate对象进行服务间通信调用:

package com.marshal.springcloud.resttemplate.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

/**
 * @Author 王毅
 * @Date 2020/9/2 11:45
 */
@Controller
public class RestTemplateController {

    @GetMapping("/getBookInfoByRestTemplate")
    @ResponseBody
    public String getBookInfoByRestTemplate(Long bookId) {

        RestTemplate restTemplate = new RestTemplate();
        String json = restTemplate.getForObject("http://localhost:9000/book/getBookInfo?bookId="
                + bookId, String.class);

        System.out.println(json);
        return json;
    }
}

注:
1:类“RestTemplate”底层使用“Apache HttpClient”组件进行HTTP传输;
2:因此种方式需要将访问IP地址和端口号均编写在代码中,不便于维护所以不推荐使用。

6.3.4 编写工程配置文件

删除原工程配置文件“application.properties”并创建编写工程新配置文件

“bootstrap.yml”:
spring:
  application:
    name: resttemplate
  cloud:
    config:
      discovery:
        enabled: true
        service-id: config
      profile: dev
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

在配置中心所访问的云Git服务添加配置文件。
在配置中心所访问的云Git服务添加配置文件
其中配置文件“resttemplate.yml”的内容为:
其中配置文件“resttemplate.yml”的内容为
配置文件“resttemplate-dev.yml”内容:
配置文件“resttemplate-dev.yml”内容
配置文件“resttemplate-prd.yml”内容:
配置文件“resttemplate-prd.yml”内容

6.3.5 启动服务进行验证

启动服务并打开浏览器输入访问地址: http://localhost:9000/resttemplate/getBookInfoByRestTemplate?bookId=3

启动服务进行验证

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值