Spring-AMQP使用和简单实例

之前写过按照官方文档学习使用RabbitMQ,了解了大概之后,我们可以开始尝试在项目里使用它。

1.前提准备

RabbitMQ,可以搭建在linux环境和windows环境。安装比较简单,这边先不赘述了。以后补上。
我们要引入jar包,给出maven

 <dependency>
      <groupId>org.springframework.amqp</groupId>
      <artifactId>spring-rabbit</artifactId>
      <version>2.0.3.RELEASE</version>
 </dependency>

版本自行选择。
开一个项目,这里是使用xml去配置。
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <description>Spring公共配置</description>
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.george"/>
    <context:annotation-config/>
    <!-- mq服务 生产者配置 -->
    <import resource="classpath:context/applicationContext-producer-mq.xml"/>
     <!-- mq服务 消费者配置 -->
    <import resource="classpath:context/applicationContext-consumer-mq.xml"/>
</beans>

准备一下properties文件,消费者和生产者都需要!
mq.properties

#参数
mq.host = 主机ip
mq.username = 用户名
mq.password = 密码
mq.port = 5672
mq.vhost = /
#消息确认
mq.publisher-confirms = true
#缓存数量,默认25
mq.channel-cache-size = 50

1.生产者

我们现在先安排生产者:
在业务代码中,我们一般都期望这种调用能够尽可能的简便。所以最好的情况就是通过注入和设置参数我们可以直接发送消息。
applicationContext-producer-mq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
         http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 消息对象json转换类 -->
    <bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />

    <!-- 配置文件位置 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath*:mq.properties" ignore-resource-not-found="true"/>

    <!-- 连接工厂配置 -->
    <rabbit:connection-factory id="connectionFactory"
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值