基於rest風格對Neo4j進行呼叫訪問之———RestTemplate

基於rest風格對Neo4j進行呼叫訪問之———RestTemplate

1.RestTemplate簡介

這個是spring 基於 web client 封裝的類,提供了很多基於rest 訪問的介面方法,極其好用。

2.程式碼實現

package neo4j.action;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.*;
@RestController
@RequestMapping("/neo4j/data")
public class NeoController {
private static final Logger log = LoggerFactory.getLogger(NeoController.class);
@Resource(name = "restTemplate")
private RestTemplate restTemplate;
@RequestMapping(value = "/getData", method = RequestMethod.POST)
public String getHello() {
//建立連線
log.info("getData介面呼叫開始時間:" new Date());// 介面呼叫開始時間
final String plainCreds = "username:password";
final byte[] plainCredsBytes = plainCreds.getBytes();
final byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
final String base64Creds = new String(base64CredsBytes);
final HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic "   base64Creds);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(new MediaType[] { new MediaType("application",
"json", Charset.forName("UTF-8")) }));
final HttpEntity<String> request = new HttpEntity<>("{\n"  
"  \"statements\" : [ {\n"  
"    \"statement\" : \"MATCH (n) RETURN n LIMIT 25\"\n"  
"  } ]\n"  
"}",headers);
final ResponseEntity<String> response = restTemplate.exchange("http://localhost/db/data/transaction/commit", HttpMethod.POST, request, String.class);
final String respString = response.getBody();
return respString;
}
}

3.保證RestTemplate返回結果不會正文亂碼

關聯的gettemplate方法,保證了通過restTemplate返回的結果不會中文亂碼

package neo4j.config;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.apache.commons.httpclient.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestTemplateConfiguration {
private int maxTotalConnect = 0; //連線池的最大連線數預設為0
private int maxConnectPerRoute =200; //單個主機的最大連線數
private int connectTimeout =2000; //連線超時預設2s
private int readTimeout = 30000; //讀取超時預設30s
//建立HTTP客戶端工廠
private ClientHttpRequestFactory createFactory() {
if (this.maxTotalConnect <= 0) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
.setMaxConnPerRoute(this.maxConnectPerRoute).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
httpClient);
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
//初始化RestTemplate,並加入spring的Bean工廠,由spring統一管理
@Bean("restTemplate")
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate(this.createFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//重新設定StringHttpMessageConverter字符集為UTF-8,解決中文亂碼問題
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//加入FastJson轉換器
converterList.add(new FastJsonHttpMessageConverter4());
return restTemplate;
}
}

4.通過postman模擬訪問返回結果

這裡寫圖片描述