Here I will briefly introduce the basic usage in my project. The redis service adopts the three master and three slave mode.
1. The configuration file code is as follows:
package ;
import ;
import ;
import ;
/**
* @author whb
* @date February 2, 2018 3:14:54 pm
* @Description: Redis's cluster configuration (and other master-slave configurations BaseMasterSlaveServersConfig, etc.)
*/
@Configuration
@ConfigurationProperties(prefix = "")
public class ClusterServerConfigProperties extends ClusterServersConfig {
}
2. The initialization file is as follows:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* @author whb
* @date February 2, 2018 3:16:25 pm
* @Description: Distributed locks solve resource competition problems
*/
@Configuration
@ConditionalOnClass()
@EnableConfigurationProperties()
public class EnableRedissonAutoConfiguration {
/** Cluster configuration */
@Autowired
private ClusterServerConfigProperties clusterServerConfigProperties;
/**
* Automatic assembly in cluster mode
* @return
*/
@Bean
@Primary
//@ConditionalOnExpression("'${}'=='10000'")
@ConditionalOnProperty(prefix = "",name = "startup",matchIfMissing = false)
public RedissonClient redissonCluster() {
Config config = new Config();
ClusterServersConfig serverConfig = ();
(clusterServerConfigProperties,serverConfig);
List<URI> nodeAddresses = ();
int size = ();
String[] address = new String[size];
for(int i=0;i<size;i++){
address[i] = (i).toString();
}
(address);
return (config);
}
}
3. The usage tutorial is as follows:
@Autowired
RedissonClient redissonClient;
public void getLock(){
RLock lock = ("123");
try{
boolean b = (5, 20, );
if(!b){
throw new RuntimeException("-------------");
}
(500L);
} catch (InterruptedException e) {
();
} finally {
();
}
}
4. The basic use of Redission is as follows:
Introduction
Redisson - is a high-level distributed coordinated Redis client service, which can help users easily implement some Java objects in a distributed environment (Bloom filter, BitSet, Set, SetMultimap, ScoredSortedSet, SortedSet, Map, ConcurrentMap, List, ListMultimap, Queue, BlockingQueue, Deque, BlockingDeque, Semaphore, Lock, ReadWriteLock, AtomicLong, CountDownLatch, Publish / Subscribe, HyperLogLog).
Supports Redis connection modes
Cluster mode
Config config = new Config()
config.useClusterServers()
.setScanInterval(2000) // cluster state scan interval in milliseconds
.addNodeAddress("127.0.0.1:7000", "127.0.0.1:7001")
.addNodeAddress("127.0.0.1:7002")
RedissonClient redisson = Redisson.create(config)
Singleton mode
// connects to 127.0.0.1:6379 by default
RedissonClient redisson = Redisson.create()
Config config = new Config()
config.useSingleServer().setAddress("myredisserver:6379")
RedissonClient redisson = Redisson.create(config)
Sentinel mode
Config config = new Config()
config.useSentinelServers()
.setMasterName("mymaster")
.addSentinelAddress("127.0.0.1:26389", "127.0.0.1:26379")
.addSentinelAddress("127.0.0.1:26319")
RedissonClient redisson = Redisson.create(config)
Master-slave mode
Config config = new Config()
config.useMasterSlaveServers()
.setMasterAddress("127.0.0.1:6379")
.addSlaveAddress("127.0.0.1:6389", "127.0.0.1:6332", "127.0.0.1:6419")
.addSlaveAddress("127.0.0.1:6399")
RedissonClient redisson = Redisson.create(config)
Operation execution
Redisson supports automatic retry policy, default is to retry 3 times, with an interval of 1000ms. In addition to supporting synchronous operations, it also supports asynchronous methods and response methods.
RedissonClient client = (config);
RAtomicLong longObject = client.getAtomicLong('myLong');
(3, 401);
(3, 401);
RedissonReactiveClient client = (config);
RAtomicLongReactive longObject = client.getAtomicLong('myLong');
(3, 401);
Various serial numbering methods
Codec class name Description
Jackson JSON codec. Default codec
CBOR binary json codec
MsgPack binary json codec
Kryo binary codec
JDK Serialization codec
FST up to 10 times faster and 100% JDK Serialization compatible codec
.LZ4Codec LZ4 compression codec
Snappy compression codec
String codec
Long codec
Distributed Objects
Distributed Object
RBucket<AnyObject> bucket = ("anyObject");
bucket.set(new AnyObject(1));
AnyObject obj = bucket.get();
(new AnyObject(3));
(new AnyObject(4), new AnyObject(5));
(new AnyObject(6));
Distributed BitSet
RBitSet set = ("simpleBitset");
set.set(0, true);
set.set(1812, false);
set.clear(0);
set.addAsync("e");
set.xor("anotherBitset");
Distributed Lock
Redisson redisson = Redisson.create();
RLock lock = ("anyLock");
// Most familiar locking method
lock.lock();
// Lock time-to-live support
// releases lock automatically after 10 seconds
// if unlock method not invoked
lock.lock(10, );
// Wait for 100 seconds and automatically unlock it after 10 seconds
boolean res = lock.tryLock(100, 10, );
...
lock.unlock();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Distributed MultiLock
RLock lock1 = ("lock1");
RLock lock2 = ("lock2");
RLock lock3 = ("lock3");
RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
lock.lock();
Distributed ReadWriteLock
RReadWriteLock rwlock = redisson.getLock("anyRWLock")
// Most familiar locking method
rwlock.readLock().lock()
// or
rwlock.writeLock().lock()
// Lock time-to-live support
// releases lock automatically after 10 seconds
// if unlock method not invoked
rwlock.readLock().lock(10, TimeUnit.SECONDS)
// or
rwlock.writeLock().lock(10, TimeUnit.SECONDS)
// Wait for 100 seconds and automatically unlock it after 10 seconds
boolean res = rwlock.readLock().tryLock(100, 10, TimeUnit.SECONDS)
// or
boolean res = rwlock.writeLock().tryLock(100, 10, TimeUnit.SECONDS)
...
lock.unlock()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
Distributed Semaphore
RSemaphore semaphore = redisson.getSemaphore("semaphore")
semaphore.acquire()
semaphore.acquire(23)
semaphore.tryAcquire()
semaphore.tryAcquire(23, TimeUnit.SECONDS)
semaphore.release(10)
semaphore.release()
Distributed AtomicLong
RAtomicLong atomicLong = redisson.getAtomicLong("myAtomicLong")
atomicLong.set(3)
atomicLong.incrementAndGet()
atomicLong.get()
Distributed AtomicDouble
RAtomicDouble atomicDouble = redisson.getAtomicDouble("myAtomicDouble")
atomicDouble.set(2.81)
atomicDouble.addAndGet(4.11)
atomicDouble.get()
Distributed CountDownLatch
RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch")
latch.trySetCount(1)
latch.await()
// in other thread or other JVM
RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch")
latch.countDown()
Topic
RTopic<SomeObject> topic = ("anyTopic");
(new MessageListener<SomeObject>() {
@Override
public void onMessage(String channel, SomeObject message) {
//...
}
});
// in other thread or JVM
RTopic<SomeObject> topic = ("anyTopic");
long clientsReceivedMessage = (new SomeObject());
Topic patttern
RPatternTopic<Message> topic1 = ("topic1.*");
int listenerId = (new PatternMessageListener<Message>() {
@Override
public void onMessage(String pattern, String channel, Message msg) {
();
}
});
Distributed Collections
Distributed Map
In addition, Multimap is also supported, not listed here
RMap<String, SomeObject> map = redisson.getMap("anyMap");
SomeObject prevObject = map.put("123", new SomeObject());
SomeObject currentObject = map.putIfAbsent("323", new SomeObject());
SomeObject obj = map.remove("123");
map.fastPut("321", new SomeObject());
map.fastRemove("321");
Future<SomeObject> putAsyncFuture = map.putAsync("321");
Future<Void> fastPutAsyncFuture = map.fastPutAsync("321");
map.fastPutAsync("321", new SomeObject());
map.fastRemoveAsync("321");
Map eviction
Now Redis does not have the function of clearing an entry in the map after expiration, it can only clear all entry in the map. Redission provides this capability.
RMapCache<String, SomeObject> map = redisson.getMapCache("anyMap");
map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES);
map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);
map.putIfAbsent("key2", new SomeObject(), 3, TimeUnit.SECONDS);
map.putIfAbsent("key2", new SomeObject(), 40, TimeUnit.SECONDS, 10, TimeUnit.SECONDS);
Distributed Set
RSet<SomeObject> set = redisson.getSet("anySet")
set.add(new SomeObject())
set.remove(new SomeObject())
In addition, it also supports Set eviction, SortedSet, ScoredSortedSet, LexSortedSet
Distributed List
RList<SomeObject> list = ("anyList");
list.add(new SomeObject());
list.get(0);
list.remove(new SomeObject());
Distributed Blocking Queue
RBlockingQueue<SomeObject> queue = redisson.getBlockingQueue("anyQueue")
queue.offer(new SomeObject())
SomeObject obj = queue.peek()
SomeObject someObj = queue.poll()
SomeObject ob = queue.poll(10, TimeUnit.MINUTES)
In addition, Queue, Deque, Blocking Deque is also supported
Other features
Execute batch commands
RBatch batch = redisson.createBatch()
batch.getMap("test").fastPutAsync("1", "2")
batch.getMap("test").fastPutAsync("2", "3")
batch.getMap("test").putAsync("2", "5")
batch.getAtomicLongAsync("counter").incrementAndGetAsync()
batch.getAtomicLongAsync("counter").incrementAndGetAsync()
List<?> res = batch.execute()