spring boot實現(xiàn)超輕量級網(wǎng)關(guān)的方法(反向代理、轉(zhuǎn)發(fā))
在我們的rest服務(wù)中,需要暴露一個中間件的接口給用戶,但是需要經(jīng)過rest服務(wù)的認證,這是典型的網(wǎng)關(guān)使用場景??梢砸刖W(wǎng)關(guān)組件來搞定,但是引入zuul等中間件會增加系統(tǒng)復(fù)雜性,這里實現(xiàn)一個超輕量級的網(wǎng)關(guān),只實現(xiàn)請求轉(zhuǎn)發(fā),認證等由rest服務(wù)的spring security來搞定。
如何進行請求轉(zhuǎn)發(fā)呢? 熟悉網(wǎng)絡(luò)請求的同學(xué)應(yīng)該很清楚,請求無非就是請求方式、HTTP header,以及請求body,我們將這些信息取出來,透傳給轉(zhuǎn)發(fā)的url即可。
舉例:
/graphdb/** 轉(zhuǎn)發(fā)到 Graph_Server/**
獲取轉(zhuǎn)發(fā)目的地址:
private String createRedictUrl(HttpServletRequest request, String routeUrl, String prefix) {
String queryString = request.getQueryString();
return routeUrl + request.getRequestURI().replace(prefix, "") +
(queryString != null ? "?" + queryString : "");
}
解析請求頭和內(nèi)容
然后從request中提取出header、body等內(nèi)容,構(gòu)造一個RequestEntity,后續(xù)可以用RestTemplate來請求。
private RequestEntity createRequestEntity(HttpServletRequest request, String url) throws URISyntaxException, IOException {
String method = request.getMethod();
HttpMethod httpMethod = HttpMethod.resolve(method);
MultiValueMap<String, String> headers = parseRequestHeader(request);
byte[] body = parseRequestBody(request);
return new RequestEntity<>(body, headers, httpMethod, new URI(url));
}
private byte[] parseRequestBody(HttpServletRequest request) throws IOException {
InputStream inputStream = request.getInputStream();
return StreamUtils.copyToByteArray(inputStream);
}
private MultiValueMap<String, String> parseRequestHeader(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
List<String> headerNames = Collections.list(request.getHeaderNames());
for (String headerName : headerNames) {
List<String> headerValues = Collections.list(request.getHeaders(headerName));
for (String headerValue : headerValues) {
headers.add(headerName, headerValue);
}
}
return headers;
}
透明轉(zhuǎn)發(fā)
最后用RestTemplate來實現(xiàn)請求:
private ResponseEntity<String> route(RequestEntity requestEntity) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange(requestEntity, String.class);
}
全部代碼
以下是輕量級轉(zhuǎn)發(fā)全部代碼:
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
@Service
public class RoutingDelegate {
public ResponseEntity<String> redirect(HttpServletRequest request, HttpServletResponse response,String routeUrl, String prefix) {
try {
// build up the redirect URL
String redirectUrl = createRedictUrl(request,routeUrl, prefix);
RequestEntity requestEntity = createRequestEntity(request, redirectUrl);
return route(requestEntity);
} catch (Exception e) {
return new ResponseEntity("REDIRECT ERROR", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private String createRedictUrl(HttpServletRequest request, String routeUrl, String prefix) {
String queryString = request.getQueryString();
return routeUrl + request.getRequestURI().replace(prefix, "") +
(queryString != null ? "?" + queryString : "");
}
private RequestEntity createRequestEntity(HttpServletRequest request, String url) throws URISyntaxException, IOException {
String method = request.getMethod();
HttpMethod httpMethod = HttpMethod.resolve(method);
MultiValueMap<String, String> headers = parseRequestHeader(request);
byte[] body = parseRequestBody(request);
return new RequestEntity<>(body, headers, httpMethod, new URI(url));
}
private ResponseEntity<String> route(RequestEntity requestEntity) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange(requestEntity, String.class);
}
private byte[] parseRequestBody(HttpServletRequest request) throws IOException {
InputStream inputStream = request.getInputStream();
return StreamUtils.copyToByteArray(inputStream);
}
private MultiValueMap<String, String> parseRequestHeader(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
List<String> headerNames = Collections.list(request.getHeaderNames());
for (String headerName : headerNames) {
List<String> headerValues = Collections.list(request.getHeaders(headerName));
for (String headerValue : headerValues) {
headers.add(headerName, headerValue);
}
}
return headers;
}
}
Spring 集成
Spring Controller,RequestMapping里把GET \ POST\PUT\DELETE 支持的請求帶上,就能實現(xiàn)轉(zhuǎn)發(fā)了。
@RestController
@RequestMapping(GraphDBController.DELEGATE_PREFIX)
@Api(value = "GraphDB", tags = {
"graphdb-Api"
})
public class GraphDBController {
@Autowired
GraphProperties graphProperties;
public final static String DELEGATE_PREFIX = "/graphdb";
@Autowired
private RoutingDelegate routingDelegate;
@RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, produces = MediaType.TEXT_PLAIN_VALUE)
public ResponseEntity catchAll(HttpServletRequest request, HttpServletResponse response) {
return routingDelegate.redirect(request, response, graphProperties.getGraphServer(), DELEGATE_PREFIX);
}
}
到此這篇關(guān)于spring boot實現(xiàn)超輕量級網(wǎng)關(guān)(反向代理、轉(zhuǎn)發(fā))的文章就介紹到這了,更多相關(guān)spring boot輕量級網(wǎng)關(guān)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
用StopWatch優(yōu)雅替代currentTimeMillis計算程序執(zhí)行耗時
別再用System.currentTimeMillis()計算程序執(zhí)行耗時了,擁抱StopWatch優(yōu)雅來優(yōu)雅的計算,代碼更簡潔效率更高,本文帶你了解StopWatch的使用2021-09-09
剖析Java中在Collection集合中使用contains和remove為什么要重寫equals
這篇文章主要介紹了Collection集合的contains和remove方法詳解remove以及相關(guān)的經(jīng)驗技巧,通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-09-09
java同步器AQS架構(gòu)AbstractQueuedSynchronizer原理解析下
這篇文章主要為大家介紹了java同步器AQS架構(gòu)AbstractQueuedSynchronizer原理解析下,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03
設(shè)計模式之構(gòu)建(Builder)模式 建造房子實例分析

