Spring下使用RestTemplate实现单点远程调用

Spring下使用RestTemplate实现单点远程调用

使用的原理是httpclient
官网地址:
http://hc.apache.org/httpclient-3.x/
但是已经停止服务了。。。
Spring下使用参考文档:
链接:https://pan.baidu.com/s/1xZU5EhZg6OecKX7KbI8xnA
提取码:ewcc
在这里插入图片描述
调用方法说明:
在这里插入图片描述

1.案例基础

基于实现的项目代码:
SpringBoot下使用Swagger2开发API文档
因此实现的基础是上面这个项目已经运行

具体实现的结果是远程调用该项目的controller的getById方法,并将结果返回到前端页面

2.开发远程调用

2.1 pom依赖

	   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2.2 application.properties配置

配置端口,防止端口冲突

#端口指定
server.port=9999

2.3 DemoApplication

因为使用RestTemplate,而默认容器中没有,需要向容器中先注入一个

@SpringBootApplication
public class DemoApplication {

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


    //向容器中注入一个RestTemplate
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

2.4 两个项目共同返回前端数据封装类R

//用于返回数据的封装
@Data
public class R {
    private Integer code;
    private Boolean status;
    private Map<String,Object> data =new HashMap<>();
    private String message;


    //私有构造方法
    private R(){}

    //链式编程
    public static R ok(){
        R r = new R();
        r.setStatus(true);
        r.setCode(200);
        return  r;
    }
    public static R error(String message,Integer code){
        R r =new R();
        r.setStatus(false);
        r.setCode(code);
        r.setMessage(message);
        return r;
    }

    //数据封装
    public R put(String key,Object value){
        this.data.put(key,value);
        return this;
    }


}

2.5 controller开发

@RestController
public class DemoController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/demo1")
    public String demo1(){

        R r = restTemplate.getForObject("http://localhost:8089/stu/student/4", R.class);
        return String.valueOf(r.getData().get("data"));
    }
}

或者用返回的ResponseEntity(包含了数据返回页面的响应头响应体等信息)

@RestController
public class DemoController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/demo1")
    public String demo1(){

//        R r = restTemplate.getForObject("http://localhost:8089/stu/student/4", R.class);
        ResponseEntity<R> forEntity = restTemplate.getForEntity("http://localhost:8089/stu/student/4", R.class);
        return String.valueOf(forEntity.getBody().getData().get("data"));
    }
}

2.6 返回结果

在这里插入图片描述

3. 缺点

只能点对点的调用,当使用分布式微服务时不能很好适用

4.解决方案

使用注册中心

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值