카테고리 없음

Rabbit MQ 스터디 (2) 210706 -

Khookie 2021. 7. 6. 14:16

래빗엠큐를 이용하여 전송하는 메시지의 포맷을 json 등으로 해주어야 하는 이유는

String 등으로 사용할 시 비효율적이기 때문에 규격을 통일하기 위함이다

 

출처 : [RabbitMQ] JSON Message Format 사용하기 - 1 (tistory.com)

 

[RabbitMQ] JSON Message Format 사용하기 - 1

이번 글에서는 RabbitMQ에서 사용하는 메세지 포맷인 JSON에 대해 알아보도록 하겠습니다. 0. 왜 JSON을 사용하는가? RabbitMQ는 메세지 Format으로 어떠한 String 형식도 허용합니다. 하지만 이러한 자유도

minholee93.tistory.com

 

나는 자바언어로 래빗엠큐를 사용하려고 공부중인데

자바에는 JSON 을 위한 라이브러리로 JACKSON 과GSON, json-simple 등 이 있다.

 

자바 객체를 json 형식 스트링으로 바꿀 수가 있게 된다

 

제이슨이란 

{"name2": 50, "name3": "값3", "name1": true} 이런 형식의 포맷이다 

 


rabbitmq 공식사이트에 있는 튜토리얼에서 내가 시도하고자 하는

exchange 타입인 topic 튜토리얼이 있다

 

 


 

(rabbit mq) 자바 client공식 문서 

Overview (RabbitMQ Java Client 5.12.0 API)

 

Overview (RabbitMQ Java Client 5.12.0 API)

The client API proper: classes and interfaces representing the AMQP connections, channels, and wire-protocol framing descriptors.

rabbitmq.github.io


래빗엠큐 서버를 좀 더 살펴봐야겠다

 

이렇게 하면 선택한 큐에 메시지가 publish 된다

 

큐를 만드는 인터페이스도 있다

 

바인딩도 할 수 있고

 

익스체인지를 선택하고 메시지를 퍼블리쉬할 수 있다

 

 

 

이곳에서 전송하는 메시지 properties 에 콘텐츠 타입이 있다

 


 

자바 프로그램에서 래빗엠큐를 이용해

서버에서 메시지 전송시에  json형식으로 변환을 시키고 싶은데

스프링으로 구현하는것 말고는 예제가 잘 나오지 않는다

 

(스프링으로 구현시 엔티티 클래스를 만들고 겟터 셋터를 만든후 ,

String json = objectMapper.writeValueAsString(엔티티객체);

rabbitTemplate.convertAndSend("q.employee", json);

이런식으로 사용하여 파싱하는 동시에 전송을 한다

객체 -> json 스트링 - >json)

 

원래 래빗엠큐와 연동이 되는 java 포맷팅 은 없는건가..

 

일단 json 파싱을 통해 구현을 해보도록 해야겠다 

Java에서 문자열을 JSON 객체로 변환 | Delft Stack

 

Java에서 문자열을 JSON 객체로 변환

이 튜토리얼은 Java에서 문자열을 json 객체로 변환하는 방법을 설명합니다.

www.delftstack.com

 

위 링크 내용에서 

String json_str = "{\"name\":\"John\", \"age\":21 , \"place\":\"Nevada\"}";

이부분의 john , 21 과 값은 value 값 부분을 변수로 입력받아서 사용하면 되지 않을까 

 

클라이언트에서 메시지를 받을때 

json 파싱을 하는 부분을 먼저 구현하는게 좋을 거 같다

 

Overview (RabbitMQ Java Client 5.12.0 API)

 

Overview (RabbitMQ Java Client 5.12.0 API)

The client API proper: classes and interfaces representing the AMQP connections, channels, and wire-protocol framing descriptors.

rabbitmq.github.io

이 문서에 json 패키지도 있다

 

 

JsonRpcClient (RabbitMQ Java Client 5.7.3 API) (javadoc.io)Java Source Code: com.rabbitmq.tools.jsonrpc.JsonRpcClient (javased.com)

 

Java Source Code: com.rabbitmq.tools.jsonrpc.JsonRpcClient

package com.rabbitmq.tools.jsonrpc;  import java.io.IOException;  import java.lang.reflect.InvocationHandler;  import java.lang.reflect.Method;  import java.lang.reflect.Proxy;  import java.util.HashMap;  import java.util.Map;  import java.u

www.javased.com

 

JsonRpcClient (RabbitMQ Java Client 5.7.3 API)

JSON-RPC is a lightweight RPC mechanism using JSON as a data language for request and reply messages. It is rapidly becoming a standard in web development, where it is used to make RPC requests over HTTP. RabbitMQ provides an AMQP transport binding for JSO

javadoc.io



공식문서 

콘슈머 

Consumers — RabbitMQ

 

Consumers — RabbitMQ

Consumers This guide covers various topics related to consumers: and more. The term "consumer" means different things in different contexts. In general in messaging a consumer is an application (or application instance) that consumes messages. The same app

www.rabbitmq.com

unsubscribing 등등

 

기타 공식문서

Documentation: Table of Contents — RabbitMQ

 

Documentation: Table of Contents — RabbitMQ

Documentation: Table of Contents This page summarises the available RabbitMQ documentation for the current release, 3.8.4. Installation See the Downloads and Installation page for information on the most recent release and how to install it. Tutorials See

www.rabbitmq.com

 

 


교훈 

남의 글보다 공식문서를 제일 먼저 살펴보자

Uses of Package com.rabbitmq.tools.jsonrpc (RabbitMQ Java Client 5.12.0 API)

 

Uses of Package com.rabbitmq.tools.jsonrpc (RabbitMQ Java Client 5.12.0 API)

JSON-RPC client and server classes for supporting JSON-RPC over an AMQP transport.

rabbitmq.github.io

JSON 관련 패키지

 

 

참고하기

RabbitMQ Tutorial - 6. RPC - 하루에 하나씩..... (tistory.com)

 

RabbitMQ Tutorial - 6. RPC

Remote Procedure Call (RPC) 두번째 튜토리얼에서 다수의 작업자들사이에 시간이 소요되는 업무에 대해서 분산처리하는 Work Queue에 대한 사용법에 대해서 배웠습니다. 원격 컴퓨터에서 함수를 호출하

kimseunghyun76.tistory.com

 

https://okky.kr/article/758734?note=2055557 

 

OKKY | [rabbitMQ] java에서 메시지 파싱하기 질문드립니다 :)

안녕하세요! rabbitMQ를 공부중에 잘 이해가 되지 않는 부분이 생겨 질문을 드립니다! maven을 통해서 메시지 발행과 구독예제를 풀어보았는데 이것을 응용해서 구독한 메시지를 파싱한뒤 DB에 저장

okky.kr


래빗엠큐의 기본 설정

 

RabbitMQ 기본 포트 - 5672

RabbitMQ 대시보드 포트 - 15672

RabbitMQ 아이디 - guest

RabbitMQ 비밀번호 - guest

출처:[AMQP][RabbitMQ]RabbitMQ그리고 Work Queue의 사용법 - (3) :: Kamang's IT Blog (tistory.com)

 

[AMQP][RabbitMQ]RabbitMQ그리고 Work Queue의 사용법 - (3)

참고 [AMQP][RabbitMQ]RabbitMQ를 사용하는 이유와 설치방법 - (1) [AMQP][RabbitMQ]RabbitMQ아주 기초적이게 사용하기 - Java(feat.Hello World!) - (2) https://www.rabbitmq.com/tutorials/tutorial-two-java...

kamang-it.tistory.com

 

 

 

 



07.08

 

모든 메시지는 Queue 로 직접 전달되지 않고, 반드시 Exchange 에서 먼저 받는다. 그리고 Exchange Type  Binding 규칙에 따라 적절한 Queue 로 전달된다. 

 

익스체인지 타입을 바꾸기

 

우선 익스체인지 타입에 이름을 붙여  선언

channel.exchangeDeclare("logs", "fanout");

 publish 발행할때 인자로 지정한 이름의 익스체인지를 넣는다

channel.basicPublish( "logs", "qname", null, message.getBytes());

//퍼블리쉬 
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); 

//채널.베이직 퍼블리쉬(익스체인지 타입,큐이름,프로퍼티 설정,스트링을 바이트로 바꾸어)

 

바인딩 튜토리얼  학습중 

토끼MQ 튜토리얼 - 라우팅 — 토끼MQ (rabbitmq.com)

channel.queueBind(queueName, EXCHANGE_NAME, "black");

// 채널.큐바인드( 큐네임, exchange name, 라우팅키)

 

 


RabbitMQ tutorial - Topics — RabbitMQ

 

RabbitMQ tutorial - Topics — RabbitMQ

Topics (using the Java client) Prerequisites This tutorial assumes RabbitMQ is installed and running on localhost on the standard port (5672). In case you use a different host, port or credentials, connections settings would require adjusting. Where to get

www.rabbitmq.com

 

토픽 익스체인지 타입 으로 구현해보기

 

토픽 익스체인지는 임의적인 라우팅키를 가질 수 없다

 it must be a list of words, ‎점으로 구뷴된 단어여야 함

예 > "stock.usd.nyse", "nyse.vmw", "quick.orange.rabbit". 

뭐든 가능하지만 255 bytes.로 제한된다 

 

 

direct 익스체인지와 유사한 로직을 갖는다

 

 

라우팅키 1 을 바인딩키로 가진 모든 큐로 메시지를 전송한다.

큐 하나는 여러개의 바인딩 키를 가질 수 있다

 

 

바인딩 키에는 특수한 경우가 적용된다

 

  • * (star) can substitute for exactly one word.
  • # (hash) can substitute for zero or more words. (자유도 가 높은 기호 )
  • (제로가 가능하냐 안하냐, dots 로 구분한 word 가 더 있을 수 있느냐 없느냐로 구별하는)

 

라우팅 키 -> 

<speed>.<colour>.<species> 등으로 바인딩할 형식을 지정하고 사용한다 

 

Q1 는 "*.orange.*" 바인딩 키로 바인딩 합니다.

Q2 는 "*.*.rabbit" 과 "lazy.#" 으로 바인딩 합니다.

 



"quick.oragne.rabbit"으로 라우팅 키를 갖는 메세지는 두개의 큐에 전달될겁니다.

"lazy.oragne.elephant" 메시지 역시 두개의 큐에 전달될것입니다.

다른 한편 "quick.orange.fox"는 첫번째 큐에 가고, "lazy.brown.fox" 는 두번째 큐에만 갑니다.

"lazy.pink.rabbit"은 두번째큐에만 한번 갑니다. 비록 두개의 바인딩에 매칭되었어도 말이죠

"quick.brown.fox"은 어떤 바인딩과도 매칭되지 않았기에, 버려질겁니다.

 

 

1. 큐가 "#"(hash) 바인딩 키를 바인딩하면, 라우팅 키를 무시하고, 모든 메시지를 받을 겁니다. - (fanout Exchange  같이.)

 

2. 특수문자 "*"(star) 와 "#"(hash) 을 바인딩에 사용하지 않았을땐 - (direct Exchange와 같이 행동.)

출처: https://kimseunghyun76.tistory.com/427 [하루에 하나씩.....]



출처: https://kimseunghyun76.tistory.com/427 [하루에 하나씩.....]

RabbitMQ Tutorial - 5. Topics - 하루에 하나씩..... (tistory.com)

 

RabbitMQ Tutorial - 5. Topics

Topics : Receiving messages based on a pattern (topics) 이전 장에서는 우리 로깅 시스템을 발전시켰습니다. 오직 더미 방송하는 능력의 fanout Exchange를 사용하는 대신에 direct Exchange를 사용했고, 로그..

kimseunghyun76.tistory.com


0709

 

json포맷팅 툴 계속 찾는중

 

The Blas from Pas: JSON messages with RabbitMQ

 

JSON messages with RabbitMQ

Using JSON message solution in RabbitMQ gives you something that's a bit more friendly in polyglot systems, and leaves your application with...

theblasfrompas.blogspot.com

 

이것이 자바를 이용한 json 툴인거 같다

 

근데 사용한 클래스의 공식 링크가 닫힌거 보면 이제 못쓰는거 같다...

 

RabbitMQ - Send a JSON message - Stack Overflow

 

RabbitMQ - Send a JSON message

I send the following message with content type application/json: However whene i get messages from the same RabbitMQ Web console, it shows the payload as String. What am I doing wrong? Or am I

stackoverflow.com

JSON과 바디 직렬화 사용 - RabbitMQ 쿡북 (packtpub.com)

 

Using body serialization with JSON - RabbitMQ Cookbook

In AMQP the messages are opaque entities; AMQP does not provide any standard way to encode/decode them.

subscription.packtpub.com

 

 


팬아웃 익스체인지 타입 튜토리얼 공부

- 브로드 캐스트 

 

큐 네임이 의미가 없어지기 때문에

임의의 큐 네임을 부여받는 코드 

 

이때 임시 부여받는 큐 네임 amq.gen-JzTY20BRgKO-HjmUJj0wLg과  같은 모습

String queueName = channel.queueDeclare().getQueue();

로그를 만들기 위해

Secondly, once we disconnect the consumer the queue should be automatically deleted.

In the Java client,  queueDeclare() 에서 파라미터를 제공하지 않으면 we create a non-durable, exclusive, autodelete queue with a 생성된 네임


0713

 

컴파일하려면 다음을 수행합니다.

파일 두개

javac -cp $CP ReceiveLogsTopic.java EmitLogTopic.java

 

모든 로그를 받으려면 다음을 수행합니다. (리시브)

java -cp $CP ReceiveLogsTopic "#"

시설에서 모든 로그를 수신하려면 "":

java -cp $CP ReceiveLogsTopic "kern.*"

또는"중요한" 로그에 대해서만 듣고 싶다면:

java -cp $CP ReceiveLogsTopic "*.critical"

여러 바인딩을 만들 수 있습니다.

 

java -cp $CP ReceiveLogsTopic "kern.*" "*.critical"

그리고 라우팅 키"kern.critical"유형으로로그를 방출하려면:

 

java -cp $CP EmitLogTopic "kern.critical" "A critical kernel error"

 

지금까지 인터페이스를 이용해 래빗엠큐 서버를 이용했는데

아규먼트 (옵션값) 을 넣기위해 코맨드 창을 사용해 봤는데 잘 되지 않고 있다...

어렵당'

개발환경 이외에서 자바어플을 사용하는 방법은아직 학습하지 않았다

eclipse java exe compile 이런걸 검색해ㅓ야 할지도..?

 

 

 

 

ㄹ개발환경에서와는 다른듯 하다

라이브러리를 인식할 수 있는 곳이 아닌것 같다

 

 

 

임시로 개발환경 상에서 argument 를

rou msg msg 로 입력을 해서 원하는 결과가 나왔다

 

참고한 블로그에서 사용한대로 사용했지만

slf4j 로드 패일 경고가 신경쓰였는데

topic receive 할 때 역시 이부분에서 가로막는다

 

경고문의 링크를 따라가면 

이런 내용이 있다 

 

 

권고대로 slf4j-simple 를 다운받아 lib 폴더에 넣어주었더니 오류가 해결된다

Maven Repository: org.slf4j » slf4j-simple » 1.7.25 (mvnrepository.com)

 

 

 

이클립스에서 실행 할 때 

-> 발행하는 소스를 실행후 , 리시브 소스를 실행해서 큐가 만들어지면 접속을 하게 하여

-> 그 다음 다시 발행 소스를 실행하여 argument 가 입력되어 메시지가 전송되도록 만들었다