SpringBoot 整合ActiveMQ

1,pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
<--引入activemq的依賴--> 
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>

2,主配置類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;

@SpringBootApplication
/*啓用jms*/
@EnableJms
public class SpringbootBasicApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootBasicApplication.class, args);
    }
    /*定義json類型的消息轉換器*/
    @Bean
    public MessageConverter messageConverter(){
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        /*這個必須配,不然會報空指針異常*/
        converter.setTypeIdPropertyName("JMSXUserID");
        return converter;
    }
}

3,生產者

import com.example.springbootbasic.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*生產者*/
@RestController
public class ProductorController {
    /*在JmsAutoConfiguration自動配置的*/
    @Autowired
    private JmsMessagingTemplate messagingTemplate;


    @RequestMapping("msg")
    public String index(User user){
        String queue="su.topic";//隊列名
        messagingTemplate.convertAndSend(queue,user);
        System.out.println("往"+queue+",發送了一個消息。。。");
        return "消息發送成功";
    }

}

4,消費者

import com.example.springbootbasic.bean.User;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

/*消費者*/
@Component
public class CustomerController {

    @JmsListener(destination="su.topic")
    public void index(User msg){
        System.out.println("接受到消息:"+msg);
    }

}
相關文章
相關標籤/搜索