pom.xml
<dependencies>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.1</version>
</dependency>
</dependencies>
RedissonUtil.java
package game;
import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.redisson.codec.SerializationCodec;
import org.redisson.config.Config;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
public class RedissonUtil {
private static RedissonClient redisson;
public static void init() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
redisson = Redisson.create(config);
}
public static <T> void setSync(String key, T value) {
RBucket<T> rBucket = redisson.getBucket(key);
rBucket.set(value);
}
public static <T> T get(String key) {
RBucket<T> rBucket = redisson.getBucket(key);
return rBucket.get();
}
public static void sub() {
RTopic topic = redisson.getTopic("dw", new SerializationCodec());
topic.addListener(Car.class, new MessageListener<Car>() {
@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());
}
});
}
public static void pub() {
RTopic topic1 = redisson.getTopic("dw", new SerializationCodec());
topic1.publish(new Car(120000, "white"));
}
public static void main(String[] args) {
// 初始化redis连接
init();
// 订阅
sub();
// 发布消息
while (true) {
try {
// 发布消息
pub();
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 消息体
public static 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;
}
}
}