Redis发布订阅传对象[消息队列](基于Redisson)

定义一个基本类(必须继承自Serializable,否则无效)

public class Car  implements Serializable {
private static final long serialVersionUID = -1L;

private double price;
private String colour;

public Car(double price, String colour){
    this.price = price;
    this.colour = colour;
}

public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getColour() {
    return colour;
}
public void setColour(String colour) {
    this.colour = colour;
}

@Override
public String toString(){
    return colour +"car costs $"+price;
}

}

1.订阅消息:

public static void main(String[] args) {
    RedissonClient redisson = null;
    try{
        Config config = new Config();
        config.useSingleServer().setAddress("127.0.0.1:6379");

        redisson = Redisson.create(config);

        RTopic topic = redisson.getTopic("dw",new SerializationCodec());
        topic.addListener(Car.class, new MessageListener() {
            @Override
            public void onMessage(CharSequence charSequence, Car car) {
                System.out.println("onMessage:"+charSequence+"; Thread: "+Thread.currentThread().toString());
                System.out.println(car.getColour()+" price : "+car.getPrice());
            }
        });


    }
    catch (Exception ex){
        System.out.println(ex.getMessage());
    }
    finally {

    }
}

2.发布消息:

public static void main(String[] args) {
    RedissonClient redisson = null;
    try{
        Config config = new Config();
        config.useSingleServer().setAddress("127.0.0.1:6379");

        redisson = Redisson.create(config);

        RTopic topic1 = redisson.getTopic("dw", new SerializationCodec());
        topic1.publish(new Car(120000,"white"));
        topic1.publish(new Car(100000,"black"));
    }
    catch (Exception ex){
        System.out.println(ex.getMessage());
    }
    finally {
        redisson.shutdown();
    }
}

先运行订阅消息的main,再运行发布消息的main。
然后看订阅消息的控制台,显示:

Redis发布订阅传对象[消息队列](基于Redisson)_第1张图片

看运行结果,每次有新消息过来,都会开个新线程去跑的,这点要注意。

相关链接
https://www.jianshu.com/p/cb493e65fd35

https://blog.csdn.net/yupi1057/article/details/80877248

https://blog.csdn.net/he37176427/article/details/84973508

Redis发布订阅传对象[消息队列](基于Redisson)_第2张图片

欢迎关注微信公众号:程序猿微刊,更多技术文章持续更新中

你可能感兴趣的:(【Redis】)