# RestClient **Repository Path**: shellay/rest-client ## Basic Information - **Project Name**: RestClient - **Description**: 适用于集成模块间通信,对RestTemplate做了接口级的封装,简化api调用,每个api封装成一个Service方法。 - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-03-30 - **Last Updated**: 2022-07-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: HttpRequest, RestTemplate, integration ## README # RestClient #### 介绍 RestClient是一个基于RestTemplate封装的一个API调用的调用通信模块,使API调用不再麻烦,并且易于维护和扩展。 #### 软件架构 模块设计的基本思想是,调用API就像调用本地Service方法一样,把每个API封闭成Service的方法。一个API主要包含URL、Request、Response、Headers、Authorization几部分,在Service中把通用部分抽象,在实际中,大多情况下只需要注意Request和Response部分。 #### 安装教程 1. Clone当前代码或是依赖Jar。 2. 把`com.yy.technical`加入到当前Project的扫描路径中。 3. API的Service需要实现抽象类"AbstractInteService"。 #### 使用说明 + 基本功能 > 1. 根据API文档,定义好Service方法及Request和Response。 > 2. Service实现类继承`AbstractInteService`. > 3. 构建一个`HttpRequestWrapper`,并调用`exchange`方法。 - Example: ```java @Service public class SmsServiceImpl extends AbstractInteService implements SmsService { @Override public SmsResponse send(final SmsRequest request) { String uri = "spring.api.uri.sms.notice";//指定uri的配置key HttpRequestWrapper wrapper = HttpRequestWrapper.createPost(uri,"sms",request,SmsResponse.class); //sms表示api的Host类型,默认key:spring.api.host.XXXX return exchange(wrapper); } } ``` + 扩展功能 1. Request初始化 > - 实现抽象类`AbstractHttpRequestInitializer`,`initializeHttpHeaders`方法可自定义请求头内容。`support`方法表示该类针对哪些`HttpRequestWrapper`有效。 > - 使用 @Order,定义顺序,小于99。 2. RequestAuthorizer > - 自定义认证方式,实现RequestAuthorizer接口, > - 可针对不同的AuthType和TargetType多种认证方式实现。 3. RestInterceptor > - 接口拦截,注解加到Service方法上,当condition条件为true时,拦截方法,并可返回Response。 > RequestInterceptor,用于返回自定义Response。 #### Example + Properties ```yaml spring: api: host: sms: localhost:8008 uri: sms: send: /mail/send test: api: sms: send: true ``` + Service ```java public interface SmsService { SmsResponse send(SmsRequest request); } ``` ```java @Service public class SmsServiceImpl extends AbstractInteService implements SmsService { @Override @RestInterceptor(condition = "test.api.sms.send") public SmsResponse send(final SmsRequest request) { String uri = "spring.api.uri.sms.notice";//指定uri的配置key HttpRequestWrapper wrapper = HttpRequestWrapper.createPost(uri,"sms",request,SmsResponse.class); //sms表示api的Host类型,默认key:spring.api.host.XXXX return exchange(wrapper); } } ``` + Domain ```java public class SmsRequest { private String phone; private String message; public String getPhone() { return phone; } public void setPhone(final String phone) { this.phone = phone; } public String getMessage() { return message; } public void setMessage(final String message) { this.message = message; } } ``` ```java public class SmsResponse { private String status; public String getStatus() { return status; } public void setStatus(final String status) { this.status = status; } } ```