SlideShare uma empresa Scribd logo
1 de 45
RESTful Web Service
REST
(REpresentational State Transfer)
• The software architectural style of the World
Wide Web.
• 현재의 아키텍처가 웹의 본래 설계의 우수성을 많이 사
용하지 못하고 있다고 판단했기 때문에, 웹의 장점을 최
대한 활용할 수 있는 네트워크 기반의 아키텍처 제안
Client-Server Model
Socket
• 높은 이식성/성능, 세세한 제어
• Boilerplate code, 구현 및 예외 처리의 어려움
Client-Server Model
RPC(Remote Procedure Call)
• Network 통신 관련 작업은 몰라도 됨
• IDL(Interface Definition Language) 활용
• 원격지의 프로그램을 로컬 프로그램처럼 사용
Client-Server Model
Object-Oriented RPC
• 분산 환경에서의 Remote Call
• CORBA: Common Object Request Broker
Architecture
• RMI: Remote Method Invocation
• DCOM: Distributed Component Object Model
Client-Server Model
CORBA
• 로컬/원격을 포괄한 프로그램 객체 간의 메소드
호출 표준화에
• 목적으로 OMG에서 정의한 규격.
• 다양한 언어 지원.
Client-Server Model
RMI/EJB
• 서로 다른 JVM간의 메소드 호출을 지원.
• JAVA만 지원.
Client-Server Model
COM/DCOM/COM+
• COM은 플랫폼 독립적…
• 프로세스간 통신과 동적 오브젝트 생성이 가능
• 동일 OS간 사용(사실 윈도우..).
Client-Server Model
RPC, CORBA, RMI, DCOM..
• 복잡성
• 어려움
• 보안
• 성능
• 호환성
Client-Server Model
SOA(Service Oriented
Architecture)
• 업무상에 일 처리에 해당하는 소프트웨어 기능
을 서비스로 판단하여 그 서비스를 네트워크상
에 연동하여 시스템 전체를 구축해 나가는 방법
론
• 공개, 기민성, 확장, 연합, 자립적 요소들로 구성
된 조합 가능한 아키텍처, 서비스 품질, 다양한
벤더, 상호 운영성, 느슨한 연결, 서비스 발견 그
리고 잠재적으로 재사용 가능한 서비스들이 웹
서비스로 구현
Client-Server Model
SOAP(Simple Object Access
Protocol)
• HTTP + XML, WSDL, UDDI
• HTTP에서 메시지 전달 Overhead
• 엄격한 문법 및 고 난이도 개발
The Constraints of REST
• 클라이언트-서버 (Client-Server)
• 무상태 (Stateless)
• 캐시 (Cache)
• 균일한 인터페이스 (Uniform Interface)
• 계층 시스템 (Layered System)
• 주문형 코드(Code-on-demand) - optional
Client-Server
• 웹의 일관된 인터페이스를 따른다는 전제하에,
클라이언트와 서버는 독립적으로 구현/배포 되어
야 함.
Stateless
• 웹 서버가 클라이언트의 상태를 관리할 필요가
없어야 함.
Stateful vs Stateless
Cache
• 웹 서버가 응답 데이터마다 캐시 여부를 선언 할
수 있어야 함.
Uniform Interface
• Identification of resources (자원 식별)
• Manipulation of resource through representations (표
현을 통한 자원 처리)
• Self-descriptive messages (자기 서술적 메시지)
• HATEOAS (Hypermedia as the Engine Of Application
State)
• 같은 인터페이스 제약에 따라 서로 일관성 있게 상호 운
영 되어야 한다.
Identification of resources
• 리소스란 웹 상에서 서로 구별되는 어떤 개념
• 리소스는 유일하게 구별되어 저야 함.
• URI(URL,URN)로 표현
• http://www.my-domain.com/users/my-name
Manipulation of resource
through representations
• 클라이언트가 리소스 표현을 처리
• 리소스는 다양한 방법으로 표현
• 리소스 표현은 리소스와 상호작용 하는 방법
<xml>
<user>
<id>user-id</id>
<name>user-name</name>
</user>
</xml>
{
"user": {
"id": "user-id",
"name": "user-name"
}
}
Self-descriptive messages
• 요청을 처리하는데 필요한 모든 정보가 포함
• 리소스의 요청 상태는 클라이언트의 요청 메시지로, 리
소스의 현재 상태는 서버의 응답 메시지로 처리
• 메시지는 메타데이터를 포함하고 상태, 표현 형식, 크기
등 추가 정보를 전달
GET /users/ user-id HTTP/1.1
Host: http://www.mydomain.com/
User-Agent: curl
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Location:
http://www.mydomain.com/users/user
-id
Content-Length: 35
{
…
}
HATEOAS
• 리소스의 상태 표현은 관련 리소스의 링크를 포함
• 리소스 링크를 통한 State transitions (상태 전이)
• 리소스의 현재 상태에서 서버가 다음으로 할 수 있는 행
위 제공
• 절대적 표준은 없고 RFC4287,RFC5988의 권고 사항 따름
{
"user": {
"id": "user-id",
"name": "user-name"
}
}
{
"user": {
"id": "user-id",
"name": "user-name"
},
“links” : [{
“rel” : “delete”,
“href” : “http://~/users/user-id”
}]
}
Richardson Maturity Model
• Leonard Richardson이 고안한 HTTP 전송 계층의 관점에
서 REST를 리소스, 메소드, 하이퍼미디어등의 용어로 쉽
게 설명한 모델
Level 0
단일 URI, 단일 메소드
Level 1
다중 URI 기반의 리소스,
단일 메소드
Level 2
다중 URI 기반의
리소스 및 메소드
Level 3
HATEOAS
Level 0 : 원격 프로시저 호출
POST로 XML 데이터를 SOAP이나 XML-RPC 전송
Level 1 : REST 리소스
함수 파라미터 대신 REST URI 이용, 리소스 분산
Level 2 : 추가 HTTP 메소드
POST 외에 GET, HEAD, DELETE, PUT,
REST 진정한 유스케이스
Level 3 : HATEOAS
가장 성숙한 단계로 응답 속에 클라이언트가
취해야 할 액션 전달
Chain of connected feeds
Layered System
• 웹의 일관된 인터페이스를 사용해서, Proxy 또는
Gateway 같은 네트워크 기반의 중간매체를 사용 가능하
도록 함.
Code-On-Demand
• 유일한 선택사항으로 스크립트나 플러그인 같은 실행 가
능한 프로그램을 클라이언트에 전송하여, 클라이언트가
실행 가능 하도록 함.
REST Goals
• Performance
• Scalability
• Simplicity
• Modifiability
• Visibility
• Portability
• Reliability
REST Goals
RESTful & RESTful API ?
• REST 원리(제약조건)를 따르는 시스템
• REST 구조적 스타일에 적합한 Web API
Five Clues That Your API isn't
RESTful
• It has a single endpoint
- http://www.mydomain.com/api
• All requests are POSTs
- ~/users?query=select,insert,update,delete
• Response metadata is in the body, not header
- HTTP1.1 200 OK
resultCode: 1400, message: “bad request”
• There are verbs in the URL
- /item/42/activate -> /item/42/status
• The URL includes method names
- ?action=getRecentItems -> ?action=modifyRecentItems
HTTP Method
Method Description
POST Create or Execute function
GET Select
PUT Create or Update
DELETE Delete
OPTION Get available Method
PATCH Update partial
JAX-RS Implementations
• Apache CXF - an open source Web service framework (JAX-RS 2.0)
• Jersey - the reference implementation from Sun(now Oracle, JAX-RS 2.0)
• RESTeasy - JBoss's implementation (JAX-RS 2.0)
• Restlet - a lightweight, comprehensive, open source RESTful web API framework
for the Java platform. (JAX-RS 1.1)
• Apache Wink - Apache Software Foundation Incubator project, the server module
implements JAX-RS
• WebSphere - Application Server from IBM
• WebLogic - Application Server from Oracle, see notes
• Apache Tuscany - (http://tuscany.apache.org/documentation-2x/sca-java-
bindingrest.html)
• Cuubez - framework (http://www.cuubez.com)
• Everrest - Codenvy's Implementation
• Jello-Framework - Java Application Framework optimized for Google App Engine.
• Dropwizard, Ninja Web Framework, Play Framework, RestExpress, Restx, Spark
Framework
JAX-RS API
Spring
JAX-RS vs Spring
• @Path specifies the relative path for a resource class or method.
• - @RequestMapping
• @GET, @PUT, @POST, @DELETE and @HEAD specify the HTTP request type of a resource.
• - @RequestMapping(method)
• @Produces specifies the response Internet media types (used for content negotiation).
• - @RequestMapping(headers)
• @Consumes specifies the accepted request Internet media types.
• - @RequestMapping(headers)
• @PathParam binds the method parameter to a path segment.
• - @PathVariable
• @QueryParam binds the method parameter to the value of an HTTP query parameter.
• - @RequestVariable
• @MatrixParam binds the method parameter to the value of an HTTP matrix parameter.
• - @MatrixVariable
• @HeaderParam binds the method parameter to an HTTP header value.
• - @RequestHeader
• @CookieParam binds the method parameter to a cookie value.
• - @CookieValue
• @FormParam binds the method parameter to a form value.
• - @RequestParam
• @DefaultValue specifies a default value for the above bindings when the key is not found.
• - @RequestParam(defaultValue)
• @Context returns the entire context of the object (for example @Context HttpServletRequest request).
• - @ResponseStatus
• @Provider binds the application components(data, exception mapping and context resolution)
• - @ExceptionHandler
Comparison
Why use
JAX-RS Implementations ?
• Java 표준 API
• 구현체간 쉬운 포팅
• Spring 3.2 이전에는 대안이 없었음
• 여전히 Spring에서 최신 스펙 지원 X
Caching
• Strong Caching Header
- 리소스 요효시간 지정
ex) Expires, Cache-Control, max-age
• Weak Caching Header
- GET 요청을 날려 캐시로부터 아이템을
가져와야 할 지 판단하기 위한 정보
ex) Last-Modified, ETag
JAX-RS Cache-Control
CacheControl cacheControl = new CacheControl();
cacheControl.setMaxAge(3600);
cacheControl.setPrivate(true);
cacheControl.setNoCache(true);
Response.ResponseBuilder responseBuilder =
Response.ok();
responseBuilder.cacheControl(cacheControl);
Spring Cache-Control
<mvc:annotation-driven/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/api/**/*"/>
<bean id="webContentInterceptor"
class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<property name="cacheSeconds" value="0"/>
<property name="useExpiresHeader" value="true"/>
<property name="useCacheControlHeader" value="true"/>
<property name="useCacheControlNoStore" value="true"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>
* Spring 4.2 : org.springframework.http.CacheControl
ETags(Entity Tag)
Client Server
GET /users/1
200 OK ETag: “1”
GET /users/1 If-None-Match: ”1”
304 Not Modified
Time
No content
1. 클라이언트에서 /users/1로 REST 리소스를 GET 요청
2. 서버는 Etag값(예: “1” 실제로는 MD5해쉬값)과 함께 200 OK 응답 코드 전송
3. 잠시 후 클라이언트는 동일한 리소스를 한번 더 GET으로 요청
이때 If-None-Match 헤더에 마지막으로 받은 ETag값 동봉
4. 서버는 해당 리소스의 해시값이 바뀌지 않았는지 체크하고
동일한 경우 304 Not-Modified 리턴
JAX-RS ETag
EntityTag et = new EntityTag("1");
Response.ResponseBuilder responseBuilder =
request.evaluatePreconditions(et);
if (responseBuilder != null) {
return responseBuilder.build();
}
responseBuilder = Response.ok();
return responseBuilder.tag(et).build();
Spring ETag
<web-app>
…
<filter>
<filter-name>etagFilter</filter-name>
<filter-class>
org.springframework.web.filter.ShallowEtagHeaderFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>etagFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Types of ETags
• Strong ETag : 강한 ETag검증 일치로 두
리소스가 바이트 단위 까지 일치하고
Content-Language 필드도 변경되면 안됨
• Weak ETag : 약한 ETag검증 일치로 GET
요청과 ETag, IF-None-Match, 304-Not
Modified만 사용
• HTTP 응답 시 Last-Modified, ETag중 하나
• Expires, Cache-Control max-age 중 하나
• 모두 설정할 경우 Etag가 Last-Modified 보다 우선, Cache-Control이 Expires 보다 우선
Rate Limiting Pattern
• 클라이언트의 요청 개수를 제한 하기 위해
HTTP 429 Too Many Request를 전달
HTTP/1.1 429 Too Many Request
Content-Type: text/html
Retry-After: 3600
X-RateLimit-Limit : 100
X-RateLimit-Remaining : 10
• Rety-After : 재시도 요청 대기 시간(초단위)
• X-RateLimit-Limit : 일정 기간 동안 클라이언트가 요청 가능 수
• X-RateLimit-Remaining : 현재 남이 있는 요청 가능 수
Rate Limit Filter
Client Server
Rate
Limiting
Filter
Request Request
Response
420 Error, Retry-After,
X-RateLmit-Remaining
Tools
• cURL, Postman, Advaned Rest Client
• Swagger(http://swagger.io/),
APIDOC(http://apidocjs.com/), I/O
DOCS(http://www.mashery.com/api/io-docs)
• RAML(http://raml.org/),
WRML(http://www.wrml.org),
VISUALDIAGRAM(https://www.visual-
paradigm.com),
APISTUDIO(http://apistudio.io/)

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

REST API 설계
REST API 설계REST API 설계
REST API 설계
 
REST API 디자인 개요
REST API 디자인 개요REST API 디자인 개요
REST API 디자인 개요
 
대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest대용량 분산 아키텍쳐 설계 #5. rest
대용량 분산 아키텍쳐 설계 #5. rest
 
제 4회 DGMIT R&D 컨퍼런스 : REST API - 리소스 지향적 아키텍처
제 4회 DGMIT R&D 컨퍼런스 : REST API - 리소스 지향적 아키텍처제 4회 DGMIT R&D 컨퍼런스 : REST API - 리소스 지향적 아키텍처
제 4회 DGMIT R&D 컨퍼런스 : REST API - 리소스 지향적 아키텍처
 
RESTful API 설계
RESTful API 설계RESTful API 설계
RESTful API 설계
 
RESTful Mashup
RESTful MashupRESTful Mashup
RESTful Mashup
 
Flask, Redis, Retrofit을 이용한 Android 로그인 서비스 구현하기
Flask, Redis, Retrofit을 이용한 Android 로그인 서비스 구현하기Flask, Redis, Retrofit을 이용한 Android 로그인 서비스 구현하기
Flask, Redis, Retrofit을 이용한 Android 로그인 서비스 구현하기
 
REST Ovewview
REST OvewviewREST Ovewview
REST Ovewview
 
RPC에서 REST까지 간단한 개념소개
RPC에서 REST까지 간단한 개념소개RPC에서 REST까지 간단한 개념소개
RPC에서 REST까지 간단한 개념소개
 
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
대용량 분산 아키텍쳐 설계 #3 대용량 분산 시스템 아키텍쳐
 
Json view 예제 설명
Json view 예제 설명Json view 예제 설명
Json view 예제 설명
 
SOAP REST 이해
SOAP REST 이해SOAP REST 이해
SOAP REST 이해
 
Web http spec(basic)
Web http spec(basic)Web http spec(basic)
Web http spec(basic)
 
WoO 2012-Web 서비스 기술
WoO 2012-Web 서비스 기술WoO 2012-Web 서비스 기술
WoO 2012-Web 서비스 기술
 
1. 웹 어플리케이션 아키텍처
1. 웹 어플리케이션 아키텍처1. 웹 어플리케이션 아키텍처
1. 웹 어플리케이션 아키텍처
 
[D2 CAMPUS]웹 개발자의 스펙 : HTTP
[D2 CAMPUS]웹 개발자의 스펙 : HTTP[D2 CAMPUS]웹 개발자의 스펙 : HTTP
[D2 CAMPUS]웹 개발자의 스펙 : HTTP
 
HTTP 발표자료 - 김연수
HTTP 발표자료 - 김연수HTTP 발표자료 - 김연수
HTTP 발표자료 - 김연수
 
Http 완벽가이드(3장 http 메시지)
Http 완벽가이드(3장 http 메시지)Http 완벽가이드(3장 http 메시지)
Http 완벽가이드(3장 http 메시지)
 
Open source apm scouter를 통한 관제 관리 jadecross 정환열 수석
Open source apm scouter를 통한 관제  관리 jadecross 정환열 수석Open source apm scouter를 통한 관제  관리 jadecross 정환열 수석
Open source apm scouter를 통한 관제 관리 jadecross 정환열 수석
 
Web server
Web serverWeb server
Web server
 

Destaque

Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
knight1128
 
서비스를 성공적으로 만드는 방법
서비스를 성공적으로 만드는 방법서비스를 성공적으로 만드는 방법
서비스를 성공적으로 만드는 방법
우영 주
 
[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법
[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법
[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법
Nts Nuli
 
Rpc (Distributed computing)
Rpc (Distributed computing)Rpc (Distributed computing)
Rpc (Distributed computing)
Sri Prasanna
 
Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...
Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...
Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...
Lightbend
 
[2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견!
[2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견![2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견!
[2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견!
Nts Nuli
 
Introduction to Remote Procedure Call
Introduction to Remote Procedure CallIntroduction to Remote Procedure Call
Introduction to Remote Procedure Call
Abdelrahman Al-Ogail
 

Destaque (20)

Grpc present
Grpc presentGrpc present
Grpc present
 
Distributed System
Distributed SystemDistributed System
Distributed System
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
 
[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기
[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기
[Toolcon2014] WebStorm에서 자바스크립트 리팩토링하기
 
서비스를 성공적으로 만드는 방법
서비스를 성공적으로 만드는 방법서비스를 성공적으로 만드는 방법
서비스를 성공적으로 만드는 방법
 
Trends in advertising and Public Relation
Trends in advertising and Public RelationTrends in advertising and Public Relation
Trends in advertising and Public Relation
 
Web Design Trends & Best Practices (by Blueliner Marketing CEO, Arman Rousta)
Web Design Trends & Best Practices (by Blueliner Marketing CEO, Arman Rousta)Web Design Trends & Best Practices (by Blueliner Marketing CEO, Arman Rousta)
Web Design Trends & Best Practices (by Blueliner Marketing CEO, Arman Rousta)
 
[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법
[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법
[2014널리세미나] 장애 환경의 온라인 체험 및 활용 방법
 
Rpc (Distributed computing)
Rpc (Distributed computing)Rpc (Distributed computing)
Rpc (Distributed computing)
 
Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...
Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...
Distributed Systems Done Right: Why Java Enterprises Are Embracing The Actor ...
 
[2016널리세미나] 남의 문제 나의 문제 우리의 문제
[2016널리세미나] 남의 문제 나의 문제 우리의 문제[2016널리세미나] 남의 문제 나의 문제 우리의 문제
[2016널리세미나] 남의 문제 나의 문제 우리의 문제
 
Service Worker 를 이용한 
Offline Web Application 구현
Service Worker 를 이용한 
Offline Web Application 구현Service Worker 를 이용한 
Offline Web Application 구현
Service Worker 를 이용한 
Offline Web Application 구현
 
[2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견!
[2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견![2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견!
[2014널리세미나] 접근성 빅(?) 데이터, 새로운 법칙의 발견!
 
Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)Component Object Model (COM, DCOM, COM+)
Component Object Model (COM, DCOM, COM+)
 
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
웹을 지탱하는 차세대 기술 @한국웹20주년 컨퍼런스
 
Micro Service Architecture 탐방기
Micro Service Architecture 탐방기Micro Service Architecture 탐방기
Micro Service Architecture 탐방기
 
Introduction to Remote Procedure Call
Introduction to Remote Procedure CallIntroduction to Remote Procedure Call
Introduction to Remote Procedure Call
 
SharePoint User Experience Best Practices
SharePoint User Experience Best PracticesSharePoint User Experience Best Practices
SharePoint User Experience Best Practices
 
웹 서비스 기획
웹 서비스 기획웹 서비스 기획
웹 서비스 기획
 
웹 콘텐츠 기획
웹 콘텐츠 기획웹 콘텐츠 기획
웹 콘텐츠 기획
 

Semelhante a Restful web service

숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
VMware Tanzu Korea
 

Semelhante a Restful web service (20)

REST with Spring
REST with SpringREST with Spring
REST with Spring
 
4-3. jquery
4-3. jquery4-3. jquery
4-3. jquery
 
Spring 4.x Web Application 살펴보기
Spring 4.x Web Application  살펴보기Spring 4.x Web Application  살펴보기
Spring 4.x Web Application 살펴보기
 
자바 웹 개발 시작하기 (3주차 : 스프링 웹 개발)
자바 웹 개발 시작하기 (3주차 : 스프링 웹 개발)자바 웹 개발 시작하기 (3주차 : 스프링 웹 개발)
자바 웹 개발 시작하기 (3주차 : 스프링 웹 개발)
 
200.마이크로서비스에 적합한 오픈소스 WAS는 무엇?
200.마이크로서비스에 적합한 오픈소스 WAS는 무엇?200.마이크로서비스에 적합한 오픈소스 WAS는 무엇?
200.마이크로서비스에 적합한 오픈소스 WAS는 무엇?
 
CouchDB - Introduction - Korean
CouchDB - Introduction - KoreanCouchDB - Introduction - Korean
CouchDB - Introduction - Korean
 
Cloud life seminar open shift,이준영(배포용)
Cloud life seminar   open shift,이준영(배포용)Cloud life seminar   open shift,이준영(배포용)
Cloud life seminar open shift,이준영(배포용)
 
Apache Htrace overview (20160520)
Apache Htrace overview (20160520)Apache Htrace overview (20160520)
Apache Htrace overview (20160520)
 
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3 AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
AWS로 게임 기반 다지기 - 김병수, 박진성 :: AWS Game Master 온라인 세미나 #3
 
Servlet3
Servlet3Servlet3
Servlet3
 
.Net conf 2019 Korea_ ASP.NET Core를 통한 HealthCheck 서비스 구현
.Net conf 2019 Korea_ ASP.NET Core를 통한 HealthCheck 서비스 구현.Net conf 2019 Korea_ ASP.NET Core를 통한 HealthCheck 서비스 구현
.Net conf 2019 Korea_ ASP.NET Core를 통한 HealthCheck 서비스 구현
 
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
숨겨진 마이크로서비스: 초고속 응답과 고가용성을 위한 캐시 서비스 디자인
 
#22.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#22.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#22.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#22.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
 
파이썬 웹 프로그래밍 2탄
파이썬 웹 프로그래밍 2탄 파이썬 웹 프로그래밍 2탄
파이썬 웹 프로그래밍 2탄
 
마이크로서비스 아키텍처로 개발하기
마이크로서비스 아키텍처로 개발하기마이크로서비스 아키텍처로 개발하기
마이크로서비스 아키텍처로 개발하기
 
Azure를 이용한 Join 없는 글로벌 분산 시스템 설계하기
Azure를 이용한 Join 없는 글로벌 분산 시스템 설계하기Azure를 이용한 Join 없는 글로벌 분산 시스템 설계하기
Azure를 이용한 Join 없는 글로벌 분산 시스템 설계하기
 
Trace End-User Request (조동진)
Trace End-User Request (조동진)Trace End-User Request (조동진)
Trace End-User Request (조동진)
 
서버성능개선 류우림
서버성능개선 류우림서버성능개선 류우림
서버성능개선 류우림
 
CloudWatch 성능 모니터링과 신속한 대응을 위한 노하우 - 박선용 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
CloudWatch 성능 모니터링과 신속한 대응을 위한 노하우 - 박선용 솔루션즈 아키텍트:: AWS Cloud Track 3 GamingCloudWatch 성능 모니터링과 신속한 대응을 위한 노하우 - 박선용 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
CloudWatch 성능 모니터링과 신속한 대응을 위한 노하우 - 박선용 솔루션즈 아키텍트:: AWS Cloud Track 3 Gaming
 
자바 웹 개발 시작하기 (6주차 : 커뮤니티를 만들어보자!)
자바 웹 개발 시작하기 (6주차 : 커뮤니티를 만들어보자!)자바 웹 개발 시작하기 (6주차 : 커뮤니티를 만들어보자!)
자바 웹 개발 시작하기 (6주차 : 커뮤니티를 만들어보자!)
 

Restful web service

  • 2. REST (REpresentational State Transfer) • The software architectural style of the World Wide Web. • 현재의 아키텍처가 웹의 본래 설계의 우수성을 많이 사 용하지 못하고 있다고 판단했기 때문에, 웹의 장점을 최 대한 활용할 수 있는 네트워크 기반의 아키텍처 제안
  • 3. Client-Server Model Socket • 높은 이식성/성능, 세세한 제어 • Boilerplate code, 구현 및 예외 처리의 어려움
  • 4. Client-Server Model RPC(Remote Procedure Call) • Network 통신 관련 작업은 몰라도 됨 • IDL(Interface Definition Language) 활용 • 원격지의 프로그램을 로컬 프로그램처럼 사용
  • 5. Client-Server Model Object-Oriented RPC • 분산 환경에서의 Remote Call • CORBA: Common Object Request Broker Architecture • RMI: Remote Method Invocation • DCOM: Distributed Component Object Model
  • 6. Client-Server Model CORBA • 로컬/원격을 포괄한 프로그램 객체 간의 메소드 호출 표준화에 • 목적으로 OMG에서 정의한 규격. • 다양한 언어 지원.
  • 7. Client-Server Model RMI/EJB • 서로 다른 JVM간의 메소드 호출을 지원. • JAVA만 지원.
  • 8. Client-Server Model COM/DCOM/COM+ • COM은 플랫폼 독립적… • 프로세스간 통신과 동적 오브젝트 생성이 가능 • 동일 OS간 사용(사실 윈도우..).
  • 9. Client-Server Model RPC, CORBA, RMI, DCOM.. • 복잡성 • 어려움 • 보안 • 성능 • 호환성
  • 10. Client-Server Model SOA(Service Oriented Architecture) • 업무상에 일 처리에 해당하는 소프트웨어 기능 을 서비스로 판단하여 그 서비스를 네트워크상 에 연동하여 시스템 전체를 구축해 나가는 방법 론 • 공개, 기민성, 확장, 연합, 자립적 요소들로 구성 된 조합 가능한 아키텍처, 서비스 품질, 다양한 벤더, 상호 운영성, 느슨한 연결, 서비스 발견 그 리고 잠재적으로 재사용 가능한 서비스들이 웹 서비스로 구현
  • 11. Client-Server Model SOAP(Simple Object Access Protocol) • HTTP + XML, WSDL, UDDI • HTTP에서 메시지 전달 Overhead • 엄격한 문법 및 고 난이도 개발
  • 12. The Constraints of REST • 클라이언트-서버 (Client-Server) • 무상태 (Stateless) • 캐시 (Cache) • 균일한 인터페이스 (Uniform Interface) • 계층 시스템 (Layered System) • 주문형 코드(Code-on-demand) - optional
  • 13. Client-Server • 웹의 일관된 인터페이스를 따른다는 전제하에, 클라이언트와 서버는 독립적으로 구현/배포 되어 야 함.
  • 14. Stateless • 웹 서버가 클라이언트의 상태를 관리할 필요가 없어야 함.
  • 16. Cache • 웹 서버가 응답 데이터마다 캐시 여부를 선언 할 수 있어야 함.
  • 17. Uniform Interface • Identification of resources (자원 식별) • Manipulation of resource through representations (표 현을 통한 자원 처리) • Self-descriptive messages (자기 서술적 메시지) • HATEOAS (Hypermedia as the Engine Of Application State) • 같은 인터페이스 제약에 따라 서로 일관성 있게 상호 운 영 되어야 한다.
  • 18. Identification of resources • 리소스란 웹 상에서 서로 구별되는 어떤 개념 • 리소스는 유일하게 구별되어 저야 함. • URI(URL,URN)로 표현 • http://www.my-domain.com/users/my-name
  • 19. Manipulation of resource through representations • 클라이언트가 리소스 표현을 처리 • 리소스는 다양한 방법으로 표현 • 리소스 표현은 리소스와 상호작용 하는 방법 <xml> <user> <id>user-id</id> <name>user-name</name> </user> </xml> { "user": { "id": "user-id", "name": "user-name" } }
  • 20. Self-descriptive messages • 요청을 처리하는데 필요한 모든 정보가 포함 • 리소스의 요청 상태는 클라이언트의 요청 메시지로, 리 소스의 현재 상태는 서버의 응답 메시지로 처리 • 메시지는 메타데이터를 포함하고 상태, 표현 형식, 크기 등 추가 정보를 전달 GET /users/ user-id HTTP/1.1 Host: http://www.mydomain.com/ User-Agent: curl Accept: application/json HTTP/1.1 200 OK Content-Type: application/json Location: http://www.mydomain.com/users/user -id Content-Length: 35 { … }
  • 21. HATEOAS • 리소스의 상태 표현은 관련 리소스의 링크를 포함 • 리소스 링크를 통한 State transitions (상태 전이) • 리소스의 현재 상태에서 서버가 다음으로 할 수 있는 행 위 제공 • 절대적 표준은 없고 RFC4287,RFC5988의 권고 사항 따름 { "user": { "id": "user-id", "name": "user-name" } } { "user": { "id": "user-id", "name": "user-name" }, “links” : [{ “rel” : “delete”, “href” : “http://~/users/user-id” }] }
  • 22. Richardson Maturity Model • Leonard Richardson이 고안한 HTTP 전송 계층의 관점에 서 REST를 리소스, 메소드, 하이퍼미디어등의 용어로 쉽 게 설명한 모델 Level 0 단일 URI, 단일 메소드 Level 1 다중 URI 기반의 리소스, 단일 메소드 Level 2 다중 URI 기반의 리소스 및 메소드 Level 3 HATEOAS Level 0 : 원격 프로시저 호출 POST로 XML 데이터를 SOAP이나 XML-RPC 전송 Level 1 : REST 리소스 함수 파라미터 대신 REST URI 이용, 리소스 분산 Level 2 : 추가 HTTP 메소드 POST 외에 GET, HEAD, DELETE, PUT, REST 진정한 유스케이스 Level 3 : HATEOAS 가장 성숙한 단계로 응답 속에 클라이언트가 취해야 할 액션 전달
  • 24. Layered System • 웹의 일관된 인터페이스를 사용해서, Proxy 또는 Gateway 같은 네트워크 기반의 중간매체를 사용 가능하 도록 함.
  • 25. Code-On-Demand • 유일한 선택사항으로 스크립트나 플러그인 같은 실행 가 능한 프로그램을 클라이언트에 전송하여, 클라이언트가 실행 가능 하도록 함.
  • 26. REST Goals • Performance • Scalability • Simplicity • Modifiability • Visibility • Portability • Reliability
  • 28. RESTful & RESTful API ? • REST 원리(제약조건)를 따르는 시스템 • REST 구조적 스타일에 적합한 Web API
  • 29. Five Clues That Your API isn't RESTful • It has a single endpoint - http://www.mydomain.com/api • All requests are POSTs - ~/users?query=select,insert,update,delete • Response metadata is in the body, not header - HTTP1.1 200 OK resultCode: 1400, message: “bad request” • There are verbs in the URL - /item/42/activate -> /item/42/status • The URL includes method names - ?action=getRecentItems -> ?action=modifyRecentItems
  • 30. HTTP Method Method Description POST Create or Execute function GET Select PUT Create or Update DELETE Delete OPTION Get available Method PATCH Update partial
  • 31. JAX-RS Implementations • Apache CXF - an open source Web service framework (JAX-RS 2.0) • Jersey - the reference implementation from Sun(now Oracle, JAX-RS 2.0) • RESTeasy - JBoss's implementation (JAX-RS 2.0) • Restlet - a lightweight, comprehensive, open source RESTful web API framework for the Java platform. (JAX-RS 1.1) • Apache Wink - Apache Software Foundation Incubator project, the server module implements JAX-RS • WebSphere - Application Server from IBM • WebLogic - Application Server from Oracle, see notes • Apache Tuscany - (http://tuscany.apache.org/documentation-2x/sca-java- bindingrest.html) • Cuubez - framework (http://www.cuubez.com) • Everrest - Codenvy's Implementation • Jello-Framework - Java Application Framework optimized for Google App Engine. • Dropwizard, Ninja Web Framework, Play Framework, RestExpress, Restx, Spark Framework
  • 34. JAX-RS vs Spring • @Path specifies the relative path for a resource class or method. • - @RequestMapping • @GET, @PUT, @POST, @DELETE and @HEAD specify the HTTP request type of a resource. • - @RequestMapping(method) • @Produces specifies the response Internet media types (used for content negotiation). • - @RequestMapping(headers) • @Consumes specifies the accepted request Internet media types. • - @RequestMapping(headers) • @PathParam binds the method parameter to a path segment. • - @PathVariable • @QueryParam binds the method parameter to the value of an HTTP query parameter. • - @RequestVariable • @MatrixParam binds the method parameter to the value of an HTTP matrix parameter. • - @MatrixVariable • @HeaderParam binds the method parameter to an HTTP header value. • - @RequestHeader • @CookieParam binds the method parameter to a cookie value. • - @CookieValue • @FormParam binds the method parameter to a form value. • - @RequestParam • @DefaultValue specifies a default value for the above bindings when the key is not found. • - @RequestParam(defaultValue) • @Context returns the entire context of the object (for example @Context HttpServletRequest request). • - @ResponseStatus • @Provider binds the application components(data, exception mapping and context resolution) • - @ExceptionHandler
  • 36. Why use JAX-RS Implementations ? • Java 표준 API • 구현체간 쉬운 포팅 • Spring 3.2 이전에는 대안이 없었음 • 여전히 Spring에서 최신 스펙 지원 X
  • 37. Caching • Strong Caching Header - 리소스 요효시간 지정 ex) Expires, Cache-Control, max-age • Weak Caching Header - GET 요청을 날려 캐시로부터 아이템을 가져와야 할 지 판단하기 위한 정보 ex) Last-Modified, ETag
  • 38. JAX-RS Cache-Control CacheControl cacheControl = new CacheControl(); cacheControl.setMaxAge(3600); cacheControl.setPrivate(true); cacheControl.setNoCache(true); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder.cacheControl(cacheControl);
  • 39. Spring Cache-Control <mvc:annotation-driven/> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/api/**/*"/> <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor"> <property name="cacheSeconds" value="0"/> <property name="useExpiresHeader" value="true"/> <property name="useCacheControlHeader" value="true"/> <property name="useCacheControlNoStore" value="true"/> </bean> </mvc:interceptor> </mvc:interceptors> * Spring 4.2 : org.springframework.http.CacheControl
  • 40. ETags(Entity Tag) Client Server GET /users/1 200 OK ETag: “1” GET /users/1 If-None-Match: ”1” 304 Not Modified Time No content 1. 클라이언트에서 /users/1로 REST 리소스를 GET 요청 2. 서버는 Etag값(예: “1” 실제로는 MD5해쉬값)과 함께 200 OK 응답 코드 전송 3. 잠시 후 클라이언트는 동일한 리소스를 한번 더 GET으로 요청 이때 If-None-Match 헤더에 마지막으로 받은 ETag값 동봉 4. 서버는 해당 리소스의 해시값이 바뀌지 않았는지 체크하고 동일한 경우 304 Not-Modified 리턴
  • 41. JAX-RS ETag EntityTag et = new EntityTag("1"); Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(et); if (responseBuilder != null) { return responseBuilder.build(); } responseBuilder = Response.ok(); return responseBuilder.tag(et).build();
  • 43. Types of ETags • Strong ETag : 강한 ETag검증 일치로 두 리소스가 바이트 단위 까지 일치하고 Content-Language 필드도 변경되면 안됨 • Weak ETag : 약한 ETag검증 일치로 GET 요청과 ETag, IF-None-Match, 304-Not Modified만 사용 • HTTP 응답 시 Last-Modified, ETag중 하나 • Expires, Cache-Control max-age 중 하나 • 모두 설정할 경우 Etag가 Last-Modified 보다 우선, Cache-Control이 Expires 보다 우선
  • 44. Rate Limiting Pattern • 클라이언트의 요청 개수를 제한 하기 위해 HTTP 429 Too Many Request를 전달 HTTP/1.1 429 Too Many Request Content-Type: text/html Retry-After: 3600 X-RateLimit-Limit : 100 X-RateLimit-Remaining : 10 • Rety-After : 재시도 요청 대기 시간(초단위) • X-RateLimit-Limit : 일정 기간 동안 클라이언트가 요청 가능 수 • X-RateLimit-Remaining : 현재 남이 있는 요청 가능 수 Rate Limit Filter Client Server Rate Limiting Filter Request Request Response 420 Error, Retry-After, X-RateLmit-Remaining
  • 45. Tools • cURL, Postman, Advaned Rest Client • Swagger(http://swagger.io/), APIDOC(http://apidocjs.com/), I/O DOCS(http://www.mashery.com/api/io-docs) • RAML(http://raml.org/), WRML(http://www.wrml.org), VISUALDIAGRAM(https://www.visual- paradigm.com), APISTUDIO(http://apistudio.io/)

Notas do Editor

  1. Reprensentational -> 구상주의 : 구체적인 이미지나 상징을 표한하는 것(리소스를 표현한다는 의미) ROA라고도 함 네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
  2. Hessian: Caucho가 제공하는 HTTP기반 경랑 바이너리 프로토콜 Burlap : XML기반 Hessian 대안 FactoryBean, ServiceExporter제공 JAX-RPC : 원격 지원 표준 JAX-WS : JAX-RPC의 상위 버전 Java EE5, Java SE6 지원
  3. 네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
  4. 네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
  5. 네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
  6. 통신의 동작 상태를 정의하지 않고 항상 클라이언트로부터의 독립적인 request에 의해 서비스를 제공하는 서버를 stateless 서버라고 한다.
  7. Note: Pronunciations of HATEOAS vary. Some people pronounce it as "hate-ee-os," similar to "hideous," or as "hate O-A-S". People also refer to it as a hypermedia-driven system.
  8. Proxy - 웹 서버와 마찬가지로 HTTP 요청을 구성요소로 부터 받지만 웹서버와는 다르게 요청을 처리하지 않고  다른 서버, 프록시, 게이트웨이로 보내고 응답을 기다림. Gateway - HTTP와 다른 프로토콜 사이에서 중계하는 프록시.
  9. swagger-editor : 스웨거 명세를 작성하게 도와주는 텍스트 에디터. http://editor.swagger.io/#/ swagger-ui: swagger api를 문서화 해서 보여주고 직접 rest api call도 해볼 수 있음http://petstore.swagger.io/ swagger-codegen : swagger 명세를 기반으로 각 언어로 소스 뼈대를 만들어줌. Java, Scala, node 등을 지원해 줌. 등이 있고, 잘 사용하면 유용하게 사용할 수 있다. http://heidloff.net/article/usage-of-swagger-2-0-in-spring-boot-applications-to-document-apis/