玩转Redis!非常强大的Redisson分布式集合,少写60%代码
在Redis中,我们可以使用Redisson框架来操作Redis。Redisson提供了分布式的Java集合,例如分布式Map,分布式List,分布式Set等,这些集合都可以跨多个Redis实例进行水平扩展。
以下是一些使用Redisson进行操作的示例:
- 使用分布式RMap:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RMap<String, SomeObject> map = redisson.getMap("anyMap");
map.put("key1", new SomeObject());
SomeObject obj = map.get("key1");
- 使用分布式RSet:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RSet<SomeObject> set = redisson.getSet("anySet");
set.add(new SomeObject());
set.contains(new SomeObject());
- 使用分布式RQueue:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RQueue<SomeObject> queue = redisson.getQueue("anyQueue");
queue.offer(new SomeObject());
SomeObject obj = queue.poll();
- 使用分布式RTopic:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RTopic<SomeObject> topic = redisson.getTopic("anyTopic");
topic.publish(new SomeObject());
topic.addListener(new MessageListener<SomeObject>() {
@Override
public void onMessage(String channel, SomeObject message) {
// handle new message
}
});
- 使用分布式RLock:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("anyLock");
lock.lock();
try {
// do your work
} finally {
lock.unlock();
}
- 使用分布式RSemaphore:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RSemaphore semaphore = redisson.getSemaphore("anySemaphore");
semaphore.acquire();
try {
// do your work
} finally {
semaphore.release();
}
- 使用分布式RAtomicLong:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient redisson = Redisson.create(config);
RAtomicLong atomicLong = redisson.getAtomicLong("anyAtomicLong");
atomicLong.incrementAndGet();
long value = atomicLong.get();
以上
评论已关闭