溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體

發(fā)布時(shí)間:2022-04-07 14:35:15 來(lái)源:億速云 閱讀:483 作者:iii 欄目:編程語(yǔ)言

這篇文章主要介紹“在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體”,在日常操作中,相信很多人在在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

緩存請(qǐng)求響應(yīng)體的目的

把一個(gè)HTTP的請(qǐng)求,響應(yīng)信息完整的紀(jì)錄到日志。是一種常見(jiàn)有效的問(wèn)題排查,BUG重現(xiàn)的手段。

但是這種東西,有一個(gè)特點(diǎn)就是只能讀取/寫(xiě)入一次,不能重復(fù)。下一次讀寫(xiě),就是一個(gè)空的流,為了實(shí)現(xiàn)流的重用,就很有必要,把讀取和寫(xiě)入的數(shù)據(jù)緩存起來(lái), 可以在某個(gè)地方,再一次的讀取。

實(shí)現(xiàn)的思路

  • HttpServletRequestWrapper

  • HttpServletResponseWrapper

上面2個(gè)類(lèi),熟悉Servlet的都知道,這倆就是RequestResponse的裝飾模式實(shí)現(xiàn)。

通過(guò)裝飾者設(shè)計(jì)模式,我們可以在Request讀取請(qǐng)求body的時(shí)候,把讀取到的數(shù)據(jù)復(fù)制一份緩存起來(lái),記錄日志時(shí)使用。同理,也可以把Response響應(yīng)的數(shù)據(jù),先緩存起來(lái),用于記錄日志,然后再響應(yīng)給客戶(hù)端。

Spring提供的實(shí)現(xiàn)

ContentCachingRequestWrapper

// 這里忽略了 HttpServletRequest 的相關(guān)方法
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper  {
	// 包裝Servlet,不限制請(qǐng)求體的大小
	public ContentCachingRequestWrapper(HttpServletRequest request)
	// 包裝Servlet,限制請(qǐng)求體的大小
	public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit)
	// 獲取到緩存的請(qǐng)求體
	public byte[] getContentAsByteArray()
	// 請(qǐng)求體超過(guò)限制時(shí)會(huì)調(diào)用這個(gè)方法,默認(rèn)空實(shí)現(xiàn)
	protected void handleContentOverflow(int contentCacheLimit) 
}

比較好理解的一個(gè)類(lèi),建議通過(guò)contentCacheLimit限制請(qǐng)求體大小。因?yàn)樗J(rèn)把請(qǐng)求體緩存到內(nèi)存中,如果客戶(hù)端發(fā)起惡意請(qǐng)求,構(gòu)造大體積的請(qǐng)求體可能會(huì)消耗干凈服務(wù)器的內(nèi)存

ContentCachingResponseWrapper

// 這里忽略了 HttpServletResponse 的相關(guān)方法
public class ContentCachingResponseWrapper {
	// 把緩存中的響應(yīng)數(shù)據(jù),刷出到客戶(hù)端
	void copyBodyToResponse()
	// 獲取緩存數(shù)據(jù)
	byte[] getContentAsByteArray()
	// 獲取緩存數(shù)據(jù)
	InputStream getContentInputStream()
	// 獲取緩存數(shù)據(jù)的大小
	int getContentSize()
}

很簡(jiǎn)單,通過(guò)ContentCachingResponseWrapper 的包裝,任何往客戶(hù)端的響應(yīng)數(shù)據(jù),都會(huì)被它緩存起來(lái),重復(fù)的讀取使用,最終響應(yīng)給客戶(hù)端

請(qǐng)求日志的實(shí)現(xiàn)

Controller

及其簡(jiǎn)單,把請(qǐng)求體,添加時(shí)間戳后回寫(xiě)給客戶(hù)端。

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/demo")
public class DemoController {
	
	@RequestMapping(produces = { "application/json; charset=utf-8" })
	public Object demo (@RequestBody(required = false) String body) {
		Map<String, Object> response = new HashMap<>();
		response.put("reqeustBody", body);
		response.put("timesttamp", System.currentTimeMillis());
		return response;
	}
}

AccessLogFilter

通過(guò)AccessLogFilter輸出請(qǐng)求體/響應(yīng)體,耗時(shí),等等信息到日志。還對(duì)當(dāng)前請(qǐng)求體生成了一個(gè)全局唯一request-id,可以作為檢索的條件。

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.NestedServletException;

@Component
@WebFilter(filterName = "accessLogFilter", urlPatterns = "/*")
@Order(-9999) 		// 保證最先執(zhí)行
public class AccessLogFilter extends HttpFilter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AccessLogFilter.class);
	
	private static final long serialVersionUID = -7791168563871425753L;
	
	// 消息體過(guò)大
	@SuppressWarnings("unused")
	private static class PayloadTooLargeException extends RuntimeException {
		private static final long serialVersionUID = 3273651429076015456L;
		private final int maxBodySize;
		public PayloadTooLargeException(int maxBodySize) {
			super();
			this.maxBodySize = maxBodySize;
		}
	}

	@Override
	protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
		
		ContentCachingRequestWrapper cachingRequestWrapper = new ContentCachingRequestWrapper(req, 30) { // 限制30個(gè)字節(jié)
			@Override
			protected void handleContentOverflow(int contentCacheLimit) {
				throw new PayloadTooLargeException(contentCacheLimit);
			}
		};
		
		ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper(res);
		
		
		long start = System.currentTimeMillis();
		try {
			// 執(zhí)行請(qǐng)求鏈
			super.doFilter(cachingRequestWrapper, cachingResponseWrapper, chain);
		} catch (NestedServletException e) {
			Throwable cause = e.getCause();
			// 請(qǐng)求體超過(guò)限制,以文本形式給客戶(hù)端響應(yīng)異常信息提示
			if (cause instanceof PayloadTooLargeException) {
				cachingResponseWrapper.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
				cachingResponseWrapper.setContentType(MediaType.TEXT_PLAIN_VALUE);
				cachingResponseWrapper.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
				cachingResponseWrapper.getOutputStream().write("請(qǐng)求體過(guò)大".getBytes(StandardCharsets.UTF_8));
			} else {
				throw new RuntimeException(e);
			}
		}
		
		long end = System.currentTimeMillis();
		
		String requestId = UUID.randomUUID().toString();		// 生成唯一的請(qǐng)求ID
		cachingResponseWrapper.setHeader("x-request-id", requestId);
		
		String requestUri = req.getRequestURI();		// 請(qǐng)求的
		String queryParam = req.getQueryString();		// 查詢(xún)參數(shù)
		String method = req.getMethod();				// 請(qǐng)求方法
		int status = cachingResponseWrapper.getStatus();// 響應(yīng)狀態(tài)碼
		
		// 請(qǐng)求體
		// 轉(zhuǎn)換為字符串,在限制請(qǐng)求體大小的情況下,因?yàn)樽止?jié)數(shù)據(jù)不完整,這里可能亂碼,
		String requestBody = new String(cachingRequestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);	
		// 響應(yīng)體
		String responseBody = new String(cachingResponseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
		
		LOGGER.info("{} {}ms", requestId, end - start);
		LOGGER.info("{} {} {} {}", method, requestUri, queryParam, status);
		LOGGER.info("{}", requestBody);
		LOGGER.info("{}", responseBody);
		
		// 這一步很重要,把緩存的響應(yīng)內(nèi)容,輸出到客戶(hù)端
		cachingResponseWrapper.copyBodyToResponse();
	}
}

演示

正常請(qǐng)求和日志

在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體

com.demo.web.filter.AccessLogFilter      : a53500bc-c003-414a-9add-99655295a34f 1ms
com.demo.web.filter.AccessLogFilter      : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 200
com.demo.web.filter.AccessLogFilter      : {"name": "springboot"}
com.demo.web.filter.AccessLogFilter      : {"reqeustBody":"{\"name\": \"springboot\"}","timesttamp":1620395056498}

體積超過(guò)限制的請(qǐng)求和日志

在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體

com.demo.web.filter.AccessLogFilter      : 99476161-1790-48cc-86b9-0641efadc1b5 1ms
com.demo.web.filter.AccessLogFilter      : POST /demo site=springboot.io&name=springboot%E4%B8%AD%E6%96%87%E7%A4%BE%E5%8C%BA 413
com.demo.web.filter.AccessLogFilter      : {"name": "springboot"}{"name":
com.demo.web.filter.AccessLogFilter      : 請(qǐng)求體過(guò)大

因?yàn)橄拗屏苏?qǐng)求體的大小,這里日志中輸出的請(qǐng)求體日志,就只有限制字節(jié)的大小了

到此,關(guān)于“在SpringBoot中怎么緩存HTTP請(qǐng)求響應(yīng)體”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI