'개발'에 해당되는 글 35건

  1. 2016.09.06 RabbitMQ 사용하기-2
  2. 2016.09.05 RabbitMQ 사용하기-1
  3. 2016.09.01 API 모델링 및 개발 - 2
  4. 2016.08.31 API 모델링 및 개발
  5. 2016.08.17 Python Django WEB project 개발하기1

RabbitMQ 사용하기-2

개발 2016. 9. 6. 23:48

# RabbitMQ 설치하기

--------------------------------------

[참고자료](http://killins.egloos.com/3025514)


1. windows 에 RabbitMQ 설치하기

- erlang 설치

- [다운로드](http://www.erlang.org/downloads)

- 설치

                  


- 시스템 환경변수 등록

   

    - RabbitMQ 설치

    - [다운로드](http://www.rabbitmq.com/download.html)

    - 설치

         


2. RabbitMQ 설정

- management plugin 설치

- 명령어 실행

```

        cd {RabbitMQ_PATH}\sbin

        .\rabbitmq-plugins.bat enable rabbitmq_management

```

    - management admin 계정 등록

    - default 로 guest / guest 를 제공한다

    - service 재시작

    - 명령어 실행

       


3. RabbitMQ mgmt 실행 확인

- default PORT : 15672

  

4. maven dependency 설정

  

5. java client 를 이용한 queue 등록 및 획득

- QueueClient.java

- QueueClient.send();

- QueueClient.receive();

- Message.java // 메시지 큐

- RabbitmqClient.java // 큐 접속 클라이언트

        import java.io.IOException;

        import java.util.ArrayList;

        import java.util.List;

        import java.util.concurrent.TimeoutException;


        import com.rabbitmq.client.Channel;

        import com.rabbitmq.client.Connection;

        import com.rabbitmq.client.ConnectionFactory;

        import com.rabbitmq.client.ConsumerCancelledException;

        import com.rabbitmq.client.QueueingConsumer;

        import com.rabbitmq.client.ShutdownSignalException;


        public class QueueClient {


        public final static String QUEUE_NAME = "hello";


        public static void send() throws IOException, TimeoutException{

            RabbitmqClient client = new RabbitmqClient();

            Channel channel = client.getChannel();


            channel.queueDeclare(QUEUE_NAME, false, false, false, null);


            // create messages.

            List<Message> messages = new ArrayList<Message>();

            for (int i = 0; i < 10; i++) {

                messages.add(new Message(QUEUE_NAME, "Hello World! " + i));

            }


            System.out.println("ready to send.");

            for (Message m : messages) {

                channel.basicPublish(m.exchange, m.routingKey, null,

                        m.body.getBytes());

                System.out.println(" [x] Sent " + m.toString());

            }


            client.close();

        }


        public static void receive() throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException, TimeoutException{

            RabbitmqClient client = new RabbitmqClient();

            Channel channel = client.getChannel();


            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");


            QueueingConsumer consumer = new QueueingConsumer(channel);

            channel.basicConsume(QUEUE_NAME, true, consumer);


            System.out.println("ready to receive.");

            while (true) {

                QueueingConsumer.Delivery delivery = consumer.nextDelivery();

                String message = new String(delivery.getBody());

                System.out.println(" [x] Received '" + message + "'");

            }

        }


        public static void main(String[]args) throws IOException, TimeoutException, InterruptedException{


            // QueueClient.send();


            QueueClient.receive();


            }


        }


        class RabbitmqClient {

            public static String HOST = "127.0.0.1";// RabbitMQ Server.

            private Connection connection = null;

            private Channel channel = null;


            public Channel getChannel() throws IOException, TimeoutException {

                ConnectionFactory factory = new ConnectionFactory();

                factory.setHost(RabbitmqClient.HOST);

                this.connection = factory.newConnection();

                this.channel = connection.createChannel();


                return this.channel;

            }


            public void close() throws IOException, TimeoutException {

                this.channel.close();

                this.connection.close();

            }

        }


        class Message {

            public String exchange = "";

            public String routingKey = "";

            public String body = "";


            public Message(String routingKey, String body) {

                this.routingKey = routingKey;

                this.body = body;

            }


            public Message(String exchange, String routingKey, String body) {

                this.exchange = exchange;

                this.routingKey = routingKey;

                this.body = body;

            }


            public String toString() {

                if (exchange.length() > 0) {

                    return String.format("Exchange='%s', Key='%s', '%s'", exchange,

                            routingKey, body);

                } else {

                    return String.format("Key='%s', '%s'", routingKey, body);

                }

            }

        } 


'개발' 카테고리의 다른 글

Ubuntu 머신에서 다른 머신 제어하기  (0) 2016.09.09
Ubuntu 설치 후 초기 환경 세팅  (0) 2016.09.07
RabbitMQ 사용하기-1  (0) 2016.09.05
API 모델링 및 개발 - 2  (0) 2016.09.01
API 모델링 및 개발  (0) 2016.08.31
Posted by 감각적신사
,

RabbitMQ 사용하기-1

개발 2016. 9. 5. 23:06

# RabbitMQ

--------------------------------------

[참고자료](http://killins.egloos.com/3025514)


1. 소개

- 표준 AMQP (Advanced Message Queueing Protocol) 메세지 브로커 소프트웨어(message broker software) 오픈소스이다

- erlang 언어로 만들어졌을 뿐만 아니라, clustering과 failover를 위한 OTP framework로 서버가 만들어져 있다

- MQ (Message Queuing) 란

- 서로 다른 프로세스나 프로그램 사이에 메시지를 교환할때 AMQP(Advanced Message Queueing Protocol)을 이용

- AMQP는 메세지 지향 미들웨어를 위한 open standard application layer protocol 이다

- AMQP를 이용하면 다른 벤더 사이에 메세지를 전송하는 것이 가능한데 JMS (Java Message Service)가 API를 제공하는것과 달리 AMQP는 wire-protocol을 제공하는데 이는 octet stream을 이용해서 다른 네트워크 사이에 데이터를 전송할 수 있는 포멧인데 이를 사용한다

- 용도 

- 대용량 데이터를 처리하기 위한 배치 작업이나, 체팅 서비스, 비동기 데이터를 처리할때 사용한다


2. 동작

- Producer: 메시지를 보내는 Application

- Consumer: 메시지를 받는 User Application

- Publish: Producer 가 메시지를 보냄

- Subscribe: Consumer가 메시지를 수신하기 위해 Queue를 실시간으로 리스닝 하기로 만든다

- Exchange:

- Producer가 전달한 메시지를 Queue에 전달하는 역할

- 메시지가 Queue에 직접 전달되는 것이 아니라 Exchange Type이라는 속성에 정의한데로 동작

- RoutingKey: Exchange를 생성하거나 메시지를 Publish할 때 사용하는 Key, Exchange가 Queue에 메시지를 전달할지 결정하는 Key

- Queue: 메시지를 저장하는 버퍼(Queue는 Exchange에 Binding된다)

- durable 속성: 메세지를 디스크에 저장. memory에 저장하는 것은 transient라고 한다

- auto-delete 속성: 모든 consumer가 unsubscribe 하면, 해당 queue는 자동으로 없어진다

- 동일한 queue 가 들어오면 추가하지 않는다?

- Bindings: Exchange와 Queue를 연결

- Virtual Host : 웹서버의 virtual host concept과 같이, 하나의 물리적인 서버에 여러 개의 가상 서버를 만들 수 있다

- Channel : 하나의 물리적인 connection 내에 생성되는 가상 논리적인 connection들. Consumer의 process나 thread는 각자 이 channel을 통해서 queue에 연결 될 수 있다.

- Connection : 물리적인 TCP Connection, 보안이 필요할 경우 TLS(SSL) Connection을 사용할 수 있음


3. Exchange 타입

   

'개발' 카테고리의 다른 글

Ubuntu 머신에서 다른 머신 제어하기  (0) 2016.09.09
Ubuntu 설치 후 초기 환경 세팅  (0) 2016.09.07
RabbitMQ 사용하기-2  (0) 2016.09.06
API 모델링 및 개발 - 2  (0) 2016.09.01
API 모델링 및 개발  (0) 2016.08.31
Posted by 감각적신사
,

1. API 설계의 안티패턴

- GET-POST 를 이용한 터널링

- method=update 와 같은 파라미터 쿼리를 이요한 데이터 조작

- 복잡한 파라미터와 구조로 직관성 결여, 재활용성 저하

- HTTP Response code 미사용


2. API 설계 원칙

- URI 의 단순화

- api model 의 class 로 구성: /car

- 행위에 대한 정의는 좋지 않다: /getCar

- resource 간의 관계

- sub resource 표현: /user/{userID}/car/{carID}

- sub resource 간의 관계: /user/{userID}/wish/car/{carID}

- 예외-응답 코드 사용

- API 버전 관리: 

- URL: /api/v1/user , /api/v2/user

- 파라미터: /api/user?version=1 , /api/user?version=2

- 해더: "Accept-Version: 1.0" , "Accept-Version: 2.0"

- HTTP 매서드 재정의


3. API 개발 절차


'개발' 카테고리의 다른 글

Ubuntu 머신에서 다른 머신 제어하기  (0) 2016.09.09
Ubuntu 설치 후 초기 환경 세팅  (0) 2016.09.07
RabbitMQ 사용하기-2  (0) 2016.09.06
RabbitMQ 사용하기-1  (0) 2016.09.05
API 모델링 및 개발  (0) 2016.08.31
Posted by 감각적신사
,

API 모델링 및 개발

개발 2016. 8. 31. 18:22
APIs: Application Programming Interface
--------------------------------------

1. HTTP 
- **HTTP is request / response**
- HTTP  Primer
- URLs
- ![URLs](https://ed.fnal.gov/lincon/graphics/absolute_url.gif)
- protocol 
- host 
- port 
- resource path 
- query
- Header : key value
- Body : details
- HTTP Verbs
- GET : collection 이나 individual resource 획득, 생성에 관여해서는 안된다
- POST : 새로운 resource 생성
- PUT : 생성된 resource 에 대한 변경
- DELETE : 생성된 collection / resource 에 대한 삭제
- **PATCH** : PUT 과 유사하나 일부 속성을 변경할 때 주로 사용됨
- HTTP Response Code
- 2xx : SUCCESS에 관한 코드
- 200 : ok
- 201 : created
- 202 : accepted
- 204 : no content (주로 delete API 에 사용한다)
- 4xx : CLIENT_ERROR에 관한 코드 (요구 메시지가 처리할 수 없을 때)
- 400 : bad request
- 401 : unauthorized
- 403 : forbidden
- 404 : Not found
- 5xx : SERVER_ERROR에 관한 코드 (서버가 요청을 처리하는 과정에서 문제발생)
- 500 : Internal Server Error
- [reference](https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)

2. REST: REpresentational Statue Transfer
- 월드 와이드 웹과 같은 분산 하이퍼미디어 시스템을 위한 소프트웨어 아키텍처의 한 형식
- 특징
- Uniform Interface (Loose Coupling): 
- 아키텍처를 단순화시키고 작은 단위로 분리(decouple)함
- 클라이언트-서버의 각 파트가 독립적으로 개선 가능
- Client / Server 구조: 일관적인 인터페이스로 분리되어야 한다
- Stateless: 각 요청 간 Client 의 context 가 서버에 저장되어서는 안 된다 ( == 구현이 단순해진다 )
- Cacheable: WWW 에서와 같이 Client 는 response 을 caching 할 수 있어야 한다
- 클라이언트-서버 간 상호작용을 부분적으로 또는 완전하게 제거하여 scalability 및 성능 향상
- Layered System: Client 는 REST API 서버만 호출한다
- Server 내부에 다중 계층을 구성하여 로드 밸런싱, 공유 캐시, 인증, 비즈니스 을 나누어 관리할 수 있다
- --------------------------------------------
- Code on demand (optional): 자바 애플릿이나 자바스크립트의 제공을 통해 서버가 클라이언트가 실행시킬 수 있는 로직을 전송하여 기능을 확장시킬 수 있다

- 고려사항
- **transcation: 연속적 API 호출에 대한 트랜잭션을 보장하지 않는다**
- **Idempotent**
- API 호출 실패에 대한 구체적인 명시가 필요하다
- 필요의 경우, 보상 트랜잭션의 구현이 필요하다
- **실패에 대한 처리: 예외코드 / 예외메시지 를 제공한다**
- client 의 조치가 필요한 케이스
- retry / restart 등의 조치
- server 의 조치가 필요한 케이스

3. API 모델링 및 디자인
- API 모델링 steps
- step1 : Identify participants
- 사용할 object 단위로 정의해라? 
ex) system admin, customer, manager etc ...
- step2 :  Identify Activities
- object 들의 동작과 동작결과를 정의해라? : 한줄정도 요약
- step3 : Break Into Steps
- 동작을 쪼개어 순서대로 정의해라 : 요약된 한줄의 동작을 수행하는 단계를 정의
- step4 : Create Resource API Definitions
- 각 단계 에서 필요한 items 들을 정의해라
- 힌트 :
- 일반적인 개념과 같은 그룹
- db 테이블에서 사용하는 properties 가 될 수 있다
- step5 : Validate API
- API 디자인 steps
- step1. Ontology 구성
- 클래스(class), 인스턴스(instance), 관계(relation), 속성(property)
- step2. 구성원들간의 관계 정의
- Independent : 독립적으로 존재
- Dependent: 부모 resource 의 존재에 의해 생성 가능한 존재
- Associative: 독립적인 존재이지만, ...
- step3. HTTP 규격에 맞게 정의하기
- method: CRUD
- URL: 구성원
- response: API 수행결과
- step4. 프로토 타입 공유
- 실습

story : As a customer, I want to order a coffee so that the coffee shop can prepare my drick

1. modeling exercise

- step1 : Identify participants

Customer, waitress, Barista 

- step2 :  Identify Activities

Order | Customer, waitress |

Prepare Coffee | Barista | 

- step3 : Break Into Steps

Order

Select Menu | Customer

Order | Customer

Confirm Order | Customer, waitress

Prepare Coffee

Confirm Order | Barista

Make Coffee | Barista

- step4 : Find Resources

Order

menu list,  menu detail

Make Coffee

ingredient

- step5 : Validate API

Order

- Select menu list API | Customer, waitress

- Create Order API | waitress

- Confirm Order API | Customer, waitress

Make Coffee

- Get Order API | Barista

- Make Coffee | Barista

2. design exercise

Order

- Select menu list API

GET /menu | 200 OK , 500 Internal Server Error

- Create Order API

POST /order | 201 Created , 204 No Content , 400 Bad Request , 500 Internal Server Error

- Confirm Order API

POST /order/{order_id} | 200 OK , 500 Internal Server Error

Make Coffee

- Confirm Order API

GET /order/{order_id} | 200 OK , 404 Not Found , 500 Internal Server Error

- Make Coffee

POST /coffee/ | 201 Created , 204 No Content , 500 Internal Server Error 

4. 훌륭한 API 의 7가지 특징
- #1. Greate APIs "Just Work": 직관적이고 예측 가능해야한다
- #2. Greate APIs are Interactive (대화)
- Documentation is great
- Interactive documentation is better (like JAVA DOC) >> swagger 가 유용하다
- #3. Greate APIs have Examples
- should be short
- something useful
- simple and complex use case
- #4. Greate APIs are Considerate 신중한, 주의 깊은
- protocol 과 payload 를 쉽게 사용할 수 있도록 선택해야 한다 
- ex) REST vs SOAP, JSON vs XML 
- [REST와 SOAP비교] (http://greatkim91.tistory.com/79)
- #5. Greate APIs are Adoptable 채용
- 쉽게 호할 수 있도록
- high value for 비즈니스
- low pain for 통합/유지보수
- #6. Greate APIs offer Variation in Granularity
- 3 레벨
- access APIs ( row한 의 API )
- workflow APIs ( 상위레벨의 API )
- SDK APIs ( 개발 언어별로 )
- #7. Greate APIs are Consistent
- name, design, error handle, massage


'개발' 카테고리의 다른 글

Ubuntu 머신에서 다른 머신 제어하기  (0) 2016.09.09
Ubuntu 설치 후 초기 환경 세팅  (0) 2016.09.07
RabbitMQ 사용하기-2  (0) 2016.09.06
RabbitMQ 사용하기-1  (0) 2016.09.05
API 모델링 및 개발 - 2  (0) 2016.09.01
Posted by 감각적신사
,

# Python WEB Project

-------------


1. python web 프로젝트 framework 선택

    - Django

    - MVC 기반 패턴대로 개발할 수 있도록 이미 구조화 되어 있음

    - ORM(Object-Relational Mappings) 기능 지원

    - 객체와 관계형 데이터베이스 간의 매핑

        - DBMS Driver 지원 (MySQL, PostgreSQL, Oracle 등)

- Viewing, template 엔진 제공

- session 관리 기능 지원

    - flask

        - 가볍고 심플한 Framework

        - 자유도가 아주 높다 == 원하는 라이브러리와 패키지 를 개발자가 붙여야 한다


2. 개발 환경

    - ubuntu 14.04

    - python 2.7.10


3. Django download

- https://www.djangoproject.com/download/


4. Django 설치 및 간단 실행

- 압축해제 tar xvfz Django-1.10.tar.gz

- 설치

- cd /download-path/Django-1.10

- sudo python setup.py install

- admin 파일 실행

- cd /download-path/Django-1.10/django/bin 

- python django-admin.py startproject myproject .

- cd /download-path/Django-1.10/django/bin/myproject

- python manager.py runserver 0.0.0.0:8000


5. postgreSQL 설치 및 실행

- 설치

- sudo apt-get libpq-dev postgresql postgresql-contrib

- DB 접속 및 데이터베이스 생성

- sudo su - postgres # postgres 유저 로그인

- psql               # postgres cli 접속

- CREATE DATABASE myproject; # DB 생성

- USER 생성 및 권한 부여

- CREATE USER myprojectuser WITH PASSWORD 'password';

- ALTER ROLE myprojectuser SET client_encoding TO 'utf8';

- ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed';

- ALTER ROLE myprojectuser SET timezone TO 'Asia/Seoul';

- GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

       


6. django 와 postgre 연결하기

- cd /download-path/Django-1.10/django/bin/myproject/

- vi setting.py

# 추가

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.postgresql_psycopg2',

'NAME': 'myproject',

'USER': 'myprojectuser',

'PASSWORD': 'password',

'HOST': 'localhost',

'PORT': '5432',

}

}

          

- python manage.py makemigrations

- python manage.py migrate

          

7. Django 실행

- cd /download-path/Django-1.10/django/bin/myproject/

- python manage.py runserver 0.0.0.0:8000

- admin 유저 생성 및 web 접속


참고


'개발 > python' 카테고리의 다른 글

Python multiprocess vs multithread  (0) 2018.05.24
django mysql rest api project  (0) 2018.03.11
Django 프로젝트에서 batch job 돌리기  (0) 2018.01.23
Django 프로젝트  (0) 2017.11.29
Django 프로젝트 생성 및 App 만들기  (0) 2017.08.27
Posted by 감각적신사
,