栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

架构实战篇(六):Spring Boot RestTemplate的使用

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

架构实战篇(六):Spring Boot RestTemplate的使用

三、Java 客户端

让我们先来看下项目的目录结构

目录结构

四、配置maven依赖

    4.0.0

    com.itunion
    spring-boot-resttemplate
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.1.RELEASE
    

    

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            io.springfox
            springfox-swagger2
            2.7.0
        
        
            io.springfox
            springfox-swagger-ui
            2.7.0
        
        
            org.apache.tomcat.embed
            tomcat-embed-jasper
        
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
            provided
        
    
    war

    
        1.7
    
    
        
        swagger
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                org.apache.maven.plugins
                maven-war-plugin
                2.1.1
                
                    false
                
            
            
        
    
五、编写程序入口

程序的入口基本都一样

package com.itunion;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import java.io.IOException;@SpringBootApplicationpublic class Application {    public static void main(String[] args) throws IOException {
        SpringApplication.run(Application.class, args);
    }
}
六、RestTemplate 配置

在这里我们可以设置连接的超时时间 代理 等信息

package com.itunion.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.client.ClientHttpRequestFactory;import org.springframework.http.client.SimpleClientHttpRequestFactory;import org.springframework.web.client.RestTemplate;@Configurationpublic class ApiConfig {    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {        return new RestTemplate(factory);
    }    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }
}
七、编写API 返回对象

API 请求肯定少不了返回对象,为了方便类型转换我们把User类复制了过来(实际开发中可以把api 公共的domain 等类带jar 包出来)

package com.itunion.model;import com.fasterxml.jackson.annotation.JsonIgnore;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;@ApiModel("用户")public class User {    @ApiModelProperty("编号")    private Long id;    @ApiModelProperty("用户名")    private String username;    @ApiModelProperty("姓")    private String firstName;    @ApiModelProperty("名")    private String lastName;    @ApiModelProperty("邮箱")    private String email;    @ApiModelProperty(hidden = true)// 密码不传输
    @JsonIgnore
    private String password;    @ApiModelProperty("状态")    private Integer userStatus;    // get set

    @Override
    public String toString() {        return "User{" +                "id=" + id +                ", username='" + username + ''' +                ", firstName='" + firstName + ''' +                ", lastName='" + lastName + ''' +                ", email='" + email + ''' +                ", password='" + password + ''' +                ", userStatus=" + userStatus +                '}';
    }
}

异常类

package com.itunion.model;import java.o.Serializable;public class ErrorBody implements Serializable {    private Integer code;    private String message;    private long timestamp = System.currentTimeMillis();    // get set
    @Override
    public String toString() {        return "ErrorBody{" +                "code=" + code +                ", message='" + message + ''' +                ", timestamp=" + timestamp +                '}';
    }
}
八、使用RestTemplate 远程调用

这里我们写了两个方法

  1. 当远程接口正常返回结果的时候我们会封装成User对象返回到前端

  2. 当远程调用返回 RestClientResponseException 异常的时候封装成ErrorBody对象(比如传入参数不合法等数据验证,不能返回逾期结果的时候会返回Error信息,这时候需要做处理)

package com.itunion.controller;import com.fasterxml.jackson.databind.ObjectMapper;import com.itunion.model.ErrorBody;import com.itunion.model.User;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import org.springframework.web.client.HttpClientErrorException;import org.springframework.web.client.RestTemplate;import java.io.IOException;@Api(value = "用户", description = "用户")@RequestMapping("/user")@RestControllerpublic class UserController {    @Autowired
    private RestTemplate restTemplate;    @ApiOperation(value = "调用远程用户服务", notes = "调用远程用户服务")    @RequestMapping(value = "/info/{userId}", method = RequestMethod.GET)    public User info(@PathVariable("userId") String userId) throws IOException {
        String apiURL = "http://localhost:8081/swagger/user/info/" + userId;        return restTemplate.getForObject(apiURL, User.class);
    }    @ExceptionHandler(RestClientResponseException.class)    public ErrorBody exceptionHandler(HttpClientErrorException e) throws IOException {        return new ObjectMapper().readValue(e.getResponseBodyAsString(), ErrorBody.class);
    }
}
九、修改端口

为了同时启动两个服务端口肯定是不能一样的了

server.port=8082

server.context-path=/

swagger.enable=true
十、启动程序和验证

服务端成功启动


服务端成功启动

客户端成功启动


客户端成功启动

访问客户端页面
http://localhost:8082/swagger-ui.html

测试正确的请求参数


设置参数

验证正确结果

测试错误的请求参数

设置参数

验证异常结果



作者:IT实战联盟咖啡
链接:https://www.jianshu.com/p/c96049624891


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号