Redisson
是一个 Java 的 Redis 客户端,基于 Redis 实现了许多分布式数据结构和功能,例如分布式锁、缓存、限流器、布隆过滤器等。
以下是一些常见的 Redisson
使用示例,来自ChatGPT,用于自学。
Redisson 提供了 RLock
接口用于实现分布式锁,适用于需要同步访问共享资源的分布式应用场景。
Redisson 提供了 RMap
,可以在 Redis 中存储键值对,类似于 Java 的 Map
,但支持分布式。
Redisson 支持布隆过滤器(RBloomFilter
),可用于检测一个元素是否在集合中。
它适用于需要快速判断某元素是否存在于某集合的场景。
Redisson 提供了 RRateLimiter
接口,可用于实现限流功能,控制某一资源的访问速率。
Redisson 也支持发布/订阅模式的分布式消息队列,可以用于事件驱动的应用程序。
Redisson 提供的 RMapCache
支持自动过期和最大容量控制,可用于分布式缓存。
public static void main(String[] args) {
// Create a Config instance and configure Redis connection
Config config = new Config();
config.useSingleServer().setAddress("redis://" + REDIS_HOST + ":" + REDIS_PORT).setPassword(redisPassword);
// Create a RedissonClient instance
RedissonClient redissonClient = Redisson.create(config);
// use redissonClient to perform Redis operations
// Example1: get a distributed lock
RLock lock = redissonClient.getLock("myLock");
try {
// Attempt to add a lock and set the automatic expiration time of the lock to 10 seconds
if (lock.tryLock()) {
System.out.println("Successfully get lock, execute business logic");
Thread.sleep(5000); // Simulate task execution
} else {
System.out.println("Can not get lock, execute other logic");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// release lock
lock.unlock();
}
// Example2: get RMap object
RMap<String, String> map = redissonClient.getMap("myMap");
//put data into the map
map.put("name", "Alice");
map.put("city", "New York");
System.out.println("Name: " + map.get("name"));
System.out.println("City: " + map.get("city"));
// Example3: get RBloomFilter object
RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("myBloomFilter");
// initialize BloomFilter, set the expected number of elements to 10000 and the false positive probability to 0.01
bloomFilter.tryInit(10000, 0.01);
// add elements to BloomFilter
bloomFilter.add("Alice");
bloomFilter.add("Bob");
// check if elements exist in BloomFilter
System.out.println("Alice exist: " + bloomFilter.contains("Alice"));
System.out.println("Eve exist: " + bloomFilter.contains("Eve"));
// Example4:get RateLimiter object
RRateLimiter rateLimiter = redissonClient.getRateLimiter("myRateLimiter");
// set the rate limit to 5 permits per second
rateLimiter.trySetRate(RateType.OVERALL, 5, 1, RateIntervalUnit.SECONDS);
for (int i = 0; i < 10; i++) {
// try to acquire a permit
if (rateLimiter.tryAcquire()) {
System.out.println("the " + i + " operation is allowed");
} else {
System.out.println("the " + i + " operation was limited in current");
}
}
// Example5: get Topic object
RTopic topic = redissonClient.getTopic("myTopic");
// subscribe to a message
topic.addListener(String.class, new MessageListener<String>() {
@Override
public void onMessage(CharSequence channel, String message) {
System.out.println("Received message:" + message);
}
});
// publish message to the topic
topic.publish("Hello, Redis!");
// Example6: get RMapCache object
RMapCache<String, String> cache = redissonClient.getMapCache("myCache");
// put data into the cache
cache.put("key1", "value1", 10, TimeUnit.SECONDS); // Expires in 10 seconds
System.out.println("Key1: " + cache.get("key1"));
// Delay access for a few seconds and verify expiration time
try {
Thread.sleep(11000); // Delay 11s
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Key1 after 11 seconds: " + cache.get("key1")); // out put null(Expired)
// close RedissonClient
redissonClient.shutdown();
}
> Task :RedissonExample.main()
Successfully get lock, execute business logic
Name: Alice
City: New York
Alice exist: true
Eve exist: false
the 0 operation is allowed
the 1 operation is allowed
the 2 operation is allowed
the 3 operation is allowed
the 4 operation is allowed
the 5 operation is allowed
the 6 operation is allowed
the 7 operation is allowed
the 8 operation is allowed
the 9 operation is allowed
Received message:Hello, Redis!
Key1: value1
Key1 after 11 seconds: null