spring boot實現(xiàn)超輕量級網(wǎng)關(guān)(反向代理、轉(zhuǎn)發(fā))的示例
作者: JadePeng
出處:https://www.cnblogs.com/xiaoqi/p/spring-boot-route.html
在我們的rest服務(wù)中,需要暴露一個中間件的接口給用戶,但是需要經(jīng)過rest服務(wù)的認(rèn)證,這是典型的網(wǎng)關(guān)使用場景。可以引入網(wǎng)關(guān)組件來搞定,但是引入zuul等中間件會增加系統(tǒng)復(fù)雜性,這里實現(xiàn)一個超輕量級的網(wǎng)關(guān),只實現(xiàn)請求轉(zhuǎn)發(fā),認(rèn)證等由rest服務(wù)的spring security來搞定。
如何進(jìn)行請求轉(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;@Servicepublic 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 POSTPUTDELETE 支持的請求帶上,就能實現(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); }}
以上就是spring boot實現(xiàn)超輕量級網(wǎng)關(guān)(反向代理、轉(zhuǎn)發(fā))的示例的詳細(xì)內(nèi)容,更多關(guān)于spring boot實現(xiàn)網(wǎng)關(guān)的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 基于javaweb+jsp實現(xiàn)學(xué)生宿舍管理系統(tǒng)2. 如何封裝一個Ajax函數(shù)3. 多級聯(lián)動下拉選擇框,動態(tài)獲取下一級4. ASP.NET MVC實現(xiàn)樹形導(dǎo)航菜單5. PHP擴(kuò)展之URL編碼、解碼及解析——URLs6. 使用maven開發(fā)springboot項目時pom.xml常用配置(推薦)7. Java 接口和抽象類的區(qū)別詳解8. Laravel Eloquent ORM高級部分解析9. 聊聊python dropna()和notnull()的用法區(qū)別10. jsp response.sendRedirect()用法詳解
