1. 최초 요청 시 HTTP Request와 Response

Client's request

Client  ------------------------------> Server

Request URL: http://i1.daumcdn.net/cfs.tistory/static/images/logo.gif


Server's response

Client <------------------------------ Server

Header에 "Last-Modified"를 설정하여 응답한다. (아래의 그림 참조)




2. 재 요청 시 HTTP Request Response

Client's request

Client  ------------------------------> Server

Request URL: http://i1.daumcdn.net/cfs.tistory/static/images/logo.gif

최초 응답 시 받은 "Last-Modified"를 참조하여 Header에 "If-Modified-Since"를 설정하여 요청한다.
(Browser가 알아서 설정)

Server's response

Client <------------------------------ Server

Server는 "If-Modified-Since" 값과 비교하여 변경 사항이 없으면 HTTP Status Code 304로  응답한다.

(아래의 그림 참조)



3. Code Snipet


public void downloadResource(@PathVariable String resourceName,
						       HttpServletRequest request,
						      HttpServletResponse response) {
																				
		WebResource webResource = ResourceService.getResource(resourceName);
		long lastModified = webResource.getLastModified();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(lastModified);
		calendar.set(Calendar.MILLISECOND, 0);
		lastModified = calendar.getTimeInMillis();
		
		long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
		if (ifModifiedSince != -1 && ifModifiedSince >= lastModified) {
			response.setStatus(HttpStatus.SC_NOT_MODIFIED);
			return;
		}
		
		response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
		...
	}

- 출처: http://irooti.tistory.com/8

"올바른 성장과 따뜻한 나눔"이 있는 넥스트리

HTTP 는 대형 네트워크 시스템 아키텍처를 염두한 프로토콜이기에 단순하면서도 다양한 스펙들이 존재합니다. 대형 네트워크 시스템이다 보니 서로 주고 받는 정보가 많을 것이고 이에 네트워크 부하나 서버 부하가 발생할 소지가 매우 큽니다. 그런 상황을 위해 HTTP에는 단순하면서도 강력한 캐싱 메커니즘을 제공하고 있습니다.



브라우저와 웹서버와의 대화

브라우저는 웹서버에게 이미지, CSS 그리고 동적생성 정보(HTML, XML, JSON... 등 많은 컨텐츠를 요청합니다. 그런데 동일한 리소스(이하 컨텐츠)를 여러번 요청하는 경우가 굉장히 많습니다. 전형적인 예가 이미지나 CSS 같은 정적 컨텐츠인데 이런 것을 요청할 때 브라우저와 웹서버가 어떻게 대화하는지 아래 그림으로 살펴보겠습니다.

  • 1: /AAA 컨텐츠를 주세요
  • 2: OK 주었습니다. 이 컨텐츠의 마지막 갱신일은 2009년 9월 7일... 입니다. (컨텐츠 전송)
  • 잠시 후...
  • 3: /AAA 컨텐츠를 주세요. 아. 제가 캐시에 가지고 있는 건 마지막 갱신일이 2009년 9월 7일 ... 이네요
  • 4: 변경사항 없습니다. 그냥 캐시에 있는 것 쓰세요. (아무것도 전송 안함)
브라우저 기본설정이라면 캐시에 있을 경우 브라우저가 시작하고 한 번 확인하고 두 번 다시는 GET 확인 요청을 하지 않습니다. 그냥 캐시에 있는 걸 씁니다. 브라우저를 다시 시작할 경우만 확인 요청을 합니다. 서버에 아예 요청도 안 가니 네트워크나 서버 부하는 무지 감소합니다. (IE 인터넷 옵션 설정에서 "페이지를 열 때마다"로 설정된 경우는 매번 확인 요청을 합니다.)


동적 컨텐츠와 304

서블릿이나 JSP 등으로 생성하는 동적 컨텐츠는 매번 정보가 갱신되어야 하기에 이런 메커니즘을 사용하지 않습니다. 그런데 간혹 서버 컨텐츠 마지막 갱신일을 알고 매우 요청이 많은 페이지 일 경우 위 메커니즘을 이용하는 것도 좋은 방법이겠네요. 다음 예는 JSP로 구현한 소스 예입니다.

01<%
02  // 서버 컨텐츠의 마지막 갱신을 얻어온다.
03  java.util.Date date = getLastModified();
04  long clientDate = request.getDateHeader("If-Modified-Since");
05  long serverDate = date.getTime();
06  if (clientDate != -1 && clientDate >= serverDate) {
07      response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
08      return;
09  }
10  response.setDateHeader("Last-Modified", serverDate);
11%>

비즈니스 로직이 실행되기 전 해당 정보 갱신일을 살펴보고 다시 줄 것인지 304를 던질 것인지 판단하는게 좋겠습니다. 그래야 필요없는 서버 로직이 수행되지 않습니다.


웹 애플리케이션 성능 향상

기본에 충실하는게 좋습니다. 우선은 문제가 되는 비즈니스 로직을 충분히 튜닝하십시오. 그런 후 특별한 캐싱 장치를 사용하거나 가능하면 위의 경우처럼 표준 캐싱 메키니즘을 충분히 활용하십시오.

그리고 비즈니스 로직의 성능을 높이기 위해 특정 비즈니스 로직을 열심히 튜닝하기 전에 우선 Fiddler 같은 도구로 브라우저와 서버가 무슨 통신을 하는지 살펴보는게 좋습니다. 생각보다 필요없는 요청이 많이 발생할 수도 있습니다.

--

웹사이트를 빠르게 하는 다른 관점의 방법들도 있네요.


 - 출처 : http://greatkim91.tistory.com/118


UPDATE 07/19/2013: As pointed out in the comments by Ray Moro, a better way to fix this may be to remove the extension from your bundle name. So /bundle/myscrips.js becomes /bundle/myscriptsthis will cause it to run the module without having to change the config settings below.

That's a mouthful of a title.

If you're using ScriptBundle and StyleBundle's in an ASP.NET MVC4 app and you're suddenly getting 404 errors even though EnableOptimizations is set to true make sure you have the following in yourWeb.Config in the system.webServer section:

  1. <modules runAllManagedModulesForAllRequests="true">  
  2.   <remove name="BundleModule" />  
  3.   <add name="BundleModule" type="System.Web.Optimization.BundleModule" />  
  4. </modules>  

I've wasted incalculable amounts of time on this issue, TWICE!!! I don't know why this isn't in the web.config by default or better yet not needed to use Bundling.

출처 : http://sports.news.nate.com/view/20140830n05951?mid=s1005

+ Recent posts