RabbitMQ는 일반적으로 사용되는 AMQP 구현입니다. 이 기사는 RabbitMQ와 Spring Boot를 통합하는 간단한 자습서입니다.
ActiveMQ 서버 설치 (설치할 수도 없습니다. 설치되지 않으면 Memory MQ를 사용합니다).
스프링 부팅 프로젝트를 구축하고 종속성을 추가하십시오. 이 항목을 추가하십시오
<!-ActiveMQ 종속성 추가-> <pectionency> <groupId> org.springframework.boot </groupid> <artifactid> spring-boot-starter-activemq </artifactid> </dependency>
응용 프로그램 클래스를 추가하십시오
@springbootApplication@enablescheduling // 시간이 지정된 작업을 사용하여 메시지 보내기 공개 클래스 mqtestApplication {public static void main (string [] args) {springApplication.run (mqtestApplication.class, args); }} Application.yml을 구성하십시오
스프링 : ActiveMQ : Broker-URL : TCP : //127.0.01 : 61616 패키지 : Trust-All : True
데이터 모델을 작성하려면 보내고 소비 할 수있는 데이터 유형은 문자열, 바이트 배열,지도 <문자열,?>, 직렬화 가능한 객체입니다.
// 전송 된 메시지가 객체 인 경우 Serializable Interface Public Class TModel을 구현해야합니다. Serializable {Private STATIC Final Long SerialversionUID = -921008687184331557L; 개인 int 수; public tmodel (int count) {this.count = count; } @override public String toString () {return "tmodel [count =" + count + "]; }} 프로듀서를 구축하십시오
@ComponentPublic Class Producer {// JMStemPlate을 생산자에 주입하면이 템플릿을 통해 메시지를 보낼 수 있습니다. 개인 최종 최종 JMSTEMPLATE JMSTEMPLATE; 개인 int count = 0; @autowired public producer (jmstemplate jmstemplate) {this.jmstemplate = jmstemplate; } // 여기에서 Spring Boot의 시간이 지정된 작업을 사용하여 메시지를 보내 @scheduled (fixedRate = 1000) public void create () {// convertAndSend를 사용하여 메시지를 보내기 jmStemplate.convertAndSend ( "queue1", new tmodel (count ++)); }} 소비자를 구축하십시오
@ComponentPublic Class Consumer {@jmslistener (대상 = "queue1") public void comsume (tmodel content) {system.out.println ( "queue1에서 메시지를 남겨주세요 [" + content + "]"); }}특별 노트 : 생산자와 소비자가 다른 모듈에있는 경우, 공개 모듈에 소비 할 데이터를 추출하는 것이 가장 좋습니다. 이 프로그램은 직렬 화를 통해 객체를 직렬화하고 사로화합니다. 생산자와 소비자의 객체 모델의 직렬 버전이 일관되도록해야합니다.
프로젝트 주소 : https://github.com/ldwqh0/active-mq-spring.git
예 : RabbitMQ를 구성하고 큐를 추가하십시오
@ConfigurationPublic Class Aceue {@beanpublic queue queue () {return new queue ( "Good");}}생산자를 정의하십시오.
ActiveMQ가 활성화되면 AMQPTEMPLATE가 자동으로 생성되며 필요한 모든 곳에 주입 할 수 있습니다. 이 amqptemplate을 통해 MQ에 메시지를 보낼 수 있습니다
/*** 생산자 정의*@author lidong*/@restcontroller@restontroller ( "/test") public class sendcontroller {@autowiredPrivate amqptemplate template; @getmappingpublic string testsend () {// amqptemplate. 소비자 정의, Rabbitlistener를 지정하여 소비 대기열을 지정하십시오 (대기열 = 'Good').
@ComponentPublic Class Consumer {/*** 소비자 정의*@param message*/ @rabbitlistener (queues = "good") public void handler (string message) {system.out.println ( " + message);}}테스트를 시작하고 브라우저에 http : // localhost : 8080/테스트를 입력하여 큐에 메시지를 보냅니다. 이 열 쌍은 소비자가 처리 할 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.