现在java项目,貌似spring是必备的啦.而spring对于流行的中间件之类都有支持. rabbitmq当然也不例外.
这个整合网上的例子也挺多.不过大部分都是最简单的一个demo,连consumer这里接收对象我都找了半天没找到.
下面直接上代码了.
第一步当然是引入依赖的jar了
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
第二步,配置文件
<bean id="receiveLitener" class="com.dingcheng.rabbitmq.ReceiveLitener" />
<bean id="sendService" class="com.dingcheng.rabbitmq.SendService" />
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter" />
<rabbit:connection-factory id="connectionFactory"
host="localhost" username="admin" password="123456"/>
<rabbit:admin connection-factory="connectionFactory" />
<rabbit:queue name="queue.hello" /><!-- 这里多个只能分开写,不能用逗号隔开 -->
<!-- 给模板指定转换器 -->
<rabbit:template id="amqpTemplate" exchange="mq-exchange" connection-factory="connectionFactory" message-converter="jsonMessageConverter"/>
<!-- 这一段可以不写 -->
<rabbit:direct-exchange name="mq-exchange"
durable="true" auto-delete="false" id="mq-exchange">
<rabbit:bindings>
<rabbit:binding queue="queue.hello" key="queue.hello" />
</rabbit:bindings>
</rabbit:direct-exchange>
<!-- 配置consumer, 监听的类和queue的对应关系 -->
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto" >
<!-- 下面的queue可以写多个 用,号隔开 -->
<rabbit:listener queues="queue.hello" ref="receiveLitener"/>
</rabbit:listener-container>
这个配置文件也是比较简单,里面有些属性没设置.等以后深入用到再说.
第三步,编写生产者的代码
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
public class SendService {
@Autowired
private AmqpTemplate amqpTemplate; //消息推送
public void send(Person p) {
//这里会按xml中配置的convert方式转换对象
amqpTemplate.convertAndSend("mq-exchange","queue.hello", p);
}
}
第四步,编写消费者的代码
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class ReceiveLitener implements MessageListener {
@Override
public void onMessage(Message msg) {
Person p = JsonUtil.toBean(new String(msg.getBody()), Person.class);
System.out.println(p);
//如果用下面这个接收消息,不能放在这里面,否则接收到的是参数msg的下一条消息
// amqpTemplate.receiveAndConvert("queue.hello");
}
}
消费者主要是实现了MessageListener接口
这里要注意: 如果是实现MessageListener接口,在onMessage方法内,不能再使用amqpTemplate.receive()的一系列方法进行接收.
所以需要我们自己把msg.getBody()的内容转换为对象.
(如果想使用amqpTemplate.receiveAndConvert()方法转换对象,就需要自己起个线程来接收消息了)
第五步,测试
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.dingcheng.rabbitmq.Person;
import com.dingcheng.rabbitmq.SendService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context.xml"})
public class SendTest {
@Autowired
private SendService sendService;
@Test
public void test(){
Person p = new Person();
p.setName("小明");
p.setAge(1);
p.setBirthday(new Date());
sendService.send(p);
}
}
运行结果
Person [name=小明, age=1, birthday=Thu Nov 17 20:28:33 CST 2016]
下面是用到的Person 和 JsonUtil 类的代码
import java.util.Date;
public class Person {
private String name;
private Integer age;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonUtil {
private final static Log logger = LogFactory.getLog(JsonUtil.class);
private static ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES,true);
objectMapper.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE,true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
}
/**
*obj 转 json
* @param obj
* @return
*/
public static String toJson(final Object obj) {
String json = null;
try {
json = objectMapper.writeValueAsString(obj);
} catch (Exception e) {
logger.error("object 转 json 出错",e);
}
return json;
}
/**
* json 转 obj
* @param json
* @param clazz
* @return
*/
public static <T> T toBean(final String json, final Class<T> clazz) {
T t = null;
try {
t = objectMapper.readValue(json, clazz);
} catch (Exception e) {
logger.error("json 转 obj 出错",e);
}
return t;
}
}
源码下载地址 http://download.youkuaiyun.com/detail/qq315737546/9686056