添加代码示例springboot-resttemplate

This commit is contained in:
yidao620
2018-02-28 10:26:35 +08:00
parent 465ad8d2c4
commit 9f8444bfd4
14 changed files with 631 additions and 0 deletions

View File

@ -0,0 +1,12 @@
package com.xncoding.pos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,59 @@
package com.xncoding.pos.config;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* RestTemplate客户端连接池配置
*
* @author XiongNeng
* @version 1.0
* @since 2018/1/24
*/
@Configuration
public class RestClientConfig {
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return new RestTemplate(httpRequestFactory());
}
@Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(5);
connectionManager.setDefaultMaxPerRoute(5);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(8000)
.setConnectTimeout(8000)
.setConnectionRequestTimeout(8000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}
}

View File

@ -0,0 +1,40 @@
package com.xncoding.pos.controller;
import com.xncoding.pos.model.LoginParam;
import com.xncoding.pos.model.UnbindParam;
import com.xncoding.pos.model.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
/**
* 登录接口类
*/
@RestController
public class LoginController {
private static final Logger _logger = LoggerFactory.getLogger(LoginController.class);
@PostMapping("/login")
public BaseResponse<String> login(@RequestHeader(name = "Content-Type", defaultValue = "application/json") String contentType,
@RequestBody LoginParam loginParam) {
_logger.info("用户请求登录获取Token");
String username = loginParam.getUsername();
String password = loginParam.getPassword();
return new BaseResponse<>(true, "Login success", username + password);
}
@PostMapping("/unbind")
public BaseResponse<String> unbind(@RequestHeader(name = "Content-Type", defaultValue = "application/json") String contentType,
@RequestHeader(name = "Authorization", defaultValue = "token") String token,
@RequestBody UnbindParam unbindParam) {
_logger.info("解绑通知接口start");
String imei = unbindParam.getImei();
String location = unbindParam.getLocation();
return new BaseResponse<>(true, "解绑通知发送成功", "unbind");
}
}

View File

@ -0,0 +1,60 @@
package com.xncoding.pos.model;
/**
* Controller的基础返回类
*
* @author XiongNeng
* @version 1.0
* @since 2018/1/7
*/
public class BaseResponse<T> {
/**
* 是否成功
*/
private boolean success;
/**
* 说明
*/
private String msg;
/**
* 返回数据
*/
private T data;
public BaseResponse() {
}
public BaseResponse(boolean success, String msg, T data) {
this.success = success;
this.msg = msg;
this.data = data;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@ -0,0 +1,59 @@
package com.xncoding.pos.model;
/**
* 登录认证接口参数
*
* @author XiongNeng
* @version 1.0
* @since 2018/1/9
*/
public class LoginParam {
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* Application ID
*/
private String appid;
/**
* IMEI码
*/
private String imei;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
}

View File

@ -0,0 +1,35 @@
package com.xncoding.pos.model;
/**
* 解绑通知参数
*
* @author XiongNeng
* @version 1.0
* @since 2018/1/9
*/
public class UnbindParam {
/**
* IMEI码
*/
private String imei;
/**
* 网点
*/
private String location;
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

View File

@ -0,0 +1,46 @@
##########################################################
################## 所有profile共有的配置 #################
##########################################################
################### 项目启动端口 ###################
server.port: 8092
################### spring配置 ###################
spring:
profiles:
active: dev
logging:
level:
org.springframework.web.servlet: ERROR
---
#####################################################################
######################## 开发环境profile ##########################
#####################################################################
spring:
profiles: dev
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: E:/logs/app.log
---
#####################################################################
######################## 测试环境profile ##########################
#####################################################################
spring:
profiles: test
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: /var/logs/app.log

View File

@ -0,0 +1,23 @@
_____ _______ _____ _____
/\ \ /::\ \ /\ \ /\ \
/::\____\ /::::\ \ /::\____\ /::\ \
/:::/ / /::::::\ \ /:::/ / /::::\ \
/:::/ / /::::::::\ \ /:::/ / /::::::\ \
/:::/ / /:::/~~\:::\ \ /:::/ / /:::/\:::\ \
/:::/ / /:::/ \:::\ \ /:::/____/ /:::/__\:::\ \
/:::/ / /:::/ / \:::\ \ |::| | /::::\ \:::\ \
/:::/ / /:::/____/ \:::\____\ |::| | _____ /::::::\ \:::\ \
/:::/ / |:::| | |:::| | |::| | /\ \ /:::/\:::\ \:::\ \
/:::/____/ |:::|____| |:::| | |::| | /::\____\/:::/__\:::\ \:::\____\
\:::\ \ \:::\ \ /:::/ / |::| | /:::/ /\:::\ \:::\ \::/ /
\:::\ \ \:::\ \ /:::/ / |::| | /:::/ / \:::\ \:::\ \/____/
\:::\ \ \:::\ /:::/ / |::|____|/:::/ / \:::\ \:::\ \
\:::\ \ \:::\__/:::/ / |:::::::::::/ / \:::\ \:::\____\
\:::\ \ \::::::::/ / \::::::::::/____/ \:::\ \::/ /
\:::\ \ \::::::/ / ~~~~~~~~~~ \:::\ \/____/
\:::\ \ \::::/ / \:::\ \
\:::\____\ \::/____/ \:::\____\
\::/ / ~~ \::/ /
\/____/ \/____/

View File

@ -0,0 +1,75 @@
package com.xncoding.pos;
import com.xncoding.pos.model.LoginParam;
import com.xncoding.pos.model.UnbindParam;
import com.xncoding.pos.model.BaseResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.net.URISyntaxException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* 测试任务
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTests {
private static final Logger logger = LoggerFactory.getLogger(ApplicationTests.class);
/**
* @LocalServerPort 提供了 @Value("${local.server.port}") 的代替
*/
@LocalServerPort
private int port;
@Autowired
private RestTemplate restTemplate;
@Test
public void testRestTemplate() {
logger.info("解绑成功后推送消息给对应的POS机");
LoginParam param = new LoginParam();
param.setUsername("admin");
param.setPassword("12345678");
String loginUrl = String.format("http://localhost:%d/login", port);
BaseResponse r = restTemplate.postForObject(loginUrl, param, BaseResponse.class);
assertThat(r.isSuccess(), is(true));
logger.info("推送消息登录认证成功");
String token = (String) r.getData();
UnbindParam unbindParam = new UnbindParam();
unbindParam.setImei("imei");
unbindParam.setLocation("location");
// 设置HTTP Header信息
String unbindUrl = String.format("http://localhost:%d/unbind", port);
URI uri;
try {
uri = new URI(unbindUrl);
} catch (URISyntaxException e) {
logger.error("URI构建失败", e);
throw new RuntimeException("URI构建失败");
}
RequestEntity<UnbindParam> requestEntity = RequestEntity
.post(uri)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.header("Authorization", token)
.body(unbindParam);
ResponseEntity<BaseResponse> responseEntity = restTemplate.exchange(requestEntity, BaseResponse.class);
BaseResponse r2 = responseEntity.getBody();
assertThat(r2.isSuccess(), is(true));
assertThat(r2.getData(), is("unbind"));
}
}