Redis的发布订阅

Redis的发布订阅

一、Message类

import java.io.Serializable;

public class Message implements Serializable{
    private static final long serialVersionUID = 7792729L;
    private int id;
    private String content;
    public Message(int id, String content) {
		this.id = id;
		this.content = content;
	}
	public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

二、消息订阅类

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

import redis.clients.jedis.BinaryJedisPubSub;
import redis.clients.jedis.Jedis;

public class Subscribe extends BinaryJedisPubSub {

	/**byte[]转对象
     * @param bytes
     * @return
     * @throws Exception
     */
    public static Object bytesToObject(byte[] bytes) throws Exception{
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream sIn = new ObjectInputStream(in);
        return sIn.readObject();
    }
    //subscribe是一个阻塞的方法,在取消订阅该频道前,会一直阻塞在这,只有当取消了订阅才会执行下面的other code,参考上面代码,我在onMessage里面收到消息后,调用了this.unsubscribe(); 来取消订阅,这样才会执行后面的other code
	@Override
	public void onMessage(byte[] channel, byte[] message) {
		try {
			Message m = (Message)bytesToObject(message);
			System.out.println("id="+m.getId()+",content="+m.getContent());
			this.unsubscribe();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Subscribe su = new Subscribe();
		byte[] channel = "channel".getBytes();
    	@SuppressWarnings("resource")
    	Jedis jedis = new Jedis("10.108.169.6",6379);			
    	jedis.subscribe(su, channel);
    	System.out.println("exit");
    	jedis.disconnect();
	}
}

三、消息发布类

public class PublishDemo {

	/**对象转byte[]
     * @param obj
     * @return
     * @throws IOException
     */
    public static byte[] objectToBytes(Object obj) throws Exception{
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(obj);
        byte[] bytes = bo.toByteArray();
        bo.close();
        oo.close();
        return bytes;
    }

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		byte[] channel = "channel".getBytes();
    	Message message = new Message(1,"www1234");
    	@SuppressWarnings("resource")
    	Jedis jedis = new Jedis("10.108.169.6",6379);		
    	//清空数据库中的数据,若不删除该数据会一直存在内存中,其他的连接也能获得该数据
    	jedis.flushDB();
    	jedis.publish(channel, objectToBytes(message));
    	jedis.disconnect();

	}

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值