原文链接:http://blog.csdn.net/ado1986/article/details/39052965?utm_source=tuicool&utm_medium=referral
Redis支持发布/订阅的消息队列机制,jedis提供了Java访问redis的客户端,本文将描述如何用jedis实现简单的消息队列,并传输对象。
redis支持发布、订阅的功能,基本的命令有publish、subscribe等。在jedis中,有对应的java方法,并且只能发布字符串消息。为了传输对象,需要将对象进行序列化,并封装成字符串进行处理。将对象序列化后,只能成为字节流,如何封装成字符串是一个难点,具体可参考下面的代码。
实现三个类,一个对应publish、一个对应subscribe、一个对应要传递的对象实体类。
实体类:
[java] view plain copy- public class Bean implements Serializable {//需要实现序列化接口
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
publish类:
[java] view plain copy- public class TestPub {
- public static void main(String[] args) {
- Jedis jedis = new Jedis("127.0.0.1");
- try {
- Bean bean = new Bean();
- bean.setName("test");
- //使用ObjectOutputStream和ByteArrayOutputStream将对象转换成字节流
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(bean);
- String msg1 = baos.toString("ISO-8859-1");//指定字符集将字节流解码成字符串,否则在订阅时,转换会有问题。
- // msg1 = URLEncoder.encode(msg1, "UTF-8");
- jedis.publish("foo", msg1);
- } catch (Exception e) {
- }
- }
- }
subscribe类:
[java] view plain copy- public class TestSub {
- public static void main(String[] args) {
- Jedis jedis = new Jedis("127.0.0.1");
- JedisPubSub jedisPubSub = new JedisPubSub() {
- @Override
- public void onUnsubscribe(String channel, int subscribedChannels) {
- }
- @Override
- public void onSubscribe(String channel, int subscribedChannels) {
- }
- @Override
- public void onPUnsubscribe(String pattern, int subscribedChannels) {
- }
- @Override
- public void onPSubscribe(String pattern, int subscribedChannels) {
- }
- @Override
- public void onPMessage(String pattern, String channel,
- String message) {
- }
- @Override
- public void onMessage(String channel, String message) {
- try {
- ByteArrayInputStream bis = new ByteArrayInputStream(
- message.getBytes("ISO-8859-1"));//此处指定字符集将字符串编码成字节数组,此处的字符集需要与发布时的字符集保持一致
- ObjectInputStream ois = new ObjectInputStream(bis);
- Bean bean = (Bean) ois.readObject();
- System.out.println(bean.getName());
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- }
- }
- };
- jedis.subscribe(jedisPubSub, "foo");
- }
- }