티스토리 뷰

Test & ProtoTyping

Rabbitmq Topic 간단 예제

까오기 2020. 4. 6. 09:59

Rabbitmq, Toppic으로 보내고 받는 간단예제입니다. 

보내고 받을 때 Queue name과 routing key 설정 하는 부분만 주의 깊게 보면 될거 같습니다.  

rabbitmq 설치 관련 내용은 생략하고 설치된 mq에 간단하게 보내고 받는 것만 예제로 만들어 봤습니다. 

 

Rabbitmq 설치하기 - mac os 

Homebrew 설치하는 법은 생략합니다. 

Brew install rabbitmq

설치 후 메시지 

To start redis:
  brew services start redis
Or, if you don't want/need a background service you can just run:
  /usr/local/opt/redis/bin/redis-server /usr/local/etc/redis.conf
==> Summary
  /usr/local/Cellar/redis/6.2.5: 14 files, 2.0MB
Removing: /usr/local/Cellar/redis/6.2.4... (13 files, 2.0MB)
==> Checking for dependents of upgraded formulae...
==> No broken dependents found!
==> Caveats
==> rabbitmq
Management Plugin enabled by default at http://localhost:15672

To start rabbitmq:
  brew services start rabbitmq
Or, if you don't want/need a background service you can just run:
  /usr/local/opt/rabbitmq/sbin/rabbitmq-server
==> redis
To start redis:
  brew services start redis
Or, if you don't want/need a background service you can just run:
  /usr/local/opt/redis/bin/redis-server /usr/local/etc/redis.conf

위 메시지 중에 rabbitmq 관련 정보만 알고 있으면 됩니다. 

 

설치 위치

/usr/local/opt/rabbitmq/sbin/

실행 

/usr/local/opt/rabbitmq/sbin/rabbitmq-server 
// 또는 아래 가능 
brew services start rabbitmq

 

관리자 사이트 접속정보 

http://localhost:15672/

계정 추가 

/usr/local/opt/rabbitmq/sbin/rabbitmqctl add_user [아이디] [패스워드]

user tag 설정

/usr/local/opt/rabbitmq/sbin/rabbitmqctl set_user_tags [아이디] [권한]

예제 

/usr/local/opt/rabbitmq/sbin/rabbitmqctl set_user_tags admin administrator 
/usr/local/opt/rabbitmq/sbin/rabbitmqctl set_permissions admin ".*" ".*" ".*"
## 유저리스트 확인
/usr/local/opt/rabbitmq/sbin/rabbitmqctl list_users
퍼미션 확인
/usr/local/opt/rabbitmq/sbin/rabbitmqctl list_permissions
Listing permissions for vhost "/" ...
user	configure	write	read
guest	.*	.*	.*
admin	.*	.*	.*

 

설치 후 샘플 프로젝트 만들기 

 

What you'll need

  • 대략 15분 정도 소요
  • eclipse 
  • jdk 1.8 or later
  • Gradle
  • spring boot

Work flow

1. 프로젝트생성

2. build.gradle 수정 

3. Source Coding 

4. Test 

 

1. 기본 Spring boot 프로젝트를 생성합니다.  

2. build.gradle 수정

plugins {
	id 'org.springframework.boot' version '2.2.6.RELEASE'
	id 'io.spring.dependency-management' version '1.0.9.RELEASE'
	id 'java'
	id 'war'
}

group = 'eblo.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
    implementation 'com.fasterxml.jackson.core:jackson-databind'
   
    implementation 'org.springframework.boot:spring-boot-starter-amqp'
    testImplementation('org.springframework.boot:spring-boot-starter-test')
    testImplementation 'org.springframework.amqp:spring-rabbit-test'
}

test {
	useJUnitPlatform()
}

3. Source Coding 

RabbitMQConfig.java

@Configuration
public class RabbitMQConfig {

    @Bean
    public TopicExchange topic() {
        return new TopicExchange("amq.topic");
    }

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
        return rabbitTemplate;
    }
}

Email.java

public class Email {

    private String to;
    private String body;

    public Email() {
    }

    public Email(String to, String body) {
      this.to = to;
      this.body = body;
    }

    public String getTo() {
      return to;
    }

    public void setTo(String to) {
      this.to = to;
    }

    public String getBody() {
      return body;
    }

    public void setBody(String body) {
      this.body = body;
    }

    @Override
    public String toString() {
      return String.format("Email{to=%s, body=%s}", getTo(), getBody());
    }

  }

EmailMsgSender.java

@Service
public class EmailMsgSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private TopicExchange topic;

    public void sendEmail(String routingKey, Email email){
        rabbitTemplate.convertAndSend(topic.getName(), routingKey, email);
    }

}

Receiver.java

@Component
public class Receiver {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue,
            exchange = @Exchange(value = "amq.topic", type = "topic", durable = "true"), //
            key = "test"))
    public void handleMsg1(Email in) {
        System.out.println(in.toString());
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "kkaok", durable = "true"),
            exchange = @Exchange(value = "amq.topic", type = "topic", durable = "true"), //
            key = "test.0001"))
    public void handleMsg2(Email in) {
        System.out.println(in.toString());
    }

}

Receiver에서는 "test", "test.0001"로 받게 설정을 합니다. 

 

application.properties

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=password

 

4. Test

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailMsgSenderTest {

    @Autowired
    private EmailMsgSender emailMsgSender;
    
    @Test
    public void testSendMsg() {
        
        Email email = new Email("info@example.com", "Hello");
        emailMsgSender.sendEmail("test.0001", email);
    }
    
}

 

Git : https://github.com/kkaok/examples/tree/master/rabbitmqExample

'Test & ProtoTyping' 카테고리의 다른 글

Activemq 간단 예제  (0) 2020.04.03
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함