RabbitMq在spring boot中集成和应用

具体如果安装rabbitmq在本例子中不涉及,主要讲解在springboot中如果发送和接收rabbitmq消息。

1.添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>

2.spring-rabbitmq 配置
本示例中使用了maven的filter
开发环境:
#rabbitMq配置
spring.rabbitmq.addresses=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
spring.rabbitmq.exchange=site
spring.rabbitmq.createTopic=dev.gov.site.createormodify
spring.rabbitmq.changeTopic=dev.gov.site.statuschange

在application.properties文件中:
#rabbitMq配置
spring.rabbitmq.addresses=@spring.rabbitmq.addresses@
spring.rabbitmq.port=@spring.rabbitmq.port@
spring.rabbitmq.username=@spring.rabbitmq.username@
spring.rabbitmq.password=@spring.rabbitmq.password@
spring.rabbitmq.virtual-host=@spring.rabbitmq.virtual-host@
spring.rabbitmq.exchange=@spring.rabbitmq.exchange@
spring.rabbitmq.createTopic=@spring.rabbitmq.createTopic@
spring.rabbitmq.changeTopic=@spring.rabbitmq.changeTopic@

3.使用java配置rabbitmq具体细节

@Configuration
@ComponentScan("com.trs.comms.amqp")
@ConfigurationProperties(prefix = "spring.rabbitmq")
public class CommsAmqpAutoConfiguration {

    private String exchange;
    private String createTopic;
    private String changeTopic;

    //构造ConnectionFactory 
    @Bean
    @ConfigurationProperties(prefix = "spring.rabbitmq")
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setPublisherConfirms(Boolean.TRUE);
        return factory;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory());
    }

    //指定从哪个exchange接收数据
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(exchange);
    }

    // 持久化队列
    @Bean
    public Queue queue() {
        return new Queue("site", true);
    }

    //绑定队列,并接收指定topic的数据
    @Bean
    public Binding bindingCreate() {
        return BindingBuilder.bind(queue()).to(topicExchange()).with(createTopic);
    }

    @Bean
    public Binding bindingChange() {
        return BindingBuilder.bind(queue()).to(topicExchange()).with(changeTopic);
    }

    //设置监听
    @Bean
    public SimpleMessageListenerContainer messageContainer(ConnectionFactory connectionFactory, AmqpConsumer amqpConsumer) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(queue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        //设置监听器,执行具体的业务
        container.setMessageListener(amqpConsumer);
        return container;
    }

    public void setExchange(String exchange) {
        this.exchange = exchange;
    }

    public void setCreateTopic(String createTopic) {
        this.createTopic = createTopic;
    }

    public void setChangeTopic(String changeTopic) {
        this.changeTopic = changeTopic;
    }
}

4.具体监听器:

/**
 * Description: 消息监听
 */
@Component
public class AmqpConsumer implements ChannelAwareMessageListener{

    private static final Log logger = LogFactory
            .getLog(AmqpConsumer.class);

    private final AmqpSiteService amqpSiteServiceImpl;

    @Autowired
    public AmqpConsumer(AmqpSiteService amqpSiteServiceImpl) {
        this.amqpSiteServiceImpl = amqpSiteServiceImpl;
    }


    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            //具体业务
            amqpSiteServiceImpl.doWithSite(new String(message.getBody(), "UTF-8"));

//手动应答,告诉rabbitmq我业务执行完成,消息可以丢弃了
           channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.info("站点同步成功!");
        } catch (Exception e) {
            throw new RuntimeException("站点同失败!!" + e);
        }
    }
}

5.测试用例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CommsISearchConfiguration.class)
public class AmqpTest {

    @Autowired
    public RabbitTemplate rabbitTemplate;

    @Test
    public void testSend() {
        String siteData = "{" +
                "\"TYPE\": 11," +
                "\"DATA\":{" +
                "\"HASCHILDREN\":\"true\"," +
                "\"OPERTIME\":\"\"," +
                "\"CRTIME\":\"2017-06-14 19:22:05\"," +
                "\"MEDIATYPE\":\"1\"," +
                "\"TRUENAME\":\"刘珍华\"," +
                "\"ISSUBSCRIBE\":\"1\"," +
                "\"STATUS\":\"0\"," +
                "\"DATAPATH\":\"chengdushi1\"," +
                "\"MPID\":\"89011234567890\"," +
                "\"SCHEDULE\":\"0\"," +
                "\"CHNLOUTLINETEMP\":\"641\"," +
                "\"ISDISTRIBUTABLE\":\"1\"," +
                "\"SITENAME\":\"成都市\"," +
                "\"OUTLINETEMPLATE\":\"250\"," +
                "\"ATTRIBUTE\":\"PUBLISHLIMIT=&PUBSTARTDATE=\"," +
                "\"CHNLDATAPATH\":\"chengdushi2\"," +
                "\"PUBLISHPRO\":\"1\"," +
                "\"SITEORDER\":\"188\"," +
                "\"CLASSIFICATIONID\":\"95\"," +
                "\"SITEID\":\"176\"," +
                "\"LASTMODIFYTIME\":\"2017-08-31 16:00:35\"," +
                "\"SITETYPE\":\"4\"," +
                "\"VIEWINFOID\":\"111\"," +
                "\"DETAILTEMPLATE\":\"446\"," +
                "\"SITEDESC\":\"成都市\"," +
                "\"ISMOBILE\":\"0\"," +
                "\"PARENTID\":\"0\"," +
                "\"ISPUSHABLE\":\"1\"," +
                "\"CRUSER\":\"dev\"" +
                "}" +
                "}";

        rabbitTemplate.convertAndSend("site", "dev.gov.site.createormodify", siteData);
    }

}
展开阅读全文

没有更多推荐了,返回首页