spring boot 통합 Rabbit MQ

3076 단어 SSH_SSM
1. pom.xml

	org.springframework.boot
	spring-boot-starter-amqp

2. application.properties
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

3. RabbitConfig.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
	
	private static final Logger log = LoggerFactory.getLogger(RabbitConfig.class);

	@Bean
	public Queue newsQueue() {
		return new Queue("newsQueue");
	}
	
	@Bean
    public Queue news1Queue() {
        return new Queue("news1");
    }

    @Bean
    public Queue news2Queue() {
        return new Queue("news2");
    }

    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange("newsTopic");
    }

    @Bean
    public Binding bindingNews1Queue(Queue news1Queue, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(news1Queue).to(fanoutExchange);
    }

    @Bean
    public Binding bindingNews2Queue(Queue news2Queue, FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(news2Queue).to(fanoutExchange);
    }
	
}

4. 메시지 보 내기
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Producer {

	private static final Logger log = LoggerFactory.getLogger(Producer.class);
	
	@Autowired
	private AmqpTemplate rabbitTemplate;
	
	public void sendNewsQueue(String msg) {
		rabbitTemplate.convertAndSend("newsQueue", msg);
	}
	
	//          
	public void sendStockTopic(String msg) {
		rabbitTemplate.convertAndSend("newsTopic", "", msg);
	}

}

5. 소식 수신
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class News1Consumer {

	private static final Logger log = LoggerFactory.getLogger(News1Consumer.class);
	
	public static long count = 0;
	
	@RabbitHandler
	@RabbitListener(queues = "news1", containerFactory = "rabbitListenerContainerFactory")
    public void process(String msg) {
		log.info("msg:" + msg);
    }
	
}

좋은 웹페이지 즐겨찾기